> This is part 1 of 4 of the full documentation (pages 1–100 of 355).
> The content is paginated: fetch every part to see all of it.
> Next part: https://fto-2.gitbook.io/fto-indicators-docs/llms-full.txt/1
> Page index: https://fto-2.gitbook.io/fto-indicators-docs/llms.txt

> Agents can also search and read this documentation through its [MCP server](https://fto-2.gitbook.io/fto-indicators-docs/~gitbook/mcp).

# Overview

Build custom indicators for Forex Tester Online.

Create, build, and upload TypeScript indicators that turn chart data into reusable calculations and visual signals.

## Start here

| Goal                      | Page                                                                                                                  |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| First build and upload    | [Open and upload an indicator](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator)                |
| Author with Cursor AI     | [Create an indicator with Cursor](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor) |
| Download working examples | [Download indicator examples](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators)                       |

## How indicators work

An indicator is a TypeScript class that extends `Indicator`. In `OnInit`, it registers inputs and can set up plots or chart objects. `OnCalculate` updates the relevant bar values or objects as chart history changes. Parameter changes, visibility, and cleanup have their own optional [lifecycle hooks](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle).

## API reference

The [API reference](https://fto-2.gitbook.io/fto-indicators-docs/api-reference) covers lifecycle hooks, inputs, plots, market data, chart tools, and utilities.

Recommended first reads:

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [Plot setup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup)


# Open and upload an indicator

Set up, build, and upload a custom FTO indicator.

Get a compiled `.js` file from a local TypeScript project into Forex Tester Online.

## What you need

* [Cursor](https://www.cursor.com/downloads) or another TypeScript IDE
* Current LTS [Node.js](https://nodejs.org/en)
* The starter ZIP on [Set up an indicator](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/set-up-indicator)

## Steps

1. [Set up an indicator](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/set-up-indicator) — download the starter, install dependencies, and run `npm run build`.
2. Implement a default-exported class extending `Indicator` with `OnInit` and `OnCalculate`. Use the complete [Step 5 indicator example](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-5-start-building) as a reference.
3. Run `npm run build` again after editing the source.
4. [Upload the compiled file to FTO](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/upload-indicator-to-fto) from `dist`, not the `.ts` source.

This is the setup and upload path for FTO indicators. For AI-assisted authoring, continue with [Create an indicator with Cursor](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor).


# Set up an indicator

Get a local TypeScript project that compiles to a `.js` file you can upload to Forex Tester Online.

## What you will have when finished

* Dependencies installed from the starter package
* A successful `npm run build`
* `dist/my-indicator-project.js` ready for [Upload indicator to FTO](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/upload-indicator-to-fto)

## 1. Download and open the starter

{% file src="/files/OknB2nxnfNEhznjvR72T" %}

Extract the zip, then open the folder in Cursor or another TypeScript IDE.

## 2. Install dependencies

In the project terminal:

```bash
npm install
```

{% hint style="warning" %}
If PowerShell blocks `npm.ps1`, call the Windows command shim directly instead:

```bash
npm.cmd install
npm.cmd run build
```

This does not change the PowerShell execution policy.
{% endhint %}

## 3. Build

```bash
npm run build
```

The build writes `my-indicator-project.js` under `dist`. The project dependency provides the `Indicator` base class, API methods, and public types you import in code.

{% hint style="warning" %}
FTO loads exactly one default-exported class from the compiled file:

```typescript
export default class MyIndicator extends Indicator {
    // ...
}
```

Without `export default`, upload may succeed but the indicator will not run.
{% endhint %}

## Next step

The starter has empty lifecycle methods: a successful build does not create a plotted line or any settings inputs. To see a calculated result, replace its source with the [working indicator example](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-5-start-building), build again, and then [upload it to FTO](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/upload-indicator-to-fto).

You can also upload the empty starter to check that the file loads; a blank chart is expected at that checkpoint.


# Upload an indicator to FTO

Get your compiled indicator running on a chart in FTO.

## What you will have when finished

* The indicator listed under **My Indicators**
* The plots and inputs that your code registers; the empty starter intentionally has neither

## 1. Build the project

In your indicator project terminal:

```bash
npm run build
```

The build writes `my-indicator-project.js` under `dist`.

## 2. Upload the compiled file

In FTO, open the indicator menu and choose **Upload Indicator**.

Drop `dist/my-indicator-project.js` into the upload area, or click the area to browse for one or more `.js` files.

{% hint style="warning" %}
Upload the compiled `.js` from `dist`, not the TypeScript source. If upload fails, rebuild and try the fresh file.
{% endhint %}

{% hint style="warning" %}
The compiled file must contain one default-exported class that extends `Indicator` (`export default class … extends Indicator`). Without a default export, FTO will not run the indicator even if the upload appears to succeed.
{% endhint %}

## 3. Add it to a chart

After upload, find the indicator under **My Indicators** and attach it to the chart like any built-in indicator.

If you built the unchanged empty starter, it will not draw a line. Use the [working example](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-5-start-building) to verify calculation and plotting. Check its configured period, the available history, and the first calculated values; uploading alone does not populate buffers.

## Next step

Browse [downloadable indicator examples](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators) for calculations you can adapt in your project, or open the [API reference](https://fto-2.gitbook.io/fto-indicators-docs/api-reference) to extend what you uploaded.


# Create an indicator with Cursor

Build your first FTO custom indicator with Cursor.

Go from an empty starter project to a compiled indicator you can upload — with Cursor helping on each step.

## What you will have when finished

* Cursor installed with the FTO starter project open
* An active project rule with the Indicators GitBook URL, created through the Rules UI or as a `.mdc` file
* The target `.ts` file attached in Agent chat, with relevant documentation pages supplied as extra context when useful
* A working moving-average example built, compiled, and ready to upload

## Steps

1. [Install Cursor and set up the project](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-1-install-cursor-and-set-up-the-project)
2. [Apply project rules](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-2-apply-cursor-rules)
3. [Give Cursor the FTO indicator docs](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-3-give-cursor-the-fto-indicator-docs)
4. [Get familiar with Cursor](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-4-get-familiar-with-cursor)
5. [Build your first indicator](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-5-start-building)
6. Read the [recommendations](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/recommendations) before your second indicator

This tutorial uses the `Indicator` base class with `OnInit` and `OnCalculate`. Keep [indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle) and [plot setup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup) open while you work through step 5.


# Step 1: Install Cursor and set up the project

Install the editor and starter package before you write any indicator code.

## What you will have when finished

* Cursor and Node.js installed
* The FTO indicator starter extracted and open in Cursor
* Dependencies installed with `npm install`
* A successful `npm run build`

## 1. Install tools

Install [Cursor](https://www.cursor.com/downloads) and the current LTS release of [Node.js](https://nodejs.org/en).

## 2. Open the starter project

Download the starter from [Set up an indicator](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/set-up-indicator), extract the zip, and open the folder in Cursor.

## 3. Install dependencies

In Cursor's terminal:

```bash
npm install
```

This installs the package with the `Indicator` base class, `this.api` helpers, and TypeScript types.

## 4. Confirm the project builds

```bash
npm run build
```

The build writes `dist/my-indicator-project.js`. If PowerShell blocks `npm.ps1`, follow the PowerShell note on [Set up an indicator](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/set-up-indicator).

## Next step

[Apply project rules](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-2-apply-cursor-rules)


# Step 2: Apply Cursor rules

Give Cursor the current FTO indicator conventions.

Add a project rule so Cursor-generated code matches FTO indicator expectations.

## Where to put the rule

Use a **Project Rule** for FTO-specific instructions. Choose either method below: both create a `.mdc` file in this project's `.cursor/rules/` folder.

### Option 1: Create it through Cursor

1. Open **Cursor Settings → Customize → Rules**, then **Add Rule** and create a project rule such as `fto-indicator-rules`.
2. Open the generated `.mdc` and paste the template below, including the frontmatter.
3. Set the rule type to **Always Apply** and save. This corresponds to `alwaysApply: true` in the file.

### Option 2: Create the file manually

Create `.cursor/rules/fto-indicator-rules.mdc` in your project and paste the complete template, keeping `alwaysApply: true`. You do not need a second copy through the UI.

### Optional: User Rules

You can also add instructions through **User Rules** in the same UI. Use plain text without the template's YAML frontmatter. User Rules apply across all projects, so a project rule is preferable for FTO. If using a User Rule, qualify it with “When working on FTO indicators…” and include the documentation URL. See [Cursor's Rules documentation](https://cursor.com/docs/rules).

## Docs URL inside the rule

The template already contains the Indicators GitBook URL. Keep it in this rule; a separate documentation rule is not required.

When the rule is active, you do not need to paste the homepage URL into every prompt. A link to a relevant API page can still provide useful extra context. The saved URL is a pointer, not a downloaded copy of the book: Agent must read the pages needed for the task. See [Step 3](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-3-give-cursor-the-fto-indicator-docs).

## Rule should require

* Extend the exported `Indicator` base class and use a **default export**.
* Implement `public override OnInit(): void` and `public override OnCalculate(index: number): void`.
* Create inputs and buffers during `OnInit`; register plots and set styles there.
* Declare inputs and buffers as class-level fields (for example `public Period!: InputNumber`).
* Read live input values with `.value` in `OnCalculate` / `OnParamsChange` — do not cache `.value` in `OnInit`.
* Treat bar index `0` as the newest bar; larger indexes move backward in time.
* Clean up chart objects in `OnDeinit` (and suppress redraw in `OnHide` when needed).
* Call only methods and public types documented in this GitBook.

## Copy-paste `.mdc` template

```
---
description: FTO indicator authoring conventions for Agent mode
alwaysApply: true
---

When working on FTO indicators in this project, follow the official documentation:
https://fto-2.gitbook.io/fto-indicators-docs
Read the relevant documentation pages before implementing or fixing indicator code. Do not invent API methods. If the pages are inaccessible, ask the user for the relevant excerpt.

An FTO indicator is a TypeScript class that must extend Indicator.

Import Indicator and API types from the project dependency (forex-tester-custom-indicator-api or the name in package.json).

The class must be a default export:
export default class MyIndicator extends Indicator { ... }
Without export default, FTO will not load the indicator.

Required lifecycle methods (declare as public override):
- OnInit(): void — create inputs/buffers, register plots, set name and styles
- OnCalculate(index: number): void — compute and write buffer values for one bar

Optional overrides only when needed (also public override):
- OnParamsChange() — react after the user changes inputs
- OnShow() / OnHide() — visibility hooks
- OnDeinit() — cleanup (delete chart objects you created)

Parameters:
- Declare as class-level fields with ! (example: public Period!: InputNumber)
- Create in OnInit with typed Create*Input helpers (CreateIntegerInput, CreateBoolInput, ...)
- Read with .value in OnCalculate — never cache .value into locals in OnInit for later use

Buffers / plots:
- Declare as class-level buffer fields with !
- Create buffers, set plot count, bind with CreatePlot / SetPlotBuffer as documented
- Write with buffer.setValue(index, value); read with buffer.getValue(index)

Bar indexing:
- index 0 is the newest (rightmost) bar
- index + 1 is the previous bar
- Guard history reads before accessing index + period

General:
- Do not invent API methods
- Call RecalculateMeAlways() in OnInit only when each bar depends on earlier bars in the same pass (recursive or stateful math). Skip it for simple lookback averages unless you need every bar recalculated.
- Use only methods and public types from the FTO Indicators GitBook above
```

## Next step

[Give Cursor the FTO indicator docs](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-3-give-cursor-the-fto-indicator-docs)


# Step 3: Give Cursor the FTO indicator docs

Keep the documentation URL in the [rule from Step 2](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-2-apply-cursor-rules), whether you added it through the UI or manually. An active rule makes repeating the homepage URL in every prompt unnecessary.

## Docs URL

<https://fto-2.gitbook.io/fto-indicators-docs>

## What to do

1. Confirm the rule containing the URL is active. The Step 2 template already includes it; no separate rule is needed.
2. Attach your indicator `.ts` file and ask Agent to read the documentation relevant to the change.
3. Optionally add a specific API page link in chat for extra context — for example:

* [Inputs](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs) for parameters
* [Current symbol](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/current-symbol) for price access
* [Plots and buffers](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers) for output lines

{% hint style="info" %}
Rules provide instructions and a URL; they do not automatically load the entire GitBook. Agent must open the needed pages. If it cannot access them, paste the relevant excerpt instead of letting it guess. Cursor Settings → Docs indexing is not required for this workflow.
{% endhint %}

## Next step

[Get familiar with Cursor](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-4-get-familiar-with-cursor)


# Step 4: Get familiar with Cursor

Use **Agent** mode to implement, build, and fix your indicator in small verified steps.

{% hint style="info" %}
Cursor’s chat chrome changes often. Exact shortcuts and mode names may differ from older guides — stay on **Agent** when you want file edits and terminal commands.
{% endhint %}

## What to do in your first session

1. Open Cursor chat and switch to **Agent** mode when you want file edits and terminal commands.
2. Describe the indicator plainly: calculation formula, inputs, output window, number of plots, and behavior on the oldest bars.
3. Attach the target `.ts` file and keep the Indicators rule active. Add a relevant documentation page link in chat when useful; see [Step 3](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-3-give-cursor-the-fto-indicator-docs).
4. Ask Cursor to run `npm run build` after each change and fix only errors it introduced.

## Prompt tips that work

* State the period defaults and whether the indicator overlays price or uses a separate pane.
* Mention lookback guards when the math reads history — span loops use `index + period > Bars()`, direct access of `index + period` uses `>=`.
* Request the smallest working version first — add inputs and styling after the core line calculates.

## Next step

[Build your first indicator](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-5-start-building)


# Step 5: Build your first indicator

Implement a complete moving average, compile it, and upload the result to FTO.

## What you will have when finished

* A moving-average indicator using inputs, one buffer, and one plot
* A successful `npm run build`
* `dist/my-indicator-project.js` ready for [Upload indicator to FTO](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/upload-indicator-to-fto)

## Reference implementation

```typescript
import {
    Indicator,
    IndexBuffer,
    InputNumber,
    PenStyle,
    PlotType
} from 'forex-tester-custom-indicator-api'

export default class MovingAverageIndicator extends Indicator {
    public Period!: InputNumber
    public Buffer!: IndexBuffer

    public override OnInit(): void {
        this.api.SetIndicatorShortName('Moving Average')
        this.Period = this.api.CreateIntegerInput('Period', 14, 1, 500)
        this.Buffer = this.api.CreateBuffer()
        this.api.SetPlotCount(1)
        this.api.CreatePlot(
            0, this.Buffer, 'MA', PlotType.LINE, PenStyle.SOLID, 1, '#2962FF'
        )
        this.api.SetPlotDrawBegin(0, this.Period.value - 1)
    }

    public override OnParamsChange(): void {
        this.api.SetPlotDrawBegin(0, this.Period.value - 1)
    }

    public override OnCalculate(index: number): void {
        if (index + this.Period.value > this.api.Bars()) return
        let sum = 0
        for (let offset = 0; offset < this.Period.value; offset += 1) {
            sum += this.api.Close(index + offset)
        }
        this.Buffer.setValue(index, sum / this.Period.value)
    }
}
```

Bar index `0` is the newest bar, so lookback uses `index + offset`. Read [bar indexing](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/current-symbol/bar-indexing) before adapting the loop.

## Build and upload

```bash
npm run build
```

Then follow [Upload indicator to FTO](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/upload-indicator-to-fto).

## Next step

Review [recommendations](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/recommendations) before starting a second indicator.


# Recommendations

Practices that keep Cursor-assisted indicator work predictable.

## Prompting

* Name every input, plot, and edge case (empty history, separate window, level lines).
* Link the exact API pages Cursor must follow — do not rely on memory.
* Ask for the smallest working version first, then iterate on styling and extras.

## Build loop

* Run `npm run build` after each meaningful change.
* Fix compile errors before asking for new features.
* Spot-check values on a chart you know — compare a few bars by hand.

## Performance

* Keep `OnCalculate` lean; it runs for every bar in range.
* Use hidden buffers for intermediate values instead of duplicate plot series.
* Call [RecalculateMeAlways](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-me-always) only when stateful math requires it.

## After the first indicator

Browse [downloadable indicator examples](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators) for patterns close to your next idea instead of prompting from scratch.


# Download indicator examples

Download indicator projects you can build, study, and adapt.

Download complete indicator projects, including recreations of FTO's built-in indicators and an object-only panel. Build them locally, then upload or adapt the code for your own indicator.

## What you can do with these examples

1. Download a ZIP, run `npm install`, and `npm run build` to verify your toolchain.
2. Read **When to copy this pattern** on each page before diving into code.
3. Upload the compiled `.js` or strip the math into your own indicator class.

Each ZIP uses `forex-tester-custom-indicator-api` `^3.0.1`. The matching page shows the same current-API implementation pattern. Most examples use `CreateBuffer` and plots; Market Conditions Panel, Pivot Points High/Low, and Round Numbers demonstrate chart objects without buffers.

## Available examples

| Indicator                                                                                                           | Description                                                     |
| ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| [ATR](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/atr)                                         | Average True Range volatility line in a separate pane.          |
| [Bollinger Bands](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/bollinger-bands)                 | Moving average with upper and lower standard-deviation bands.   |
| [CCI](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/cci)                                         | Commodity Channel Index oscillator with typical levels.         |
| [Doji](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/doji)                                       | Marks Doji candlestick patterns on the chart.                   |
| [Donchian Channel](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/donchian-channel)               | Highest high and lowest low over a lookback window.             |
| [Engulfing Bar](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/engulfing-bar)                     | Bullish and bearish engulfing pattern markers.                  |
| [Fractals](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/fractals)                               | Bill Williams fractal swing markers.                            |
| [MACD](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/macd)                                       | MACD line, signal, and histogram in a separate pane.            |
| [Rate of Change](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/rate-of-change)                   | Momentum as percent change over a period.                       |
| [RCI](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/rci)                                         | Rank Correlation Index oscillator.                              |
| [Rolling VWAP](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/rolling-vwap)                       | Volume-weighted average price over a rolling window.            |
| [Supertrend](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/supertrend)                           | ATR-based trend overlay on price.                               |
| [TDI](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/tdi)                                         | Traders Dynamic Index — RSI, signal, and volatility bands.      |
| [Market Conditions Panel](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/market-conditions-panel) | An object-only chart panel with MA, RSI, ADX, and ATR readings. |
| [Pivot Points High/Low](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/pivot-points-high-low)     | Price labels at confirmed pivot highs and lows.                 |
| [Round Numbers](https://fto-2.gitbook.io/fto-indicators-docs/built-in-indicators/round-numbers)                     | Horizontal lines at psychological price levels.                 |

After building, [upload the generated file](https://fto-2.gitbook.io/fto-indicators-docs/open-and-upload-indicator/upload-indicator-to-fto).


# ATR

ATR (Average True Range) built-in indicator — download the project and explore volatility measurement on the chart.

**Average True Range (ATR)** measures market volatility by averaging the true range over a selected period. Traders use it for stop placement, position sizing, and volatility filters.

***

## When to copy this pattern

Copy ATR when you need a volatility line in a separate pane, true-range math with a hidden working buffer, or MA-type smoothing with back offset updated in `OnParamsChange`.

## Download

{% file src="/files/7FpQctORYoxTDi2tJ9IJ" %}

***

## What you can learn

* True range from high, low, and prior close
* Hidden `TrueRange` buffer smoothed into visible ATR output
* MA-type switch (SMA, EMA, SMMA, LWMA) with back-offset calculation in `OnParamsChange`

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                      |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Period controls the window; Method selects smoothing; Apply to price chooses the previous-bar reference for true range.       |
| Output                 | One separate-pane ATR line and one hidden true-range buffer.                                                                  |
| History and edge cases | The oldest bar seeds true range from high minus low. Smoothed startup values can be partial before sufficient history exists. |

## Pattern to reuse

Compute true range into a scratch buffer, smooth it with the selected MA type into a separate-window ATR plot, and refresh back offset in `OnParamsChange`.

```typescript
export default class ATR extends Indicator {
    // inputs
    public Period!: InputNumber
    public ApplyToPrice!: InputEnum<PriceType>
    public Method!: InputEnum<MovingAverageType>
    // buffers
    public ATRBuffer!: IndexBuffer
    public TrueRange!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('ATR')
        this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
        this.api.AddLevel(0, PenStyle.DOT, 1, '#ada9a9')
        this.api.RecalculateMeAlways()

        // register input parameters
        this.Period = this.api.CreateIntegerInput('Period', 14, 1, 1000)
        this.Method = this.api.CreateMATypeInput('', MovingAverageType.SMMA)
        this.ApplyToPrice = this.api.CreateApplyToPriceInput('Apply to price', PriceType.CLOSE)

        // create all buffers
        this.ATRBuffer = this.api.CreateBuffer()
        this.TrueRange = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(1)

        this.api.CreatePlot(
            0,
            this.ATRBuffer,
            'ATR',
            PlotType.LINE,
            PenStyle.SOLID,
            1,
            '#ff0000'
        )
    }

    public OnCalculate(index: number): void {
        const high = this.api.High(index)
        const low = this.api.Low(index)

        if (index === this.api.Bars() - 1) {
            this.TrueRange.setValue(index, high - low)
        } else {
            const prevPrice = this.api.GetPrice(index + 1, this.ApplyToPrice.value)
            this.TrueRange.setValue(index, Math.max(high, prevPrice) - Math.min(low, prevPrice))
        }

        this.MAOnBuffer(index, this.TrueRange, this.Period.value, this.ATRBuffer)
    }

    public OnParamsChange(): void {
        const backOffset = this.calculateMABackOffset(this.Method.value, this.Period.value, 2)
        this.api.SetIndicatorBackOffset(backOffset)
    }

    private MAOnBuffer(index: number, source: IndexBuffer, period: number, out: IndexBuffer): void {
        switch (this.Method.value) {
            case MovingAverageType.SMA: {
                this.SMA(index, source, period, out)
                break
            }
            case MovingAverageType.EMA: {
                this.EMA(index, source, period, out)
                break
            }
            case MovingAverageType.SMMA: {
                this.SMMA(index, source, period, out)
                break
            }
            case MovingAverageType.LWMA: {
                this.LWMA(index, source, period, out)
                break
            }
            default: {
                this.SMA(index, source, period, out)
                break
            }
        }
    }

    private EMA(index: number, source: IndexBuffer, period: number, out: IndexBuffer): void {
        const alpha = 2.0 / (period + 1.0)
        const prev = out.getValue(index + 1) || this.SMA(index, source, period)
        const value = alpha * source.getValue(index) + (1 - alpha) * prev
        out.setValue(index, value)
    }

    private LWMA(index: number, source: IndexBuffer, period: number, out: IndexBuffer): void {
        const weight = (period * (period + 1)) / 2.0
        let sum = 0.0
        for (let i = 0; i < period; i++) {
            sum += source.getValue(index + i) * (period - i)
        }
        out.setValue(index, sum / weight)
    }

    private SMMA(index: number, source: IndexBuffer, period: number, out: IndexBuffer): void {
        const prev = out.getValue(index + 1) || this.SMA(index, source, period)
        const value = (prev * (period - 1) + source.getValue(index)) / period
        out.setValue(index, value)
    }

    private SMA(index: number, source: IndexBuffer, period: number, out?: IndexBuffer): number {
        let sum = 0.0
        for (let i = 0; i <= period - 1; i++) {
            sum += source.getValue(index + i)
        }
        if (out) {
            out.setValue(index, sum / period)
        }
        return sum / period
    }

    private calculateMABackOffset(method: MovingAverageType, period: number, precision: number): number {
        const maxLookback = 1000
        const nPeriod = Math.min(Math.max(period, 1), maxLookback)
        switch (method) {
            case MovingAverageType.EMA:
            case MovingAverageType.SMMA: {
                const epsilon = Math.pow(10, -Math.max(precision, 1))
                const alpha = method === MovingAverageType.EMA ? 2 / (nPeriod + 1) : 1 / nPeriod
                if (alpha >= 1 - Number.EPSILON) {
                    return 1
                }
                const k = Math.ceil(Math.log(epsilon) / Math.log1p(-alpha))
                return Math.min(k, maxLookback)
            }
            default: {
                return nPeriod
            }
        }
    }
}
```


# Bollinger Bands

Bollinger Bands built-in indicator — download the project and explore price channels based on standard deviation.

**Bollinger Bands** plot upper and lower bands around a moving average using standard deviation. They help identify volatility expansion, contraction, and potential mean-reversion zones.

***

## When to copy this pattern

Copy Bollinger Bands when you need three overlay lines on price — middle MA plus upper and lower bands scaled by standard deviation.

## Download

{% file src="/files/kjKfDvhqobwu1TPr4RMV" %}

***

## What you can learn

* Three chart-window plots from one period input
* Middle band via `GetMA` and deviation-based upper/lower bands
* Applying standard deviation multiplier as a user input

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                        |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Period/MA type define the middle line; Deviation and Std Dev Type control band width; Shift changes display placement.          |
| Output                 | Upper (slot 0), middle (1) and lower (2) chart plots.                                                                           |
| History and edge cases | The complete source window must fit. EMA/SMMA startup depends on previous-bar state; plot shift does not shift numeric storage. |

## Pattern to reuse

Build a middle band with `GetMA`, derive upper/lower bands from deviation, and wire three overlay plots from period, shift, and deviation inputs.

```typescript
enum StdDevMode {
    SOURCE_VALUES = 0,
    MA_DEVIATIONS = 1
}

export default class BollingerBands extends Indicator {
    // inputs
    public Period!: InputNumber
    public Shift!: InputNumber
    public Deviation!: InputNumber
    public MAType!: InputEnum<MovingAverageType>
    public ApplyToPrice!: InputEnum<PriceType>
    public StdDevType!: InputEnum<StdDevMode>
    // buffers
    public MABuffer!: IndexBuffer
    public UpBandBuffer!: IndexBuffer
    public DownBandBuffer!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('Bollinger Bands')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)
        this.api.RecalculateMeAlways()

        // register input parameters
        this.Period = this.api.CreateIntegerInput('Period', 8, 1, 1000)
        this.Deviation = this.api.CreateDoubleInput('Deviation', 2.0, 0.1, 200)
        this.Shift = this.api.CreateIntegerInput('Shift', 0, -1000, 1000)
        this.MAType = this.api.CreateMATypeInput('', MovingAverageType.SMA)
        this.StdDevType = this.api.CreateEnumInput(
            'Std Dev Type',
            StdDevMode.SOURCE_VALUES,
            StdDevMode,
            ['Source values', 'MA deviations']
        )
        this.ApplyToPrice = this.api.CreateApplyToPriceInput('Apply to price', PriceType.CLOSE)

        // create all buffers
        this.MABuffer = this.api.CreateBuffer()
        this.UpBandBuffer = this.api.CreateBuffer()
        this.DownBandBuffer = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(3)

        this.api.CreatePlot(0, this.UpBandBuffer, 'Upper band', PlotType.LINE, PenStyle.SOLID, 1, '#008080')
        this.api.SetPlotDrawBegin(0, this.Period.value - 1 + this.Shift.value)

        this.api.CreatePlot(1, this.MABuffer, 'MA', PlotType.LINE, PenStyle.SOLID, 1, '#008080')
        this.api.SetPlotDrawBegin(1, this.Period.value - 1 + this.Shift.value)

        this.api.CreatePlot(2, this.DownBandBuffer, 'Lower band', PlotType.LINE, PenStyle.SOLID, 1, '#008080')
        this.api.SetPlotDrawBegin(2, this.Period.value - 1 + this.Shift.value)
    }

    public OnCalculate(index: number): void {
        if (index + this.Period.value > this.api.Bars()) {
            return
        }

        const ma = this.api.GetMA(
            index,
            0,
            this.Period.value,
            this.MAType.value,
            this.ApplyToPrice.value,
            this.MABuffer.getValue(index + 1)
        )
        this.MABuffer.setValue(index, ma)

        const stdDev = this.calculateStandardDeviation(index, ma)
        this.UpBandBuffer.setValue(index, ma + stdDev * this.Deviation.value)
        this.DownBandBuffer.setValue(index, ma - stdDev * this.Deviation.value)
    }

    private calculateStandardDeviation(index: number, ma: number): number {
        if (this.StdDevType.value === StdDevMode.MA_DEVIATIONS) {
            // Standard deviation of deviations from MA
            let sumSquaredDiff = 0.0
            for (let i = 0; i < this.Period.value; i++) {
                if (index + i >= this.api.Bars()) continue
                const price = this.api.GetPrice(index + i, this.ApplyToPrice.value)
                const diff = price - ma
                sumSquaredDiff += diff * diff
            }
            return Math.sqrt(sumSquaredDiff / this.Period.value)
        } else {
            // Standard deviation of source values
            return this.StandardDeviation(index, this.ApplyToPrice.value, this.Period.value)
        }
    }

    private StandardDeviation(index: number, source: PriceType, period: number): number {
        if (period <= 0) return 0.0
        let sum = 0.0
        let counter = 0
        for (let i = 0; i < period; i++) {
            if (index + i >= this.api.Bars()) continue
            sum += this.api.GetPrice(index + i, source)
            counter++
        }
        if (counter === 0) return 0.0
        const mean = sum / period

        let sumSquaredDiff = 0.0
        for (let i = 0; i < period; i++) {
            if (index + i >= this.api.Bars()) continue
            const diff = this.api.GetPrice(index + i, source) - mean
            sumSquaredDiff += diff * diff
        }
        const variance = sumSquaredDiff / period
        return Math.sqrt(variance)
    }

    public OnParamsChange(): void {
        const backOffset = this.calculateMABackOffset(this.MAType.value, this.Period.value, 2)
        this.api.SetIndicatorBackOffset(backOffset + this.Shift.value)
        this.api.SetPlotShift(0, this.Shift.value)
        this.api.SetPlotShift(1, this.Shift.value)
        this.api.SetPlotShift(2, this.Shift.value)
        const drawBegin = this.Period.value - 1 + this.Shift.value
        this.api.SetPlotDrawBegin(0, drawBegin)
        this.api.SetPlotDrawBegin(1, drawBegin)
        this.api.SetPlotDrawBegin(2, drawBegin)
    }

    private calculateMABackOffset(method: MovingAverageType, period: number, precision: number): number {
        const maxLookback = 1000
        const nPeriod = Math.min(Math.max(period, 1), maxLookback)
        switch (method) {
            case MovingAverageType.EMA:
            case MovingAverageType.SMMA: {
                const epsilon = Math.pow(10, -Math.max(precision, 1))
                const alpha = method === MovingAverageType.EMA ? 2 / (nPeriod + 1) : 1 / nPeriod
                if (alpha >= 1 - Number.EPSILON) {
                    return 1
                }
                const k = Math.ceil(Math.log(epsilon) / Math.log1p(-alpha))
                return Math.min(k, maxLookback)
            }
            default: {
                return nPeriod
            }
        }
    }
}
```


# CCI

CCI (Commodity Channel Index) built-in indicator — download the project and explore cyclical overbought/oversold levels.

Separate-window CCI oscillator with typical-price / mean-deviation math and ±100 levels.

***

## When to copy this pattern

Copy CCI when you build a separate-window oscillator with fixed overbought/oversold levels and mean-deviation math around a typical price.

## Download

{% file src="/files/mDQocdnxE3yVjGYd24yy" %}

***

## What you can learn

* Typical price and mean deviation over a lookback period
* Separate pane with `AddLevel` lines at ±100 (and zero)
* Hidden MA buffer feeding the CCI formula

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                        |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Period controls typical-price samples.                                                                                          |
| Output                 | A separate-pane CCI line with −100, 0 and 100 levels; the MA buffer stays hidden.                                               |
| History and edge cases | Wait for the whole Period-bar window. Zero mean deviation keeps previous CCI. Empty value 0 also hides valid exact-zero output. |

## Pattern to reuse

Compute typical price and mean deviation in loops, keep a hidden MA buffer, write CCI to one separate-window plot, and mark ±100 / zero with `AddLevel`.

{% hint style="info" %}
The excerpt below includes explicit history and empty-value handling. Keep those guards when reusing the calculation.
{% endhint %}

```typescript
export default class CCI extends Indicator {
    // inputs
    public CCIPeriod!: InputNumber
    // buffers
    public CCIBuffer!: IndexBuffer
    public MABuffer!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('CCI')
        this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
        this.api.AddLevel(-100, PenStyle.DOT, 1, '#ada9a9')
        this.api.AddLevel(100, PenStyle.DOT, 1, '#ada9a9')
        this.api.AddLevel(0, PenStyle.DOT, 1, '#ada9a9')
        this.api.SetIndicatorEmptyValue(0)

        // register input parameters
        this.CCIPeriod = this.api.CreateIntegerInput('Period', 14, 1, 1000)

        // create all buffers
        this.MABuffer = this.api.CreateBuffer()
        this.CCIBuffer = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(1)

        this.api.SetPlotBuffer(0, this.CCIBuffer)
        this.api.SetPlotLabel(0, 'CCI')
        this.api.SetPlotStyle(0, PlotType.LINE, PenStyle.SOLID, 1, '#1E90FF')
    }

    public OnCalculate(index: number): void {
        // return if not enough bars (before any price reads / MA loop)
        if (index + this.CCIPeriod.value > this.api.Bars()) {
            return
        }

        // calculate MA first
        let movingAverage = 0
        for (let i = 0; i < this.CCIPeriod.value; i++) {
            movingAverage += this.api.GetPrice(index + i, PriceType.HLC3) / this.CCIPeriod.value
        }
        this.MABuffer.setValue(index, movingAverage)

        // calculate average mean deviation
        let averageDeviation = 0
        for (let i = 0; i < this.CCIPeriod.value; i++) {
            const typicalPrice = this.api.GetPrice(index + i, PriceType.HLC3)
            averageDeviation += Math.abs(typicalPrice - this.MABuffer.getValue(index)) / this.CCIPeriod.value
        }

        // calculate CCI value
        if (averageDeviation === 0) {
            this.CCIBuffer.setValue(index, this.CCIBuffer.getValue(index + 1))
        } else {
            const typicalPrice = this.api.GetPrice(index, PriceType.HLC3)
            const priceDeviation = typicalPrice - this.MABuffer.getValue(index)
            this.CCIBuffer.setValue(index, priceDeviation / (0.015 * averageDeviation))
        }
    }
}
```


# Doji

Doji built-in indicator — download the project and explore Doji candlestick pattern detection on the chart.

The **Doji** indicator highlights candlesticks where open and close are nearly equal, signaling indecision. Useful for pattern-based entries and confluence with other signals.

***

## When to copy this pattern

Copy Doji when you mark individual bars that match a candlestick rule — symbol plots at bar prices instead of continuous lines.

## Download

{% file src="/files/QLHRTUc24b4RDcwmDdNX" %}

***

## What you can learn

* Body-to-range ratio test on open, high, low, close
* Writing marker values only on matching bars
* `PlotType.SYMBOL` with empty or sentinel values elsewhere

## Inputs, output, and limits

| Topic                  | Behavior                                                                                               |
| ---------------------- | ------------------------------------------------------------------------------------------------------ |
| Inputs                 | No user inputs. Body size is limited to 5% of range; shadows must pass a balance check.                |
| Output                 | A symbol below qualifying candles; other bars contain empty value 0.                                   |
| History and edge cases | Zero-range bars, dragonfly and gravestone shapes are excluded. The marker on forming bar 0 can change. |

## Pattern to reuse

Test body-to-range and shadow balance in `OnCalculate`, write a symbol marker only on matching bars, and leave non-matches at the empty value.

```typescript
interface CandleStructure {
    bodyTop: number
    bodyBottom: number
    bodySize: number
    upperWick: number
    lowerWick: number
    totalRange: number
}

export default class Doji extends Indicator {
    public DojiBuffer!: IndexBuffer

    private readonly shadowTolerancePercent = 100.0
    private readonly bodySizePercent = 5.0

    public OnInit(): void {
        this.api.SetIndicatorShortName('Doji')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)
        this.api.HideIndicatorValuesOnPriceScale()
        this.api.SetIndicatorEmptyValue(0)

        this.DojiBuffer = this.api.CreateBuffer()

        this.api.SetPlotCount(1)

        this.api.SetPlotBuffer(0, this.DojiBuffer)
        this.api.SetPlotLabel(0, 'Doji')
        this.api.SetPlotStyle(0, PlotType.SYMBOL, PenStyle.SOLID, 2, '#72778a')
        this.api.SetPlotSymbol(0, 233, 0, -15)
    }

    public OnCalculate(index: number): void {
        this.DojiBuffer.setValue(index, 0)

        const openPrice = this.api.Open(index)
        const closePrice = this.api.Close(index)
        const highPrice = this.api.High(index)
        const lowPrice = this.api.Low(index)

        const candleStructure = this.calculateCandleStructure(openPrice, closePrice, highPrice, lowPrice)

        if (!this.isValidCandle(candleStructure)) {
            return
        }

        const hasSmallBody = this.checkSmallBodyCondition(candleStructure)
        const hasBalancedShadows = this.checkShadowBalance(candleStructure)

        if (hasSmallBody && hasBalancedShadows) {
            const isDragonfly = this.isDragonflyDoji(candleStructure)
            const isGravestone = this.isGravestoneDoji(candleStructure)

            if (!isDragonfly && !isGravestone) {
                this.DojiBuffer.setValue(index, lowPrice)
            }
        }
    }

    private calculateCandleStructure(open: number, close: number, high: number, low: number): CandleStructure {
        const bodyTop = Math.max(close, open)
        const bodyBottom = Math.min(close, open)
        const bodySize = bodyTop - bodyBottom
        const upperWick = high - bodyTop
        const lowerWick = bodyBottom - low
        const totalRange = high - low

        return {
            bodyTop,
            bodyBottom,
            bodySize,
            upperWick,
            lowerWick,
            totalRange
        }
    }

    private isValidCandle(structure: CandleStructure): boolean {
        return structure.totalRange > 0
    }

    private checkSmallBodyCondition(structure: CandleStructure): boolean {
        const maxBodySize = (structure.totalRange * this.bodySizePercent) / 100.0
        return structure.bodySize <= maxBodySize
    }

    private checkShadowBalance(structure: CandleStructure): boolean {
        if (structure.upperWick === structure.lowerWick) {
            return true
        }

        const upperWickPercent =
            structure.lowerWick === 0
                ? Number.POSITIVE_INFINITY
                : (Math.abs(structure.upperWick - structure.lowerWick) / structure.lowerWick) * 100.0

        const lowerWickPercent =
            structure.upperWick === 0
                ? Number.POSITIVE_INFINITY
                : (Math.abs(structure.lowerWick - structure.upperWick) / structure.upperWick) * 100.0

        return upperWickPercent < this.shadowTolerancePercent && lowerWickPercent < this.shadowTolerancePercent
    }

    private isDragonflyDoji(structure: CandleStructure): boolean {
        return structure.upperWick <= structure.bodySize
    }

    private isGravestoneDoji(structure: CandleStructure): boolean {
        return structure.lowerWick <= structure.bodySize
    }
}
```


# Donchian Channel

Donchian Channel built-in indicator — download the project and explore highest-high / lowest-low price channels.

Rolling highest-high / lowest-low channel with a midline — classic breakout bands.

***

## When to copy this pattern

Copy Donchian Channel when you need rolling highest-high and lowest-low bands plus a midline — classic breakout and channel indicators.

## Download

{% file src="/files/9WxGBHV4Oxl0XH82klXQ" %}

***

## What you can learn

* Rolling extrema with `GetHighestValue` / `GetLowestValue` over a lookback window
* Three chart overlays: upper, middle, lower
* Period-driven lookback guards in `OnCalculate`

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                            |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Period controls rolling extrema; Shift changes display placement.                                                   |
| Output                 | Upper, midpoint and lower chart lines.                                                                              |
| History and edge cases | The window includes the tested bar. Compare to a preceding window when the breakout boundary must exclude that bar. |

## Pattern to reuse

Register period and shift inputs, fill three overlay buffers with rolling highest/lowest via `GetHighestValue` / `GetLowestValue`, and apply plot shift in `OnParamsChange`.

{% hint style="info" %}
The excerpt below includes explicit history and empty-value handling. Keep those guards when reusing the calculation.
{% endhint %}

```typescript
export default class DonchianChannel extends Indicator {
    public Period!: InputNumber
    public Shift!: InputNumber

    public UpperBuffer!: IndexBuffer
    public MiddleBuffer!: IndexBuffer
    public LowerBuffer!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('Donchian Channel')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)
        this.api.SetIndicatorEmptyValue(0)

        this.Period = this.api.CreateIntegerInput('Period', 14, 1, 1000)
        this.Shift = this.api.CreateIntegerInput('Shift', 0, -1000, 1000)

        this.api.SetPlotCount(3)

        this.UpperBuffer = this.api.CreateBuffer()
        this.MiddleBuffer = this.api.CreateBuffer()
        this.LowerBuffer = this.api.CreateBuffer()

        this.api.SetPlotBuffer(0, this.UpperBuffer)
        this.api.SetPlotLabel(0, 'Upper')
        this.api.SetPlotStyle(0, PlotType.LINE, PenStyle.SOLID, 1, '#f7525f')

        this.api.SetPlotBuffer(1, this.MiddleBuffer)
        this.api.SetPlotLabel(1, 'Middle')
        this.api.SetPlotStyle(1, PlotType.LINE, PenStyle.SOLID, 1, '#9598a1')

        this.api.SetPlotBuffer(2, this.LowerBuffer)
        this.api.SetPlotLabel(2, 'Lower')
        this.api.SetPlotStyle(2, PlotType.LINE, PenStyle.SOLID, 1, '#38b6ff')
    }

    public OnCalculate(index: number): void {
        if (index + this.Period.value > this.api.Bars()) {
            return
        }

        const highest = this.api.GetHighestValue(PriceSeries.HIGH, index, this.Period.value)
        const lowest = this.api.GetLowestValue(PriceSeries.LOW, index, this.Period.value)

        this.UpperBuffer.setValue(index, highest)
        this.MiddleBuffer.setValue(index, (highest + lowest) / 2)
        this.LowerBuffer.setValue(index, lowest)
    }

    public OnParamsChange(): void {
        this.api.SetIndicatorBackOffset(this.Shift.value)
        this.api.SetPlotShift(0, this.Shift.value)
        this.api.SetPlotShift(1, this.Shift.value)
        this.api.SetPlotShift(2, this.Shift.value)
    }
}
```


# Engulfing Bar

Engulfing Bar built-in indicator — download the project and explore bullish and bearish engulfing candlestick pattern detection.

Two-bar engulfing markers: bullish/bearish symbol plots only on signal bars.

***

## When to copy this pattern

Copy Engulfing Bar when you compare two consecutive candles and plot bullish or bearish markers only on the signal bar.

## Download

{% file src="/files/k2EJWbs40eVEwSzzBJaQ" %}

***

## What you can learn

* Two-bar open/close body comparison at `index` and `index + 1`
* Separate symbol plots or colors for bullish vs bearish engulfing
* Conditional buffer writes so only signal bars show markers

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                      |
| ---------------------- | ------------------------------------------------------------------------------------------------------------- |
| Inputs                 | No inputs; conditions compare two consecutive candle bodies.                                                  |
| Output                 | Bullish symbols at lows and bearish symbols at highs; both outputs reset before each comparison.              |
| History and edge cases | Two bars are required. Wicks are not part of the body-engulfing condition. Forming-bar signals can disappear. |

## Pattern to reuse

Compare bodies at `index` and `index + 1`, then write separate bullish/bearish symbol buffers only on signal bars.

```typescript
export default class EngulfingBar extends Indicator {
    // buffers
    public BullishBuffer!: IndexBuffer
    public BearishBuffer!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('Engulfing Bar')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)
        this.api.HideIndicatorValuesOnPriceScale()
        this.api.SetIndicatorEmptyValue(0)

        // create all buffers
        this.BullishBuffer = this.api.CreateBuffer()
        this.BearishBuffer = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(2)

        this.api.SetPlotBuffer(0, this.BullishBuffer)
        this.api.SetPlotLabel(0, 'Bullish')
        this.api.SetPlotStyle(0, PlotType.SYMBOL, PenStyle.SOLID, 2, '#00bfff')
        this.api.SetPlotSymbol(0, 233, 0, -15)

        this.api.SetPlotBuffer(1, this.BearishBuffer)
        this.api.SetPlotLabel(1, 'Bearish')
        this.api.SetPlotStyle(1, PlotType.SYMBOL, PenStyle.SOLID, 2, '#9370db')
        this.api.SetPlotSymbol(1, 234, 0, 15)
    }

    public OnCalculate(index: number): void {
        if (index + 1 >= this.api.Bars()) {
            return
        }

        const currClose = this.api.Close(index)
        const currOpen = this.api.Open(index)
        const prevClose = this.api.Close(index + 1) || currClose
        const prevOpen = this.api.Open(index + 1) || currOpen

        this.BullishBuffer.setValue(index, 0)
        this.BearishBuffer.setValue(index, 0)

        if (currClose > currOpen && prevClose < prevOpen && currClose >= prevOpen && currOpen <= prevClose) {
            this.BullishBuffer.setValue(index, this.api.Low(index))
        }

        if (currClose < currOpen && prevClose > prevOpen && currClose <= prevOpen && currOpen >= prevClose) {
            this.BearishBuffer.setValue(index, this.api.High(index))
        }
    }
}
```


# Fractals

Fractals built-in indicator — download the project and explore Bill Williams fractal swing high and low markers.

**Fractals** mark local swing highs and lows using Bill Williams’ five-bar pattern. They help identify support/resistance pivots and structure in trending markets.

***

## When to copy this pattern

Copy Fractals when you detect a centered multi-bar swing pattern and mark confirmed highs and lows with symbol plots.

## Download

{% file src="/files/Lyu1DjDM3OKTeibcLb8a" %}

***

## What you can learn

* Five-bar Bill Williams fractal logic with neighbors on each side
* Delayed plotting at the center bar index
* Up and down markers at high and low prices

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                                                                                                                            |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Period counts neighbors on each side; 2 gives a five-bar pattern.                                                                                                                                                                   |
| Output                 | Upper/lower markers are written at the center bar, Period bars behind the calculation bar.                                                                                                                                          |
| History and edge cases | A current-bar calculation still uses forming bar 0 for confirmation. Fully closed confirmation requires a candidate at least Period + 1 bars back. Back offset is set in OnInit; this listing does not update it in OnParamsChange. |

## Pattern to reuse

Detect a centered multi-bar swing with a period lookback, plot up/down symbols at the center bar’s high/low, and set back offset from the period.

{% hint style="info" %}
The excerpt below includes explicit history and empty-value handling. Keep those guards when reusing the calculation.
{% endhint %}

```typescript
export default class Fractals extends Indicator {
    // inputs
    public Period!: InputNumber
    // buffers
    public UpperFractal!: IndexBuffer
    public LowerFractal!: IndexBuffer

    public OnInit(): void {
        this.api.RecalculateMeAlways()
        this.api.SetIndicatorShortName('Fractals')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)

        // register input parameters
        this.Period = this.api.CreateIntegerInput('Period', 2, 1, 1000)
        this.api.SetIndicatorBackOffset(this.Period.value + 3)

        // create all buffers
        this.UpperFractal = this.api.CreateBuffer()
        this.LowerFractal = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(2)
        this.api.SetIndicatorEmptyValue(0)

        this.api.SetPlotBuffer(0, this.UpperFractal)
        this.api.SetPlotLabel(0, 'Fractal up')
        this.api.SetPlotStyle(0, PlotType.SYMBOL, PenStyle.SOLID, 5, '#26A69A')
        this.api.SetPlotSymbol(0, 217, 0, 20)

        this.api.SetPlotBuffer(1, this.LowerFractal)
        this.api.SetPlotLabel(1, 'Fractal down')
        this.api.SetPlotStyle(1, PlotType.SYMBOL, PenStyle.SOLID, 5, '#EF5350')
        this.api.SetPlotSymbol(1, 218, 0, -20)
    }

    public OnCalculate(index: number): void {
        // Reset buffer values (needed for Bar Back functionality)
        this.UpperFractal.setValue(index, 0)
        this.LowerFractal.setValue(index, 0)

        const period = this.Period.value
        const fIndex = index + period

        // Safe for High/Low(fIndex ± period): need older and newer neighbors loaded
        if (fIndex < period || fIndex + period >= this.api.Bars()) {
            return
        }

        const high = this.api.High(fIndex)
        const low = this.api.Low(fIndex)

        let upperFractal = 0
        let lowerFractal = 0

        let isUpperFractal = true
        let isLowerFractal = true

        for (let i = 1; i <= period; i++) {
            const highLeft = this.api.High(fIndex + i)
            const lowLeft = this.api.Low(fIndex + i)

            const highRight = this.api.High(fIndex - i)
            const lowRight = this.api.Low(fIndex - i)

            if (high < highLeft || high <= highRight) {
                isUpperFractal = false
            }

            if (low > lowLeft || low >= lowRight) {
                isLowerFractal = false
            }
        }

        if (isUpperFractal) {
            upperFractal = high
        }

        if (isLowerFractal) {
            lowerFractal = low
        }

        this.UpperFractal.setValue(fIndex, upperFractal)
        this.LowerFractal.setValue(fIndex, lowerFractal)
    }
}
```


# MACD

MACD built-in indicator — download the project and explore Moving Average Convergence Divergence trend and momentum signals.

**MACD (Moving Average Convergence Divergence)** shows the relationship between two moving averages. The histogram and signal line help assess trend direction, momentum, and potential crossovers.

***

## When to copy this pattern

Copy MACD when you need multiple EMA stages, a signal line, histogram output, and a zero level in a separate pane — the standard three-plot oscillator layout.

## Download

{% file src="/files/NeIoYxI9hK5utKxjdC3S" %}

***

## What you can learn

* Fast and slow EMA buffers feeding a MACD spread line
* Simple moving average of MACD for the signal line
* Histogram as MACD minus signal with `PlotType.HISTOGRAM`
* `AddLevel(0, …)` on a separate window and back offset from periods

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                              |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Fast EMA, Slow EMA and Signal periods control the stages; Apply to price selects samples. This example uses 5/13/3.                   |
| Output                 | Histogram (slot 0), MACD line (1) and SMA signal (2) in one separate pane; EMA buffers remain hidden.                                 |
| History and edge cases | EMA stages seed from source prices. The signal waits for its window. A non-zero empty sentinel preserves valid zero histogram values. |

## Pattern to reuse

Chain fast/slow EMA buffers into a MACD line, smooth it for the signal, plot the histogram as MACD minus signal, and add a zero level in a separate window.

{% hint style="info" %}
The excerpt below includes explicit history and empty-value handling. Keep those guards when reusing the calculation.
{% endhint %}

```typescript
export default class MACD extends Indicator {
    // inputs
    public FastEMAPeriod!: InputNumber
    public SlowEMAPeriod!: InputNumber
    public SMAPeriod!: InputNumber
    public ApplyToPrice!: InputEnum<PriceType>
    // buffers
    public MACD!: IndexBuffer
    public Signal!: IndexBuffer
    public Histogram!: IndexBuffer
    private FastEMA!: IndexBuffer
    private SlowEMA!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('MACD')
        this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
        this.api.AddLevel(0, PenStyle.DOT, 1, '#ada9a9')
        this.api.RecalculateMeAlways()

        // register input parameters
        this.FastEMAPeriod = this.api.CreateIntegerInput('Fast EMA period', 5, 1, 1000000)
        this.SlowEMAPeriod = this.api.CreateIntegerInput('Slow EMA period', 13, 1, 1000000)
        this.SMAPeriod = this.api.CreateIntegerInput('Signal period', 3, 1, 1000000)
        this.ApplyToPrice = this.api.CreateApplyToPriceInput('', PriceType.CLOSE)

        // create all buffers
        this.MACD = this.api.CreateBuffer()
        this.Signal = this.api.CreateBuffer()
        this.Histogram = this.api.CreateBuffer()
        this.FastEMA = this.api.CreateBuffer()
        this.SlowEMA = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(3)
        // Non-zero sentinel: 0 is a valid MACD histogram value
        this.api.SetIndicatorEmptyValue(1000000)

        this.api.CreatePlot(1, this.MACD, 'MACD', PlotType.LINE, PenStyle.SOLID, 1, '#0000FF')
        this.api.CreatePlot(2, this.Signal, 'Signal', PlotType.LINE, PenStyle.DOT, 1, '#FF0000')
        this.api.CreatePlot(0, this.Histogram, 'Histogram', PlotType.HISTOGRAM, PenStyle.SOLID, 5, '#C0C0C0')
    }

    public OnCalculate(index: number): void {
        this.FastEMA.setValue(
            index,
            this.api.GetMA(
                index,
                0,
                this.FastEMAPeriod.value,
                MovingAverageType.EMA,
                this.ApplyToPrice.value,
                this.FastEMA.getValue(index + 1)
            )
        )
        this.SlowEMA.setValue(
            index,
            this.api.GetMA(
                index,
                0,
                this.SlowEMAPeriod.value,
                MovingAverageType.EMA,
                this.ApplyToPrice.value,
                this.SlowEMA.getValue(index + 1)
            )
        )

        // calculate MACD
        const macd = this.FastEMA.getValue(index) - this.SlowEMA.getValue(index)
        this.MACD.setValue(index, macd)

        // calculate Signal
        if (index + this.SMAPeriod.value > this.api.Bars()) {
            return
        }
        let sum = 0
        for (let i = index; i < index + this.SMAPeriod.value; i++) {
            sum += this.MACD.getValue(i)
        }
        const signal = sum / this.SMAPeriod.value
        this.Signal.setValue(index, signal)

        // calculate Histogram
        this.Histogram.setValue(index, macd - signal)
    }

    public OnParamsChange(): void {
        this.api.SetIndicatorBackOffset(
            Math.max(this.FastEMAPeriod.value, this.SlowEMAPeriod.value, this.SMAPeriod.value) * 3
        )
    }
}
```


# Rate of Change

Rate of Change built-in indicator — download the project and explore momentum measurement as the speed of price change.

**Rate of Change (ROC)** measures the percentage change in price over a given period. It is a momentum oscillator used to compare current momentum with historical readings.

***

## When to copy this pattern

Copy Rate of Change when you need a single-line momentum oscillator — percent change from a price `n` bars ago.

## Download

{% file src="/files/QjagJscaCaW6KzYpEafN" %}

***

## What you can learn

* Percent change formula with configurable apply-to price
* Separate-window line with period lookback guard
* Minimal buffer count for a one-series oscillator

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                          |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Period is the comparison distance in bars; Source chooses the price.                                                              |
| Output                 | One separate-pane percent-change line and a zero reference level.                                                                 |
| History and edge cases | Reading index + Period needs Period + 1 bars. The comparison price must be nonzero; this listing does not guard division by zero. |

## Pattern to reuse

Read apply-to price at `index` and `index + period`, write percent change to a separate-window line, and guard the lookback before dividing.

{% hint style="info" %}
The public package does not export internal constants. This example declares the empty-plot sentinel locally as `2147483647`, matching the runtime value.
{% endhint %}

```typescript
const INTEGER_MAX_VALUE = 2147483647

export default class RateOfChange extends Indicator {
    // inputs
    public ROCPeriod!: InputNumber
    public Source!: InputEnum<PriceType>
    // buffers
    public ROCBuffer!: IndexBuffer

    public override OnInit(): void {
        this.api.SetIndicatorShortName('Rate of Change')
        this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
        this.api.AddLevel(0, PenStyle.DOT, 1, '#a8a8a8')
        this.api.SetIndicatorEmptyValue(INTEGER_MAX_VALUE)
        this.api.SetIndicatorDigits(2)

        this.ROCPeriod = this.api.CreateIntegerInput('Period', 9, 1)
        this.Source = this.api.CreateApplyToPriceInput('', PriceType.CLOSE)

        this.ROCBuffer = this.api.CreateBuffer()

        this.api.SetPlotCount(1)

        this.api.CreatePlot(0, this.ROCBuffer, 'ROC', PlotType.LINE, PenStyle.SOLID, 1, '#2962ff')
    }

    public override OnCalculate(index: number): void {
        this.ROCBuffer.setValue(index, INTEGER_MAX_VALUE)

        if (index + this.ROCPeriod.value >= this.api.Bars()) {
            return
        }

        const currPrice = this.api.GetPrice(index, this.Source.value)
        const pastPrice = this.api.GetPrice(index + this.ROCPeriod.value, this.Source.value)
        const rateOfChange = (100.0 * (currPrice - pastPrice)) / pastPrice

        this.ROCBuffer.setValue(index, rateOfChange)
    }
}
```


# RCI

RCI (Rank Correlation Index) built-in indicator — download the project and explore rank-based momentum on the chart.

Rank-correlation oscillator over a lookback window, with optional MA smoothing and level lines.

***

## When to copy this pattern

Copy RCI when you rank bars by time vs price and display rank correlation as a bounded oscillator with level lines.

## Download

{% file src="/files/rzGnhRX2PRXzMiHEnkwZ" %}

***

## What you can learn

* Rank correlation index math over a sliding window
* Separate pane with overbought/oversold `AddLevel` lines
* Keeping scale readable with fixed min/max or reference levels

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                                        |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | RCI period/price source define ranks; MA period/type configure the smoothing line.                                                              |
| Output                 | RCI and its MA in a separate pane. Equal prices receive average ranks.                                                                          |
| History and edge cases | The MA needs its own window of valid RCI values. Constant ranks or RCI period 1 produce 0; recursive smoothing uses the available stored state. |

## Pattern to reuse

Rank bars by time vs price over the period, plot the correlation oscillator with `AddLevel` guides, and optionally smooth RCI with a second plot.

{% hint style="info" %}
The public package does not export internal constants. This example declares the empty-plot sentinel locally as `2147483647`, matching the runtime value.
{% endhint %}

```typescript
const INTEGER_MAX_VALUE = 2147483647

export default class RCI extends Indicator {
    // inputs
    public ApplyToPrice!: InputEnum<PriceType>
    public RCIPeriod!: InputNumber
    public MAType!: InputEnum<MovingAverageType>
    public MAPeriod!: InputNumber
    // buffers
    public RCIBuffer!: IndexBuffer
    public MABuffer!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('RCI')
        this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
        this.api.AddLevel(80, PenStyle.DOT, 1, '#ada9a9')
        this.api.AddLevel(0, PenStyle.DOT, 1, '#ada9a9')
        this.api.AddLevel(-80, PenStyle.DOT, 1, '#ada9a9')
        this.api.RecalculateMeAlways()

        // register input parameters
        this.ApplyToPrice = this.api.CreateApplyToPriceInput('', PriceType.CLOSE)
        this.RCIPeriod = this.api.CreateIntegerInput('RCI period', 10, 1)
        this.MAType = this.api.CreateMATypeInput('', MovingAverageType.SMA)
        this.MAPeriod = this.api.CreateIntegerInput('MA period', 14, 1)

        // create all buffers
        this.RCIBuffer = this.api.CreateBuffer()
        this.MABuffer = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(2)
        this.api.SetIndicatorEmptyValue(INTEGER_MAX_VALUE)

        this.api.CreatePlot(0, this.RCIBuffer, 'RCI', PlotType.LINE, PenStyle.SOLID, 2, '#a191ee')
        this.api.CreatePlot(1, this.MABuffer, 'MA', PlotType.LINE, PenStyle.SOLID, 1, '#ffdf43')
    }

    public OnCalculate(index: number): void {
        // RCI calculation
        if (index > this.api.Bars() - this.RCIPeriod.value) {
            return
        }
        const prices: number[] = []
        for (let i = this.RCIPeriod.value - 1; i >= 0; i--) {
            prices.push(this.api.GetPrice(index + i, this.ApplyToPrice.value))
        }
        const rci = this.calculateRCI(this.RCIPeriod.value, prices)
        this.RCIBuffer.setValue(index, rci)

        // RCI-based MA calculation
        if (index > this.api.Bars() - (this.MAPeriod.value + this.RCIPeriod.value) + 1) {
            return
        }
        const ma = this.MAOnBuffer(
            this.RCIBuffer,
            this.api.Bars(),
            this.MAPeriod.value,
            this.MAType.value,
            index,
            this.MABuffer.getValue(index + 1)
        )
        this.MABuffer.setValue(index, ma)
    }

    public OnParamsChange(): void {
        this.api.SetIndicatorBackOffset(Math.max(this.RCIPeriod.value, this.MAPeriod.value) + 1)
    }

    private calculateRCI(period: number, priceSource: number[]): number {
        if (period <= 1 || period > priceSource.length) {
            return 0
        }

        const prices = priceSource.slice(-period)
        const priceRanks = this.rankWithAverageTies(prices)
        const barRanks = Array.from({ length: period }, (_, index) => index)
        const correlation = this.calculatePearsonCorrelation(priceRanks, barRanks)

        return correlation * 100
    }

    private rankWithAverageTies(values: number[]): number[] {
        const sortedIndices = values.map((_, index) => index).sort((a, b) => values[a] - values[b])
        const ranks = Array.from({ length: values.length }, () => 0)

        let i = 0
        while (i < sortedIndices.length) {
            const start = i
            const tieValue = values[sortedIndices[i]]
            while (i < sortedIndices.length && values[sortedIndices[i]] === tieValue) {
                i++
            }

            const end = i - 1
            const averageRank = (start + end) / 2
            for (let j = start; j <= end; j++) {
                ranks[sortedIndices[j]] = averageRank
            }
        }

        return ranks
    }

    private calculatePearsonCorrelation(first: number[], second: number[]): number {
        if (first.length === 0 || first.length !== second.length) {
            return 0
        }

        const count = first.length
        const firstMean = first.reduce((sum, value) => sum + value, 0) / count
        const secondMean = second.reduce((sum, value) => sum + value, 0) / count

        let covariance = 0
        let firstVariance = 0
        let secondVariance = 0
        for (let i = 0; i < count; i++) {
            const firstCentered = first[i] - firstMean
            const secondCentered = second[i] - secondMean
            covariance += firstCentered * secondCentered
            firstVariance += firstCentered * firstCentered
            secondVariance += secondCentered * secondCentered
        }

        if (firstVariance <= 0 || secondVariance <= 0) {
            return 0
        }

        return covariance / Math.sqrt(firstVariance * secondVariance)
    }

    private MAOnBuffer(
        buffer: IndexBuffer,
        total: number,
        period: number,
        type: MovingAverageType,
        shift: number,
        prev = 0
    ): number {
        switch (type) {
            case MovingAverageType.SMA: {
                return this.simpleMA(buffer, shift, period, total)
            }
            case MovingAverageType.EMA: {
                return this.exponentialMA(buffer, shift, period, prev)
            }
            case MovingAverageType.SMMA: {
                return this.smoothedMA(buffer, shift, period, total, prev)
            }
            case MovingAverageType.LWMA: {
                return this.linearWeightedMA(buffer, shift, period, total)
            }
            default: {
                return 0
            }
        }
    }

    private simpleMA(buffer: IndexBuffer, shift: number, period: number, total: number): number {
        let result = 0.0
        if (period > 0 && shift + period <= total) {
            for (let i = 0; i < period; i++) {
                result += buffer.getValue(shift + i)
            }
            result /= period
        }
        return result
    }

    private exponentialMA(buffer: IndexBuffer, shift: number, period: number, prev: number): number {
        let result = 0.0
        if (period > 0) {
            const pr = 2.0 / (period + 1.0)
            result = buffer.getValue(shift) * pr + prev * (1 - pr)
        }
        return result
    }

    private smoothedMA(buffer: IndexBuffer, shift: number, period: number, total: number, prev: number): number {
        let result = 0.0
        if (period > 0 && shift + period <= total) {
            if (shift === total - period) {
                for (let i = 0; i < period; i++) {
                    result += buffer.getValue(shift + i)
                }
                result /= period
            }
            result = (prev * (period - 1) + buffer.getValue(shift)) / period
        }
        return result
    }

    private linearWeightedMA(buffer: IndexBuffer, shift: number, period: number, total: number): number {
        let result = 0.0
        if (period > 0 && shift + period <= total) {
            let sum = 0.0
            let wsum = 0
            for (let i = period; i > 0; i--) {
                wsum += i
                sum += buffer.getValue(shift + (period - i)) * i
            }
            result = sum / wsum
        }
        return result
    }
}
```


# Rolling VWAP

Rolling VWAP built-in indicator — download the project and explore rolling Volume Weighted Average Price on the chart.

**Rolling VWAP** computes a volume-weighted average price over a rolling window. It is useful for intraday fair-value reference and mean-reversion around volume-weighted levels.

***

## When to copy this pattern

Copy Rolling VWAP when you accumulate price×volume over a rolling bar window and plot volume-weighted fair value on price.

## Download

{% file src="/files/Tay6v46bs5UqX7SRkHOg" %}

***

## What you can learn

* Rolling sum of typical price × volume divided by rolling volume
* Window reset or sliding accumulation across `index + offset`
* Chart-overlay line calculated over a rolling bar window, without session resets

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                                                                                                                |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Period sets the rolling bar window; Source chooses prices; three multipliers set optional band pairs. Multiplier 0 hides its pair.                                                                                      |
| Output                 | VWAP and three upper/lower band pairs on the chart.                                                                                                                                                                     |
| History and edge cases | The window does not reset by session. At zero total volume the VWAP keeps its previous value, but the band calculation still divides by total volume and can produce NaN. Band values require a positive-volume window. |

## Pattern to reuse

Accumulate typical price × volume over a rolling window, plot the volume-weighted mean on price, and optionally add band plots from the same window.

{% hint style="info" %}
The excerpt below includes explicit history and empty-value handling. Keep those guards when reusing the calculation.
{% endhint %}

```typescript
export default class RollingVWAP extends Indicator {
    // inputs
    public Period!: InputNumber
    public ApplyToPrice!: InputEnum<PriceType>
    public BandsMult1!: InputNumber
    public BandsMult2!: InputNumber
    public BandsMult3!: InputNumber
    // buffers
    public RVWAPBuffer!: IndexBuffer
    public UpperBand1Buffer!: IndexBuffer
    public LowerBand1Buffer!: IndexBuffer
    public UpperBand2Buffer!: IndexBuffer
    public LowerBand2Buffer!: IndexBuffer
    public UpperBand3Buffer!: IndexBuffer
    public LowerBand3Buffer!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('Rolling VWAP')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)

        this.api.RecalculateMeAlways()
        this.api.SetIndicatorEmptyValue(0)

        this.Period = this.api.CreateIntegerInput('Period', 14, 1)
        this.ApplyToPrice = this.api.CreateApplyToPriceInput('', PriceType.HLC3)
        this.BandsMult1 = this.api.CreateDoubleInput('Bands mult 1', 1.0, 0, 1000000)
        this.BandsMult2 = this.api.CreateDoubleInput('Bands mult 2', 1.5, 0, 1000000)
        this.BandsMult3 = this.api.CreateDoubleInput('Bands mult 3', 2.5, 0, 1000000)

        this.RVWAPBuffer = this.api.CreateBuffer()
        this.UpperBand1Buffer = this.api.CreateBuffer()
        this.LowerBand1Buffer = this.api.CreateBuffer()
        this.UpperBand2Buffer = this.api.CreateBuffer()
        this.LowerBand2Buffer = this.api.CreateBuffer()
        this.UpperBand3Buffer = this.api.CreateBuffer()
        this.LowerBand3Buffer = this.api.CreateBuffer()

        this.api.SetPlotCount(7)

        this.api.CreatePlot(0, this.RVWAPBuffer, 'Rolling VWAP', PlotType.LINE, PenStyle.SOLID, 1, '#8358f3')
        this.api.CreatePlot(1, this.UpperBand1Buffer, 'Upper band 1', PlotType.LINE, PenStyle.SOLID, 1, '#ffe443')
        this.api.CreatePlot(2, this.LowerBand1Buffer, 'Lower band 1', PlotType.LINE, PenStyle.SOLID, 1, '#ffe443')
        this.api.CreatePlot(3, this.UpperBand2Buffer, 'Upper band 2', PlotType.LINE, PenStyle.SOLID, 1, '#ff9213')
        this.api.CreatePlot(4, this.LowerBand2Buffer, 'Lower band 2', PlotType.LINE, PenStyle.SOLID, 1, '#ff9213')
        this.api.CreatePlot(5, this.UpperBand3Buffer, 'Upper band 3', PlotType.LINE, PenStyle.SOLID, 1, '#ff3847')
        this.api.CreatePlot(6, this.LowerBand3Buffer, 'Lower band 3', PlotType.LINE, PenStyle.SOLID, 1, '#ff3847')
    }

    public OnCalculate(index: number): void {
        if (index + this.Period.value > this.api.Bars()) {
            return
        }

        let cumulativeVolume = 0
        let cumulativePriceVolume = 0
        let cumulativeSquaredPriceVolume = 0

        for (let i = index; i < index + this.Period.value; i++) {
            const price = this.api.GetPrice(i, this.ApplyToPrice.value)
            const volume = this.api.Volume(i)

            cumulativeVolume += volume
            cumulativePriceVolume += price * volume
            cumulativeSquaredPriceVolume += price * price * volume
        }

        if (cumulativeVolume > 0) {
            this.RVWAPBuffer.setValue(index, cumulativePriceVolume / cumulativeVolume)
        } else {
            this.RVWAPBuffer.setValue(index, this.RVWAPBuffer.getValue(index + 1))
        }

        const vwap = this.RVWAPBuffer.getValue(index)
        const expectedSquaredPrice = cumulativeSquaredPriceVolume / cumulativeVolume
        const variance = Math.max(expectedSquaredPrice - vwap * vwap, 0.0)
        const stdDev = Math.sqrt(variance)

        this.UpperBand1Buffer.setValue(index, this.BandsMult1.value === 0 ? 0 : vwap + stdDev * this.BandsMult1.value)
        this.LowerBand1Buffer.setValue(index, this.BandsMult1.value === 0 ? 0 : vwap - stdDev * this.BandsMult1.value)

        this.UpperBand2Buffer.setValue(index, this.BandsMult2.value === 0 ? 0 : vwap + stdDev * this.BandsMult2.value)
        this.LowerBand2Buffer.setValue(index, this.BandsMult2.value === 0 ? 0 : vwap - stdDev * this.BandsMult2.value)

        this.UpperBand3Buffer.setValue(index, this.BandsMult3.value === 0 ? 0 : vwap + stdDev * this.BandsMult3.value)
        this.LowerBand3Buffer.setValue(index, this.BandsMult3.value === 0 ? 0 : vwap - stdDev * this.BandsMult3.value)
    }

    public OnParamsChange(): void {
        this.api.SetIndicatorBackOffset(this.Period.value)
    }
}
```


# Supertrend

Supertrend built-in indicator — download the project and explore ATR-based trend-following overlay signals.

**Supertrend** is a trend-following overlay that flips direction based on ATR-derived bands. It gives a simple visual of uptrend vs downtrend and potential stop/trail levels.

***

## When to copy this pattern

Copy Supertrend when you need an ATR-based trailing trend line on price that flips color or direction when price crosses the band.

## Download

{% file src="/files/IxMj1kDAS8gwzrKkBH3A" %}

***

## What you can learn

* ATR-scaled upper and lower bands from median price
* Trend state that flips when price closes through the active band
* Two overlay plots (up-trend/down-trend bands), each holding the empty value on the inactive side

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                                                                                                |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Period controls a simple average of true range; Multiplier scales bands; Shift changes display placement.                                                                                               |
| Output                 | Up/down lines backed by hidden range, band and direction buffers.                                                                                                                                       |
| History and edge cases | The inactive line is empty. Startup has partial state before the window fills. The trend calculation reads Close(index + 1), so an invocation on the oldest available bar can exceed the history range. |

## Pattern to reuse

Build ATR-scaled bands, flip trend state when price closes through the active band, and drive separate up/down overlay plots from that state.

```typescript
export default class Supertrend extends Indicator {
    // inputs
    public Period!: InputNumber
    public Multiplier!: InputNumber
    public Shift!: InputNumber
    // buffers
    public UpTrendBuffer!: IndexBuffer
    public DownTrendBuffer!: IndexBuffer
    private UpperBandBuffer!: IndexBuffer
    private LowerBandBuffer!: IndexBuffer
    private DirrBuffer!: IndexBuffer
    private ATRBuffer!: IndexBuffer
    private TRBuffer!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('Supertrend')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)
        this.api.RecalculateMeAlways()

        // register input parameters
        this.Period = this.api.CreateIntegerInput('Period', 10, 1, 1000)
        this.Multiplier = this.api.CreateDoubleInput('Multiplier', 3, 0.01, 1000)
        this.Shift = this.api.CreateIntegerInput('Shift', 0, -1000, 1000)

        // create all buffers
        this.UpTrendBuffer = this.api.CreateBuffer()
        this.DownTrendBuffer = this.api.CreateBuffer()
        this.UpperBandBuffer = this.api.CreateBuffer()
        this.LowerBandBuffer = this.api.CreateBuffer()
        this.DirrBuffer = this.api.CreateBuffer()
        this.ATRBuffer = this.api.CreateBuffer()
        this.TRBuffer = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(2)
        this.api.SetIndicatorEmptyValue(0)

        this.api.SetPlotBuffer(0, this.UpTrendBuffer)
        this.api.SetPlotLabel(0, 'Up trend')
        this.api.SetPlotStyle(0, PlotType.LINE, PenStyle.SOLID, 2, '#008000')

        this.api.SetPlotBuffer(1, this.DownTrendBuffer)
        this.api.SetPlotLabel(1, 'Down trend')
        this.api.SetPlotStyle(1, PlotType.LINE, PenStyle.SOLID, 2, '#FF0000')
    }

    public OnCalculate(index: number): void {
        // ATR calculation
        const high = this.api.High(index)
        const low = this.api.Low(index)

        if (index === this.api.Bars() - 1) {
            this.TRBuffer.setValue(index, high - low)
        } else {
            const prevclose = this.api.GetPrice(index + 1, PriceType.CLOSE)
            this.TRBuffer.setValue(index, Math.max(high, prevclose) - Math.min(low, prevclose))
        }

        let atr = 0
        for (let i = 0; i < this.Period.value && this.api.Bars() - index > this.Period.value; i++) {
            atr += this.TRBuffer.getValue(index + i) / this.Period.value
        }
        this.ATRBuffer.setValue(index, atr)

        // Supertrend calculation
        const medianPrice = this.api.GetPrice(index, PriceType.HL2)

        let currLowerBand = medianPrice - this.Multiplier.value * this.ATRBuffer.getValue(index)
        let currUpperBand = medianPrice + this.Multiplier.value * this.ATRBuffer.getValue(index)

        const prevLowerBand = this.LowerBandBuffer.getValue(index + 1) || 0
        const prevUpperBand = this.UpperBandBuffer.getValue(index + 1) || 0

        const currClose = this.api.Close(index)
        const prevClose = this.api.Close(index + 1) || currClose

        currLowerBand = currLowerBand > prevLowerBand || prevClose < prevLowerBand ? currLowerBand : prevLowerBand
        currUpperBand = currUpperBand < prevUpperBand || prevClose > prevUpperBand ? currUpperBand : prevUpperBand

        this.LowerBandBuffer.setValue(index, currLowerBand)
        this.UpperBandBuffer.setValue(index, currUpperBand)

        this.DirrBuffer.setValue(index, this.DirrBuffer.getValue(index + 1) || 1)

        if (currClose > currUpperBand) {
            this.DirrBuffer.setValue(index, -1)
        } else if (currClose < currLowerBand) {
            this.DirrBuffer.setValue(index, 1)
        }

        if (this.DirrBuffer.getValue(index) < 0) {
            this.UpTrendBuffer.setValue(index, currLowerBand)
            this.DownTrendBuffer.setValue(index, 0)
        } else if (this.DirrBuffer.getValue(index) > 0) {
            this.DownTrendBuffer.setValue(index, currUpperBand)
            this.UpTrendBuffer.setValue(index, 0)
        }
    }

    public OnParamsChange(): void {
        this.api.SetIndicatorBackOffset(this.Period.value + 50)
        this.api.SetPlotShift(0, this.Shift.value)
        this.api.SetPlotShift(1, this.Shift.value)
    }
}
```


# TDI

TDI (Traders Dynamic Index) built-in indicator — download the project and explore RSI-based momentum with signal lines.

RSI-based momentum dashboard with signal lines and a volatility band in one separate window.

***

## When to copy this pattern

Copy TDI when you combine RSI, a signal line, volatility bands, and multiple plots in one separate-window momentum dashboard.

## Download

{% file src="/files/YxGRkzzoJd0FXfUGOVCu" %}

***

## What you can learn

* RSI core with moving-average signal line
* Volatility band buffers around the signal
* Four or more coordinated plots with shared period inputs

## Inputs, output, and limits

| Area       | Behavior                                                                                                                                                                                                    |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Inputs     | RSI period defaults to 13 (minimum 2), applied price to Close, volatility-band period to 34 (input minimum 1), RSI price-line period to 2, MA type to SMA, and trade-signal period to 7.                    |
| Output     | Five visible slots: upper band, market base line, lower band, RSI price line, and trade-signal line. RSI and average-gain/loss buffers are internal working data.                                           |
| Warm-up    | RSI needs its period plus one price; the combined lines also need their own lookback. The oldest output region is a startup region, not a fully warmed-up signal.                                           |
| Edge cases | Use a volatility-band period of at least 2: sample variance divides by period - 1, so period 1 produces an undefined result even though the input accepts it. Zero is the empty plot value in this listing. |

## Pattern to reuse

Compute RSI into scratch buffers, derive market base / signal / volatility-band plots from that core, and coordinate multiple separate-window lines from shared period inputs.

```typescript
export default class TDI extends Indicator {
    // inputs
    public RSIPeriod!: InputNumber
    public ApplyToPrice!: InputEnum<PriceType>
    public VolatilityBand!: InputNumber
    public RSIPriceLine!: InputNumber
    public MAType!: InputEnum<MovingAverageType>
    public TradeSignalLine!: InputNumber
    // buffers
    public VBHighBuffer!: IndexBuffer
    public MarketBaseLineBuffer!: IndexBuffer
    public VBLowBuffer!: IndexBuffer
    public RSIPriceLineBuffer!: IndexBuffer
    public TradeSignalLineBuffer!: IndexBuffer
    // RSI buffers
    public RSIBuffer!: IndexBuffer
    public AvgGainBuffer!: IndexBuffer
    public AvgLossBuffer!: IndexBuffer

    public OnInit(): void {
        this.api.SetIndicatorShortName('TDI')
        this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
        this.api.RecalculateMeAlways()

        // register input parameters
        this.RSIPeriod = this.api.CreateIntegerInput('RSI period', 13, 2)
        this.ApplyToPrice = this.api.CreateApplyToPriceInput('', PriceType.CLOSE)
        this.VolatilityBand = this.api.CreateIntegerInput('Volatility band', 34, 1)
        this.RSIPriceLine = this.api.CreateIntegerInput('RSI price line', 2, 1)
        this.MAType = this.api.CreateMATypeInput('', MovingAverageType.SMA)
        this.TradeSignalLine = this.api.CreateIntegerInput('Trade signal line', 7, 1)

        // create all buffers
        this.VBHighBuffer = this.api.CreateBuffer()
        this.MarketBaseLineBuffer = this.api.CreateBuffer()
        this.VBLowBuffer = this.api.CreateBuffer()
        this.RSIPriceLineBuffer = this.api.CreateBuffer()
        this.TradeSignalLineBuffer = this.api.CreateBuffer()
        this.RSIBuffer = this.api.CreateBuffer()
        this.AvgGainBuffer = this.api.CreateBuffer()
        this.AvgLossBuffer = this.api.CreateBuffer()

        // setup visible buffers
        this.api.SetPlotCount(5)
        this.api.SetIndicatorEmptyValue(0)

        this.api.CreatePlot(0, this.VBHighBuffer, 'VB high', PlotType.LINE, PenStyle.SOLID, 1, '#0000ff')
        this.api.CreatePlot(1, this.MarketBaseLineBuffer, 'Market base line', PlotType.LINE, PenStyle.SOLID, 2, '#ffd700')
        this.api.CreatePlot(2, this.VBLowBuffer, 'VB low', PlotType.LINE, PenStyle.SOLID, 1, '#0000ff')
        this.api.CreatePlot(3, this.RSIPriceLineBuffer, 'RSI price line', PlotType.LINE, PenStyle.SOLID, 2, '#008000')
        this.api.CreatePlot(4, this.TradeSignalLineBuffer, 'Trade signal line', PlotType.LINE, PenStyle.SOLID, 2, '#ff0000')
    }

    public OnCalculate(index: number): void {
        // RSI calculation
        if (index > this.api.Bars() - this.RSIPeriod.value - 1) {
            return
        }

        if (index === this.api.Bars() - this.RSIPeriod.value - 1) {
            this.calculateInitialRSI(index)
        } else {
            this.calculateCurrentRSI(index)
        }

        // TDI calculation
        if (
            this.api.Bars() - index <=
            Math.max(
                this.RSIPeriod.value,
                this.VolatilityBand.value,
                this.RSIPriceLine.value,
                this.TradeSignalLine.value
            )
        ) {
            return
        }

        let maValue = 0
        const tempRSI: number[] = []

        for (let x = index; x < index + this.VolatilityBand.value; x++) {
            tempRSI[x - index] = this.RSIBuffer.getValue(x)
            if (this.VolatilityBand.value !== 0) {
                maValue += this.RSIBuffer.getValue(x) / this.VolatilityBand.value
            }
        }

        const stdDev = this.calculateStdDev(tempRSI, this.VolatilityBand.value)
        const upZone = maValue + 1.6185 * stdDev
        const downZone = maValue - 1.6185 * stdDev

        this.VBHighBuffer.setValue(index, upZone)
        this.VBLowBuffer.setValue(index, downZone)
        this.MarketBaseLineBuffer.setValue(index, (upZone + downZone) / 2)

        this.RSIPriceLineBuffer.setValue(
            index,
            this.MAOnBuffer(
                this.RSIBuffer,
                this.api.Bars(),
                this.RSIPriceLine.value,
                this.MAType.value,
                index,
                this.RSIPriceLineBuffer.getValue(index + 1)
            )
        )

        this.TradeSignalLineBuffer.setValue(
            index,
            this.MAOnBuffer(
                this.RSIBuffer,
                this.api.Bars(),
                this.TradeSignalLine.value,
                this.MAType.value,
                index,
                this.TradeSignalLineBuffer.getValue(index + 1)
            )
        )
    }

    public OnParamsChange(): void {
        const maxPeriod = Math.max(
            this.RSIPeriod.value,
            this.VolatilityBand.value,
            this.RSIPriceLine.value,
            this.TradeSignalLine.value
        )
        this.api.SetIndicatorBackOffset(maxPeriod * 2)
    }

    private calculateInitialRSI(index: number): void {
        let avgGain = 0.0,
            avgLoss = 0.0

        for (let i = index; i < index + this.RSIPeriod.value; i++) {
            const currPrice = this.api.GetPrice(i, this.ApplyToPrice.value)
            const prevPrice = this.api.GetPrice(i + 1, this.ApplyToPrice.value)
            const priceDiff = this.normalizeValue(currPrice - prevPrice, this.api.Digits())

            if (priceDiff > 0) {
                avgGain += priceDiff / this.RSIPeriod.value
            } else {
                avgLoss -= priceDiff / this.RSIPeriod.value
            }
        }

        this.AvgGainBuffer.setValue(index, avgGain)
        this.AvgLossBuffer.setValue(index, avgLoss)

        this.setRSIValue(index, avgGain, avgLoss)
    }

    private calculateCurrentRSI(index: number): void {
        const currPrice = this.api.GetPrice(index, this.ApplyToPrice.value)
        const prevPrice = this.api.GetPrice(index + 1, this.ApplyToPrice.value)
        const priceDiff = this.normalizeValue(currPrice - prevPrice, this.api.Digits())

        const currGain = priceDiff > 0 ? priceDiff : 0.0
        const currLoss = priceDiff < 0 ? -priceDiff : 0.0

        const prevAvgGain = this.AvgGainBuffer.getValue(index + 1)
        const prevAvgLoss = this.AvgLossBuffer.getValue(index + 1)
        const periodFactor = this.RSIPeriod.value - 1

        const avgGain = (prevAvgGain * periodFactor + currGain) / this.RSIPeriod.value
        const avgLoss = (prevAvgLoss * periodFactor + currLoss) / this.RSIPeriod.value

        this.AvgGainBuffer.setValue(index, avgGain)
        this.AvgLossBuffer.setValue(index, avgLoss)

        this.setRSIValue(index, avgGain, avgLoss)
    }

    private setRSIValue(index: number, avgGain: number, avgLoss: number): void {
        if (avgLoss === 0.0) {
            this.RSIBuffer.setValue(index, avgGain === 0.0 ? 50.0 : 100.0)
        } else {
            const rs = avgGain / avgLoss
            this.RSIBuffer.setValue(index, 100.0 - 100.0 / (1.0 + rs))
        }
    }

    private normalizeValue(value: number, decimals: number): number {
        const factor = Math.pow(10, decimals)
        return Math.round(value * factor) / factor
    }

    private myVariance(data: number[], period: number): number {
        let sum = 0
        let ssum = 0
        for (let i = 0; i < period; i++) {
            sum += data[i]
            ssum += Math.pow(data[i], 2)
        }
        return (ssum * period - sum * sum) / (period * (period - 1))
    }

    private calculateStdDev(data: number[], period: number): number {
        return Math.sqrt(this.myVariance(data, period))
    }

    private MAOnBuffer(
        buffer: IndexBuffer,
        total: number,
        period: number,
        type: MovingAverageType,
        shift: number,
        prev = 0
    ): number {
        switch (type) {
            case MovingAverageType.SMA: {
                return this.simpleMA(buffer, shift, period, total)
            }
            case MovingAverageType.EMA: {
                return this.exponentialMA(buffer, shift, period, prev)
            }
            case MovingAverageType.SMMA: {
                return this.smoothedMA(buffer, shift, period, total, prev)
            }
            case MovingAverageType.LWMA: {
                return this.linearWeightedMA(buffer, shift, period, total)
            }
            default: {
                return 0
            }
        }
    }

    private simpleMA(buffer: IndexBuffer, shift: number, period: number, total: number): number {
        let result = 0.0
        if (period > 0 && shift + period <= total) {
            for (let i = 0; i < period; i++) {
                result += buffer.getValue(shift + i)
            }
            result /= period
        }
        return result
    }

    private exponentialMA(buffer: IndexBuffer, shift: number, period: number, prev_value: number): number {
        let result = 0.0
        if (period > 0) {
            const pr = 2.0 / (period + 1.0)
            result = buffer.getValue(shift) * pr + prev_value * (1 - pr)
        }
        return result
    }

    private smoothedMA(buffer: IndexBuffer, shift: number, period: number, total: number, prev_value: number): number {
        let result = 0.0
        if (period > 0 && shift + period <= total) {
            if (shift === total - period) {
                for (let i = 0; i < period; i++) {
                    result += buffer.getValue(shift + i)
                }
                result /= period
            }
            result = (prev_value * (period - 1) + buffer.getValue(shift)) / period
        }
        return result
    }

    private linearWeightedMA(buffer: IndexBuffer, shift: number, period: number, total: number): number {
        let result = 0.0
        if (period > 0 && shift + period <= total) {
            let sum = 0.0
            let wsum = 0
            for (let i = period; i > 0; i--) {
                wsum += i
                sum += buffer.getValue(shift + (period - i)) * i
            }
            result = sum / wsum
        }
        return result
    }
}
```


# Market Conditions Panel

Download a panel-only indicator example that combines moving averages, RSI, ADX, and ATR as chart objects without plot buffers.

**Market Conditions Panel** displays four readings for the chart symbol: whether the fast MA is above or below the slow MA, the RSI zone, ADX strength, and ATR. It draws a screen-positioned panel rather than indicator plots or buffers.

## When to copy this pattern

Use this example when you want an indicator to summarize several `i*` readings in a chart panel. The object helpers also show how to create, update, and remove your own text and rectangles.

## Download

{% file src="/files/eFAE9rc7UArcJt0sFIXw" %}

Run `npm install` and `npm run build` inside the downloaded project, then upload `dist/my-indicator-project.js` to FTO.

## What you can learn

* Group panel position and indicator settings with `AddSeparator` and typed inputs.
* Read `iMA`, `iRSI`, `iADX`, and `iATR` for the last completed bar (`index = 1`).
* Display a panel with `ObjectType.RECTANGLE` and `ObjectType.TEXT`, without `CreateBuffer` or `CreatePlot`.
* Update text and accent colors, and delete only objects owned by this indicator instance.

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                                                                                                    |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Panel X/Y position; shared price source; MA type and periods; RSI period and oversold/overbought levels; ADX period and strength threshold; ATR period.                                                     |
| Output                 | A screen-positioned card on the main chart. MA reports relative direction; RSI and ADX show values and labels; ATR shows a price-range value.                                                               |
| History and edge cases | The panel waits for sufficient bars or valid readings. It warns when fast MA period is not below slow MA period or when RSI levels overlap. It reads the previous completed bar, not the still-forming bar. |

## Pattern to reuse

Read the values together in `OnCalculate`, then update named chart objects. Use `SCREEN_COORDS` for pixel placement, `MIDDLE_LINE = false` for filled rectangles without a center line, and `DeleteObjectsByPrefix` for cleanup. `ANCHOR_POINT` uses numeric text-anchor codes; this example names the codes it needs. See [SetObjectProperty](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/objects/properties-text-and-anchors/set-object-property) for the full mapping.

The full source below is the same class included in the ZIP.

```typescript
import {
    Indicator,
    InputEnum,
    InputNumber,
    MovingAverageType,
    ObjectProperty,
    ObjectType,
    OutputWindow,
    PriceType
} from 'forex-tester-custom-indicator-api'

const PANEL_WIDTH = 340
const PANEL_HEIGHT = 250
const HEADER_HEIGHT = 52
const ROW_HEIGHT = 36
const ROW_GAP = 4
// ObjectProperty.ANCHOR_POINT uses numeric pins for text objects.
const ANCHOR_LEFT_CENTER = 1
const ANCHOR_RIGHT_CENTER = 5
const ANCHOR_CENTER = 8
const COLORS = {
    background: '#101A2A',
    header: '#1A2B42',
    row: '#192A40',
    badge: '#2A435A',
    accent: '#55B7D6',
    title: '#F4F7FC',
    label: '#AABBD0',
    muted: '#8295AE',
    badgeText: '#ACDDEB',
    bullish: '#61D5A0',
    bearish: '#F17E83',
    overbought: '#F5BD72',
    oversold: '#77C8E9',
    strong: '#B6A4F6',
    value: '#E0E9F6'
} as const

type PanelRow = 'ma' | 'rsi' | 'adx' | 'atr'
type IndicatorValues = { fastMA: number; slowMA: number; rsi: number; adx: number; atr: number }

export default class MarketConditionsPanel extends Indicator {
    private readonly objectPrefix = `MarketConditions-${Math.random().toString(36).slice(2)}-`
    private panelReady = false
    private panelNeedsRebuild = false

    public panelX!: InputNumber
    public panelY!: InputNumber
    public maType!: InputEnum<MovingAverageType>
    public priceSource!: InputEnum<PriceType>
    public fastMAPeriod!: InputNumber
    public slowMAPeriod!: InputNumber
    public rsiPeriod!: InputNumber
    public rsiOversold!: InputNumber
    public rsiOverbought!: InputNumber
    public adxPeriod!: InputNumber
    public adxThreshold!: InputNumber
    public atrPeriod!: InputNumber

    public override OnInit(): void {
        this.api.SetIndicatorShortName('Market Conditions Panel')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)
        this.api.HideIndicatorValuesOnPriceScale()

        this.api.AddSeparator('Panel position')
        this.panelX = this.api.CreateIntegerInput('Panel X', 24, 0, 10000)
        this.panelY = this.api.CreateIntegerInput('Panel Y', 100, 0, 10000)

        this.api.AddSeparator('Common settings')
        this.priceSource = this.api.CreateApplyToPriceInput('Price source', PriceType.CLOSE)

        this.api.AddSeparator('Moving averages')
        this.maType = this.api.CreateMATypeInput('MA type', MovingAverageType.EMA)
        this.fastMAPeriod = this.api.CreateIntegerInput('Fast MA period', 12, 2, 500)
        this.slowMAPeriod = this.api.CreateIntegerInput('Slow MA period', 26, 2, 500)

        this.api.AddSeparator('RSI')
        this.rsiPeriod = this.api.CreateIntegerInput('RSI period', 14, 2, 500)
        this.rsiOversold = this.api.CreateIntegerInput('RSI oversold', 30, 1, 99)
        this.rsiOverbought = this.api.CreateIntegerInput('RSI overbought', 70, 1, 99)

        this.api.AddSeparator('ADX')
        this.adxPeriod = this.api.CreateIntegerInput('ADX period', 14, 2, 500)
        this.adxThreshold = this.api.CreateIntegerInput('ADX threshold', 25, 1, 100)

        this.api.AddSeparator('ATR')
        this.atrPeriod = this.api.CreateIntegerInput('ATR period', 14, 2, 500)
    }

    public override OnShow(): void {
        this.ensurePanel()
    }

    public override OnCalculate(index: number): void {
        // The panel is not a history plot, so skip historical calculation callbacks.
        if (index !== 0 || !this.ensurePanel()) return

        if (!this.hasEnoughHistory()) {
            this.showWaitingState()
            return
        }

        const values = this.readIndicatorValues()
        if (!this.areValuesReady(values)) {
            this.showWaitingState()
            return
        }

        this.updateRows(values)
    }

    private hasEnoughHistory(): boolean {
        // Wait for enough history before showing readings for the configured periods.
        const requiredBars = Math.max(
            this.fastMAPeriod.value + 2,
            this.slowMAPeriod.value + 2,
            this.rsiPeriod.value + 2,
            this.adxPeriod.value * 4,
            this.atrPeriod.value + 2
        )
        return this.api.Bars() >= requiredBars
    }

    private readIndicatorValues(): IndicatorValues {
        const symbol = this.api.Symbol()
        const timeframe = this.api.Timeframe()
        // Bar 0 is still forming; the panel reports the latest completed bar.
        const closedBar = 1
        const priceSource = this.priceSource.value
        const fastMA = this.api.iMA(
            symbol,
            timeframe,
            this.fastMAPeriod.value,
            0,
            this.maType.value,
            priceSource,
            closedBar
        )
        const slowMA = this.api.iMA(
            symbol,
            timeframe,
            this.slowMAPeriod.value,
            0,
            this.maType.value,
            priceSource,
            closedBar
        )
        const rsi = this.api.iRSI(symbol, timeframe, closedBar, this.rsiPeriod.value, priceSource, 0)
        const adx = this.api.iADX(symbol, timeframe, closedBar, this.adxPeriod.value, priceSource, 0)
        const atr = this.api.iATR(symbol, timeframe, closedBar, this.atrPeriod.value, priceSource)
        return { fastMA, slowMA, rsi, adx, atr }
    }

    private areValuesReady({ fastMA, slowMA, rsi, adx, atr }: IndicatorValues): boolean {
        return (
            Number.isFinite(fastMA) &&
            Number.isFinite(slowMA) &&
            fastMA !== 0 &&
            slowMA !== 0 &&
            Number.isFinite(rsi) &&
            rsi >= 0 &&
            rsi <= 100 &&
            Number.isFinite(adx) &&
            adx >= 0 &&
            Number.isFinite(atr) &&
            atr >= 0
        )
    }

    private updateRows({ fastMA, slowMA, rsi, adx, atr }: IndicatorValues): void {
        if (this.fastMAPeriod.value >= this.slowMAPeriod.value) this.setRow('ma', 'Set fast < slow', COLORS.overbought)
        else if (fastMA > slowMA) this.setRow('ma', 'Fast > Slow', COLORS.bullish)
        else if (fastMA < slowMA) this.setRow('ma', 'Fast < Slow', COLORS.bearish)
        else this.setRow('ma', 'Equal', COLORS.muted)

        if (this.rsiOversold.value >= this.rsiOverbought.value) {
            this.setRow('rsi', 'Check RSI levels', COLORS.overbought)
        } else if (rsi >= this.rsiOverbought.value) {
            this.setRow('rsi', `${rsi.toFixed(2)}  Overbought`, COLORS.overbought)
        } else if (rsi <= this.rsiOversold.value) {
            this.setRow('rsi', `${rsi.toFixed(2)}  Oversold`, COLORS.oversold)
        } else {
            this.setRow('rsi', `${rsi.toFixed(2)}  Neutral`, COLORS.value)
        }

        // ADX measures strength, not bullish or bearish direction.
        this.setRow(
            'adx',
            `${adx.toFixed(2)}  ${adx >= this.adxThreshold.value ? 'Strong' : 'Weak'}`,
            adx >= this.adxThreshold.value ? COLORS.strong : COLORS.muted
        )

        // ATR is in price units, so it has no fixed strong/weak threshold.
        this.setRow('atr', atr.toFixed(this.api.Digits()), COLORS.value)
    }

    public override OnHide(): void {
        this.removePanel()
    }

    public override OnParamsChange(): void {
        this.panelNeedsRebuild = true
    }

    public override OnDeinit(): void {
        this.removePanel()
    }

    private ensurePanel(): boolean {
        if (this.api.GetChartInformation() === null) return false
        if (this.panelNeedsRebuild) {
            this.removePanel()
            this.panelNeedsRebuild = false
        }
        if (this.panelReady && this.api.DoesObjectExist(0, this.name('background'), true)) return true

        const x = this.panelX.value
        const y = this.panelY.value
        const rowStart = y + HEADER_HEIGHT + 8
        const rowCenter = (index: number) => rowStart + index * (ROW_HEIGHT + ROW_GAP) + ROW_HEIGHT / 2

        if (
            !this.addRectangle('background', x, y, PANEL_WIDTH, PANEL_HEIGHT, COLORS.background) ||
            !this.addRectangle('header', x, y, PANEL_WIDTH, HEADER_HEIGHT, COLORS.header) ||
            !this.addRectangle('accent', x, y, PANEL_WIDTH, 3, COLORS.accent) ||
            !this.addRectangle('badge', x + PANEL_WIDTH - 104, y + 16, 88, 23, COLORS.badge)
        )
            return false

        for (const [rowIndex, row] of (['ma', 'rsi', 'adx', 'atr'] as PanelRow[]).entries()) {
            const top = rowStart + rowIndex * (ROW_HEIGHT + ROW_GAP)
            if (
                !this.addRectangle(`${row}-background`, x + 10, top, PANEL_WIDTH - 20, ROW_HEIGHT, COLORS.row) ||
                !this.addRectangle(`${row}-accent`, x + 10, top + 7, 3, ROW_HEIGHT - 14, COLORS.muted)
            )
                return false
        }

        const text = [
            ['title', x + 18, y + 22, ANCHOR_LEFT_CENTER, 'MARKET CONDITIONS', COLORS.title, 15],
            ['subtitle', x + 18, y + 42, ANCHOR_LEFT_CENTER, 'MA  /  MOMENTUM  /  VOLATILITY', COLORS.muted, 10],
            ['badge-text', x + PANEL_WIDTH - 60, y + 28, ANCHOR_CENTER, 'CLOSED BAR', COLORS.badgeText, 10],
            [
                'ma-label',
                x + 26,
                rowCenter(0),
                ANCHOR_LEFT_CENTER,
                `${MovingAverageType[this.maType.value]} ${this.fastMAPeriod.value} / ${this.slowMAPeriod.value}`,
                COLORS.label,
                12
            ],
            [
                'rsi-label',
                x + 26,
                rowCenter(1),
                ANCHOR_LEFT_CENTER,
                `RSI ${this.rsiPeriod.value}`,
                COLORS.label,
                12
            ],
            [
                'adx-label',
                x + 26,
                rowCenter(2),
                ANCHOR_LEFT_CENTER,
                `ADX ${this.adxPeriod.value}`,
                COLORS.label,
                12
            ],
            [
                'atr-label',
                x + 26,
                rowCenter(3),
                ANCHOR_LEFT_CENTER,
                `ATR ${this.atrPeriod.value}`,
                COLORS.label,
                12
            ],
            ['ma-value', x + PANEL_WIDTH - 24, rowCenter(0), ANCHOR_RIGHT_CENTER, '--', COLORS.muted, 12],
            ['rsi-value', x + PANEL_WIDTH - 24, rowCenter(1), ANCHOR_RIGHT_CENTER, '--', COLORS.muted, 12],
            ['adx-value', x + PANEL_WIDTH - 24, rowCenter(2), ANCHOR_RIGHT_CENTER, '--', COLORS.muted, 12],
            ['atr-value', x + PANEL_WIDTH - 24, rowCenter(3), ANCHOR_RIGHT_CENTER, '--', COLORS.muted, 12],
            [
                'footer',
                x + 18,
                y + 232,
                ANCHOR_LEFT_CENTER,
                `RSI zones ${this.rsiOversold.value}/${this.rsiOverbought.value}   ·   ADX threshold ${this.adxThreshold.value}`,
                COLORS.muted,
                11
            ]
        ] as const

        for (const [name, x, y, anchor, value, color, fontSize] of text) {
            if (!this.addText(name, x, y, anchor, value, color, fontSize)) return false
        }
        this.panelReady = true
        return true
    }

    private addRectangle(key: string, x: number, y: number, width: number, height: number, fill: string): boolean {
        const name = this.name(key)
        if (!this.api.DoesObjectExist(0, name, true) && !this.api.CreateObject(0, name, ObjectType.RECTANGLE, 0))
            return false
        const properties: Array<[ObjectProperty, unknown]> = [
            [ObjectProperty.MIDDLE_LINE, false],
            [ObjectProperty.SCREEN_COORDS, true],
            [ObjectProperty.XDISTANCE, x],
            [ObjectProperty.YDISTANCE, y],
            [ObjectProperty.XSIZE, width],
            [ObjectProperty.YSIZE, height],
            [ObjectProperty.FILL_INSIDE, 1],
            [ObjectProperty.FILL_COLOR, fill],
            [ObjectProperty.BORDER, false],
            [ObjectProperty.LOCKED, 1]
        ]
        return properties.every(([property, value]) => this.api.SetObjectProperty(0, name, property, value, true))
    }

    private addText(
        key: string,
        x: number,
        y: number,
        anchor: number,
        value: string,
        color: string,
        fontSize: number
    ): boolean {
        const name = this.name(key)
        if (!this.api.DoesObjectExist(0, name, true) && !this.api.CreateObject(0, name, ObjectType.TEXT, 0))
            return false
        const properties: Array<[ObjectProperty, unknown]> = [
            [ObjectProperty.SCREEN_COORDS, true],
            [ObjectProperty.XDISTANCE, x],
            [ObjectProperty.YDISTANCE, y],
            [ObjectProperty.ANCHOR_POINT, anchor],
            [ObjectProperty.LOCKED, 1]
        ]
        return (
            properties.every(([property, propertyValue]) =>
                this.api.SetObjectProperty(0, name, property, propertyValue, true)
            ) && this.api.SetObjectText(0, name, value, fontSize, 'Roboto Flex', color, true) === true
        )
    }

    private setRow(row: PanelRow, value: string, color: string): void {
        this.api.SetObjectText(0, this.name(`${row}-value`), value, 12, 'Roboto Flex', color, true)
        this.api.SetObjectProperty(0, this.name(`${row}-accent`), ObjectProperty.FILL_COLOR, color, true)
    }

    private showWaitingState(): void {
        for (const row of ['ma', 'rsi', 'adx', 'atr'] as PanelRow[]) {
            this.setRow(row, 'Waiting for data', COLORS.muted)
        }
    }

    private name(key: string): string {
        return this.objectPrefix + key
    }

    private removePanel(): void {
        this.api.DeleteObjectsByPrefix(0, this.objectPrefix, -1, true)
        this.panelReady = false
    }
}
```


# Pivot Points High/Low

Download a pivot-high and pivot-low indicator project that marks confirmed swing points with price labels on the chart.

**Pivot Points High/Low** marks confirmed swing highs and lows with price labels on the chart. It uses the chart's high and low series and draws label objects rather than indicator plots.

## When to copy this pattern

Copy this example when you need to mark pivot points on a chart, give highs and lows separate lookback settings, or style chart labels through indicator inputs.

## Download

{% file src="/files/bzPHSd4dEju0AawhaZSg" %}

Run `npm install` and `npm run build` inside the downloaded project, then upload `dist/my-indicator-project.js` to FTO.

## What you can learn

* Use [iPivotHigh](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/time-series/i-pivot-high) and [iPivotLow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/time-series/i-pivot-low) with separate left/right lengths.
* Read the matching time and price with `iTime`, `iHigh`, and `iLow` before placing a label.
* Draw `LABEL_DOWN` at pivot highs and `LABEL_UP` at pivot lows, with separate size and color inputs.
* Refresh objects across the visible chart range and remove owned labels on parameter changes, hide, or removal.

## Inputs, output, and limits

| Topic        | Behavior                                                                                                                                         |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Inputs       | Separate left and right lengths for high and low pivots; label size, text color, and label color for each direction.                             |
| Output       | Price labels at confirmed pivot highs and lows on the main chart. No indicator buffers or plots.                                                 |
| Confirmation | A pivot needs enough older bars on the left and newer bars on the right. A label cannot appear until the selected right-side bars are available. |

## Pattern to reuse

Check each visible bar with `iPivotHigh` and `iPivotLow`, then create chart labels at its time and price. Name every object with a consistent prefix so `DeleteObjectsByPrefix` can remove the indicator's labels. See [Chart object cleanup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/objects/creation-and-cleanup/chart-object-cleanup) for ownership guidance.

The full source below is the same class included in the ZIP.

```typescript
import {
    Indicator,
    InputNumber,
    InputColor,
    InputEnum,
    OutputWindow,
    ObjectType,
    FontSize,
    InputTab,
    ObjectProperty,
    FTODate
} from 'forex-tester-custom-indicator-api'

export default class PivotPointsHighLow extends Indicator {
    private static readonly Prefix: string = `PivotPointsHighLow-${crypto.randomUUID()}-`

    public HighLeftLength!: InputNumber
    public HighRightLength!: InputNumber
    public LowLeftLength!: InputNumber
    public LowRightLength!: InputNumber

    public HighLabelSize!: InputEnum<FontSize>
    public HighTextColor!: InputColor
    public HighLabelColor!: InputColor
    public LowLabelSize!: InputEnum<FontSize>
    public LowTextColor!: InputColor
    public LowLabelColor!: InputColor

    private _isFirstParamsChange = true

    public OnInit(): void {
        this.api.SetIndicatorShortName('Pivot Points High/Low')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)
        this.api.RecalculateMeAlways()

        this.HighLeftLength = this.api.CreateIntegerInput('High Left Length', 10, 1, 100)
        this.HighRightLength = this.api.CreateIntegerInput('High Right Length', 10, 1, 100)
        this.LowLeftLength = this.api.CreateIntegerInput('Low Left Length', 10, 1, 100)
        this.LowRightLength = this.api.CreateIntegerInput('Low Right Length', 10, 1, 100)

        this.HighLabelSize = this.api.CreateFontSizeInput('High Label Size', FontSize.Tiny, InputTab.STYLE)
        this.HighTextColor = this.api.CreateColorInput('High Text Color', '#ffffff', InputTab.STYLE)
        this.HighLabelColor = this.api.CreateColorInput('High Label Color', '#1b70e2', InputTab.STYLE)
        this.LowLabelSize = this.api.CreateFontSizeInput('Low Label Size', FontSize.Tiny, InputTab.STYLE)
        this.LowTextColor = this.api.CreateColorInput('Low Text Color', '#ffffff', InputTab.STYLE)
        this.LowLabelColor = this.api.CreateColorInput('Low Label Color', '#1b70e2', InputTab.STYLE)
    }

    public OnCalculate(index: number): void {
        const chartInfo = this.api.GetChartInformation()
        if (chartInfo === null || chartInfo === undefined) return

        if (index !== chartInfo.lastIndex || chartInfo.firstIndex < 0 || chartInfo.lastIndex < 0) return

        this.removeAllIndicatorObjects()

        const symbol = this.api.Symbol()
        const timeframe = this.api.Timeframe()
        for (let i = chartInfo.firstIndex; i >= chartInfo.lastIndex; i--) {
            const isHighPivot = this.api.iPivotHigh(
                symbol,
                timeframe,
                this.HighLeftLength.value,
                this.HighRightLength.value,
                i
            )
            const isLowPivot = this.api.iPivotLow(
                symbol,
                timeframe,
                this.LowLeftLength.value,
                this.LowRightLength.value,
                i
            )

            if (isHighPivot) {
                this.drawLabel(this.api.iTime(symbol, timeframe, i), this.api.iHigh(symbol, timeframe, i), true)
            }

            if (isLowPivot) {
                this.drawLabel(this.api.iTime(symbol, timeframe, i), this.api.iLow(symbol, timeframe, i), false)
            }
        }

        this._isFirstParamsChange = false
    }

    public OnParamsChange(): void {
        this.removeAllIndicatorObjects()
    }

    public OnHide(): void {
        this.removeAllIndicatorObjects()
    }

    public OnDeinit(): void {
        this.removeAllIndicatorObjects()
    }

    private drawLabel(time: FTODate, price: number, isHighPivot: boolean): void {
        const pivotName = isHighPivot ? 'high' : 'low'
        const objName = `${PivotPointsHighLow.Prefix}${pivotName}${time.valueOf()}`
        const textColor = isHighPivot ? this.HighTextColor.value : this.LowTextColor.value
        const labelColor = isHighPivot ? this.HighLabelColor.value : this.LowLabelColor.value
        const labelType = isHighPivot ? ObjectType.LABEL_DOWN : ObjectType.LABEL_UP
        const labelSize = isHighPivot ? this.HighLabelSize.value : this.LowLabelSize.value

        if (this.api.DoesObjectExist(0, objName, true)) {
            this.api.DeleteObject(0, objName, true)
        }

        this.api.CreateObject(0, objName, labelType, 0, time, price, undefined, undefined, undefined, undefined, true)
        this.api.SetObjectProperty(0, objName, ObjectProperty.TEXT_COLOR, textColor, true)
        this.api.SetObjectProperty(0, objName, ObjectProperty.COLOR, labelColor, true)
        this.api.SetObjectProperty(0, objName, ObjectProperty.TEXT, price.toFixed(this.api.Digits()).toString(), true)
        this.api.SetObjectProperty(0, objName, ObjectProperty.FONT_SIZE, labelSize, true)
        this.api.SetObjectProperty(0, objName, ObjectProperty.BACK, false, true)
    }

    private removeAllIndicatorObjects(): void {
        if (this._isFirstParamsChange) {
            return
        }

        this.api.DeleteObjectsByPrefix(0, PivotPointsHighLow.Prefix, 0, true)
    }
}
```


# Round Numbers

Round Numbers built-in indicator — download the project and explore psychological round-number price levels on the chart.

The **Round Numbers** indicator draws horizontal levels at psychologically significant prices (e.g. 1.1000, 1.1050). Traders use them as support/resistance and order-cluster zones.

***

## When to copy this pattern

Copy Round Numbers when you draw horizontal levels at psychologically round prices derived from symbol digits — support/resistance grids without manual line drawing.

## Download

{% file src="/files/uAEkN0pmOXYXYAx6h7s3" %}

***

## What you can learn

* Deriving step size from `Point()` and user step inputs
* Horizontal `ObjectType.H_LINE` chart objects at computed round prices
* Redrawing only on the latest bar and deleting owned objects in `OnDeinit`

## Inputs, output, and limits

| Topic                  | Behavior                                                                                                                                                                                                                                |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Inputs                 | Three groups configure counts, point spacing and stroke; step 0 disables a group. Show values controls price labels.                                                                                                                    |
| Output                 | Horizontal chart objects, without plot buffers. Larger spacings take priority and duplicate prices are omitted.                                                                                                                         |
| History and edge cases | Instances of this class share the static object-name prefix. Hide suppresses redraw without deleting levels; remove deletes matching objects. Show resets redraw state. The shared prefix does not isolate multiple instances' objects. |

## Pattern to reuse

Derive step sizes from `Point()` and integer inputs, then create named horizontal line objects with `CreateObject` / `SetObjectProperty` on the latest bar only. `OnHide` suppresses redraw, `OnDeinit` deletes matching objects, and `OnShow` resets the redraw state. For independent object ownership across multiple instances, see [Chart object cleanup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/objects/creation-and-cleanup/chart-object-cleanup).

```typescript
export default class RoundNumbers extends Indicator {
    private static readonly Prefix: string = `RoundNumbers-${crypto.randomUUID()}-`

    private _lastBarTime = 0
    private objectsVisible = true

    public upperLevels1!: InputNumber
    public lowerLevels1!: InputNumber
    public levelsStep1!: InputNumber
    public levelStyle1!: InputStroke

    public upperLevels2!: InputNumber
    public lowerLevels2!: InputNumber
    public levelsStep2!: InputNumber
    public levelStyle2!: InputStroke

    public upperLevels3!: InputNumber
    public lowerLevels3!: InputNumber
    public levelsStep3!: InputNumber
    public levelStyle3!: InputStroke

    public showValues!: InputBool

    public override OnInit(): void {
        this.api.SetIndicatorShortName('Round Numbers')
        this.api.SetIndicatorOutputWindow(OutputWindow.CHART)
        this.api.HideIndicatorValuesOnPriceScale()

        this.api.AddSeparator('Group 1')
        this.upperLevels1 = this.api.CreateIntegerInput('Upper levels 1', 3, 0, 50)
        this.lowerLevels1 = this.api.CreateIntegerInput('Lower levels 1', 3, 0, 50)
        this.levelsStep1 = this.api.CreateIntegerInput('Levels step 1', 200, 0, 1000000)
        this.levelStyle1 = this.api.CreateStrokeInput('Levels 1 style', true, '#0f1ccf', PenStyle.SOLID, 2)

        this.api.AddSeparator('Group 2')
        this.upperLevels2 = this.api.CreateIntegerInput('Upper levels 2', 5, 0, 50)
        this.lowerLevels2 = this.api.CreateIntegerInput('Lower levels 2', 5, 0, 50)
        this.levelsStep2 = this.api.CreateIntegerInput('Levels step 2', 100, 0, 1000000)
        this.levelStyle2 = this.api.CreateStrokeInput('Levels 2 style', true, '#d2e716', PenStyle.DASH, 1)

        this.api.AddSeparator('Group 3')
        this.upperLevels3 = this.api.CreateIntegerInput('Upper levels 3', 10, 0, 50)
        this.lowerLevels3 = this.api.CreateIntegerInput('Lower levels 3', 10, 0, 50)
        this.levelsStep3 = this.api.CreateIntegerInput('Levels step 3', 50, 0, 1000000)
        this.levelStyle3 = this.api.CreateStrokeInput('Levels 3 style', true, '#ff6600', PenStyle.DASH_DOT, 1)

        this.api.AddSeparator('')
        this.showValues = this.api.CreateBoolInput('Show values', true)
    }

    public override OnCalculate(index: number): void {
        if (!this.objectsVisible) {
            return
        }
        const chartInfo = this.api.GetChartInformation()
        if (!chartInfo || chartInfo.firstIndex < 0 || chartInfo.lastIndex < 0) {
            return
        }
        if (index !== chartInfo.lastIndex) {
            return
        }

        const time = this.api.Time(0)
        const barTime = time.valueOf()
        if (barTime === this._lastBarTime) {
            return
        }
        this._lastBarTime = barTime

        const close = this.api.Close(0)
        const point = this.api.Point()

        this.removeAllLevels()

        if (!this.levelStyle1.isVisible && !this.levelStyle2.isVisible && !this.levelStyle3.isVisible) {
            return
        }

        const digits = this.api.Digits()
        const priceKey = (p: number) => Math.round(p * Math.pow(10, digits))
        const drawnPrices = new Set<number>()

        const groups: Array<{
            step: number
            upper: number
            lower: number
            style: InputStroke
            prefix: string
            stepInput: number
        }> = [
            {
                step: Math.max(point, point * this.levelsStep1.value),
                upper: this.upperLevels1.value,
                lower: this.lowerLevels1.value,
                style: this.levelStyle1,
                prefix: 'Major',
                stepInput: this.levelsStep1.value
            },
            {
                step: Math.max(point, point * this.levelsStep2.value),
                upper: this.upperLevels2.value,
                lower: this.lowerLevels2.value,
                style: this.levelStyle2,
                prefix: 'Minor',
                stepInput: this.levelsStep2.value
            },
            {
                step: Math.max(point, point * this.levelsStep3.value),
                upper: this.upperLevels3.value,
                lower: this.lowerLevels3.value,
                style: this.levelStyle3,
                prefix: 'Trace',
                stepInput: this.levelsStep3.value
            }
        ]
            .filter((g) => g.style.isVisible && g.stepInput !== 0)
            .sort((a, b) => b.step - a.step)

        for (const group of groups) {
            let counter = 0
            for (let i = 0; i < group.upper; i++) {
                const price = Math.ceil(close / group.step) * group.step + i * group.step
                const key = priceKey(price)
                if (!drawnPrices.has(key)) {
                    this.drawLine(
                        `${RoundNumbers.Prefix}${group.prefix}-up-${counter}`,
                        time,
                        price,
                        group.style.style,
                        group.style.width,
                        group.style.color,
                        this.showValues.value
                    )
                    drawnPrices.add(key)
                    counter++
                }
            }
            counter = 0
            for (let i = 0; i < group.lower; i++) {
                const price = Math.floor(close / group.step) * group.step - i * group.step
                const key = priceKey(price)
                if (!drawnPrices.has(key)) {
                    this.drawLine(
                        `${RoundNumbers.Prefix}${group.prefix}-down-${counter}`,
                        time,
                        price,
                        group.style.style,
                        group.style.width,
                        group.style.color,
                        this.showValues.value
                    )
                    drawnPrices.add(key)
                    counter++
                }
            }
        }
    }

    public override OnDeinit(): void {
        this.removeAllLevels()
    }

    public override OnHide(): void {
        // Adapted reusable pattern: suppress redraw; do not delete permanent objects here
        this.objectsVisible = false
    }

    public override OnShow(): void {
        this.objectsVisible = true
        this._lastBarTime = 0
    }

    public override OnParamsChange(): void {
        this._lastBarTime = 0
    }

    private drawLine(
        name: string,
        time: FTODate,
        price: number,
        style: PenStyle,
        width: number,
        color: string,
        showValue: boolean
    ): void {
        this.api.CreateObject(0, 
            name,
            ObjectType.H_LINE,
            0,
            time,
            price,
            undefined,
            undefined,
            undefined,
            undefined,
            true
        )
        this.api.SetObjectProperty(0, name, ObjectProperty.COLOR, color)
        this.api.SetObjectProperty(0, name, ObjectProperty.WIDTH, width)
        this.api.SetObjectProperty(0, name, ObjectProperty.STYLE, style)
        this.api.SetObjectProperty(0, name, ObjectProperty.SHOW_PRICE_LABEL, showValue)
    }

    private removeAllLevels(): void {
        const objCount = this.api.GetObjectCount(0)
        if (objCount !== null) {
            for (let i = objCount - 1; i >= 0; i--) {
                const name = this.api.GetObjectName(0, i)
                if (name?.startsWith(RoundNumbers.Prefix)) {
                    this.api.DeleteObject(0, name)
                }
            }
        }
    }
}
```


# API reference

Look up the exact method you need while building or debugging a custom indicator.

{% hint style="info" %}
**Snippet convention:** Most API examples are class-method fragments. Imports, the surrounding `export default class … extends Indicator`, and already-declared fields may be omitted. For a complete scaffold, use [Step 5 of the Cursor tutorial](https://fto-2.gitbook.io/fto-indicators-docs/tutorial-create-indicator-with-cursor/step-5-start-building) and the [lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle) pages.
{% endhint %}

{% hint style="info" %}
**Runtime boundaries:** Hidden indicators stop receiving `OnCalculate`. Showing an indicator invalidates its calculation state so FTO can recount the required range. For clickable chart buttons, use `AddActionButton` state callbacks.
{% endhint %}

## Build an indicator in this order

1. [Lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle) — `OnInit`, `OnCalculate`, cleanup, and optional hooks.
2. [Inputs](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs) — parameters users change in the settings dialog.
3. [Plots and buffers](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers) — store values, draw lines/histograms/fills, and detect series crosses.
4. [Current symbol](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/current-symbol) and [time series](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/time-series) — read prices, volume, and bar indexes.
5. [Indicator configuration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration) — name, pane, oscillator levels, precision, and recalculation behavior.

## Extend the chart

Before reading another indicator, use [Reading indicators](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/technical-indicators/reading-indicators) to distinguish history readiness, an empty output and an invalid index. For another timeframe, follow [Multi-timeframe data](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/time-series/multi-timeframe) instead of copying the chart's bar index into another series.

For time-based calculations, start with [Time conventions](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/date-time/time-conventions) and [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating).

* [Chart](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/chart) — visible geometry, coordinate conversion, and display refresh.
* [Objects](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/objects) — labels, lines, and other drawn chart objects.

[Action-button workflow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/objects/action-buttons/action-button-workflow) shows creation, callbacks, state updates and cleanup together.

## Market, account, and testing

* [Technical indicators](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/technical-indicators) — built-in MA, RSI, MACD helpers.
* [Date time](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/date-time) — bar time and calendar helpers.
* [Account](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/account) and [symbols and market information](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/symbols-and-market-info) — account and symbol metadata.
* [Testing](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/testing) — detect and pause backtest playback.
* [Errors and utilities](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/errors-and-utilities) — alerts, logging, and helpers.
* [Types](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types) — enums and value objects used across the API.


# Lifecycle

Wire your indicator through the hooks FTO calls from first load to removal.

## When to open this section

You are deciding where setup, per-bar math, parameter reactions, and cleanup belong — or you need the signature for a specific hook.

## Hooks by responsibility

The lifecycle has fixed boundaries: FTO attaches the API before `OnInit`, calls the initial `OnParamsChange` after `OnInit`, and treats `OnDeinit` as terminal. Between those boundaries, chart, parameter, and visibility events may interleave.

### Once per instance

* [OnInit](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-init) — register inputs, create buffers, bind plots, subscribe to events.
* [OnDeinit](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-deinit) — final cleanup when the indicator is removed.

### Per bar

* [OnCalculate](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-calculate) — compute one requested bar index when FTO needs it.

### Event-driven

* [OnParamsChange](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-params-change) — initialize and refresh offsets, shifts, or derived state.
* [OnShow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-show) / [OnHide](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-hide) — manage visibility and owned chart objects; hidden indicators do not calculate.

Start with the [indicator lifecycle overview](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle) for a full end-to-end example before opening individual method pages.


# Indicator lifecycle

## Purpose

Place setup, calculation, parameter reactions, and cleanup in the lifecycle hooks FTO calls for indicators — setup once, calculate per bar, react to changes, then clean up.

## What you will wire up

* Inputs, buffers, and plots in `OnInit`
* Per-bar values in `OnCalculate`
* Optional reactions in `OnParamsChange`, visibility hooks, and `OnDeinit`

## Workflow

1. **OnInit** (once per runtime instance) — set the display name, create inputs, allocate buffers, declare plot count, bind visible plots.
2. **OnCalculate** (for requested bar indexes) — read prices or earlier buffer values at `index`, write results at the same `index`. FTO reuses valid cached buffer values, so a calculation pass does not necessarily revisit every bar. Guard lookback with `Bars()` when you read history:
   * Span loop over `index..index + period - 1`: `index + period > Bars()`
   * Direct access of `index + period`: `index + period >= Bars()`
3. **OnParamsChange** (initial and event-driven) — initialize derived settings immediately after `OnInit`, then refresh them after input edits. FTO can also call it while previewing boolean or enum option enablement. Input `.value` fields are updated for the values being evaluated.
4. **OnShow / OnHide** (event-driven) — hide, delete, or restore custom visuals tied to visibility. Hidden indicators stop receiving `OnCalculate`. Showing an indicator invalidates its calculation state, and FTO recounts the required range on a later calculation pass.
5. **OnDeinit** (once) — delete chart objects and release anything the indicator owns.

FTO attaches the API before `OnInit`, performs the initial `OnParamsChange` afterward, and never calculates again after `OnDeinit`. Other parameter and visibility events may interleave between those boundaries, so keep their handlers safe to repeat.

## Example

```typescript
export default class DifferenceIndicator extends Indicator {
    public Output!: IndexBuffer

    public override OnInit(): void {
        this.api.SetIndicatorShortName('Bar body')
        this.Output = this.api.CreateBuffer()
        this.api.SetPlotCount(1)
        this.api.CreatePlot(
            0,
            this.Output,
            'Close − Open',
            PlotType.LINE,
            PenStyle.SOLID,
            1,
            '#2962FF'
        )
    }

    public override OnCalculate(index: number): void {
        this.Output.setValue(index, this.api.Close(index) - this.api.Open(index))
    }

    public override OnDeinit(): void {
        this.api.DeleteObjectsByPrefix(0, 'DifferenceIndicator_', 0, true)
    }
}
```

## Related API

* [OnInit](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-init)
* [OnCalculate](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-calculate)
* [OnParamsChange](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-params-change)
* [OnDeinit](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-deinit)
* [Plot setup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup)


# OnCalculate

Fill indicator buffers for one requested bar when FTO needs history, invalidated values, or the latest bar.

## Signature

```typescript
OnCalculate(index: number): void
```

## Parameters

* `index` — Reverse bar index being calculated. `0` is the newest bar; larger values move backward in time.

## Returns

`void`.

## Usage

1. Treat `index` as the bar you are writing right now. Read older bars with `index + offset`.
2. Before reading history, guard by how far you read:
   * Span loop over `index..index + period - 1`: `if (index + period > this.api.Bars()) return`
   * Direct access of `index + period`: `if (index + period >= this.api.Bars()) return`
3. Read prices with `Close(index + offset)`, `High(index + offset)`, and similar helpers.
4. Read prior buffer values with `buffer.getValue(index + 1)` when your formula depends on the previous bar.
5. Write every result with `buffer.setValue(index, value)` at the same `index` you received.
6. Account getters and unindexed quotes are current snapshots; they do not become historical just because `index` is historical.
7. Do not rely on every calculation pass visiting every historical bar. FTO reuses valid cached buffer values unless the indicator requests exact coverage with `RecalculateMeAlways`.

FTO calls `OnCalculate` for the bar indexes required by the current calculation range. It may skip already-valid cached bars, and it does not call this hook while the indicator is hidden. Keep the body fast because initial loads, invalidation, scrolling, and `RecalculateMeAlways` can still request many bars.

## Example

Self-contained calculation pattern. Declare the fields once in `OnInit` (see [OnInit](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-init)); this hook only fills buffers.

```typescript
public Period!: InputNumber
public MAType!: InputEnum<MovingAverageType>
public ApplyToPrice!: InputEnum<PriceType>
public MATempBuffer!: IndexBuffer
public MABuffer!: IndexBuffer

public override OnCalculate(index: number): void {
    if (index + this.Period.value > this.api.Bars()) {
        return
    }

    const value = this.api.GetMA(
        index,
        0,
        this.Period.value,
        this.MAType.value,
        this.ApplyToPrice.value,
        this.MATempBuffer.getValue(index + 1)
    )

    this.MATempBuffer.setValue(index, value)
    this.MABuffer.setValue(index, value)
}
```

## Related API

* [Safe indicator reads](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/technical-indicators/reading-indicators)
* [Multi-timeframe reads](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/time-series/multi-timeframe)
* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [Bar indexing](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/current-symbol/bar-indexing)
* [IndexBuffer.setValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/index-buffer/set-value)


# OnDeinit

Release chart objects and other owned resources when the user removes the indicator.

## Signature

```typescript
OnDeinit(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

1. Override when the indicator creates chart objects, custom timers, listeners outside FTO, or other external state.
2. Delete or detach everything you created — objects, labels, custom timers, and external handles.
3. Keep temporary hide/show behavior in `OnHide` / `OnShow`. Use `OnDeinit` for permanent teardown.

FTO calls this hook once when the indicator instance is destroyed. After it returns, the instance will not calculate again.

## Example

```typescript
private readonly objectName = 'MyIndicator_status'

public override OnDeinit(): void {
    this.removeTestText()
}

private removeTestText(): void {
    if (this.api.DoesObjectExist(0, this.objectName, true)) {
        this.api.DeleteObject(0, this.objectName, true)
    }
}
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [Chart-object cleanup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/objects/creation-and-cleanup/chart-object-cleanup)
* [OnHide](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-hide)


# OnHide

Hide or remove custom visuals when the user turns the indicator off without deleting it.

## Signature

```typescript
OnHide(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

1. Override when the indicator draws chart objects or maintains visibility-only state.
2. Hide or delete owned chart objects that must disappear immediately. `OnHide` cleanup is valid when `OnShow` or later `OnCalculate` calls can recreate those objects.
3. Keep only the state and external resources that must survive the next show. Final teardown still belongs in [OnDeinit](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-deinit).

FTO stops calling `OnCalculate` while the indicator is hidden.

## Example

```typescript
public override OnHide(): void {
    this.api.DeleteObjectsByPrefix(0, 'MyIndicator_', 0, true)
}
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [Chart-object cleanup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/objects/creation-and-cleanup/chart-object-cleanup)
* [OnShow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-show)
* [OnDeinit](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-deinit)


# OnInit

Run once when the indicator loads — register everything `OnCalculate` will need later.

## Signature

```typescript
OnInit(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

1. Set the display name and output window if the indicator is not a simple overlay.
2. Create and register inputs so they appear in the settings dialog.
3. Create every `IndexBuffer` and store each in a class field.
4. Call `SetPlotCount`, then `CreatePlot` (or `SetPlotBuffer`) for each visible series.
5. Call configuration helpers such as `RecalculateMeAlways` or `SetIndicatorBackOffset` when your math requires them.

The runtime attaches the indicator API before invoking `OnInit`, invokes this hook exactly once per runtime instance, and calls the initial `OnParamsChange` after it returns. Do not read bar prices for ongoing calculation here — that belongs in `OnCalculate`.

## Example

```typescript
public MABuffer!: IndexBuffer

public override OnInit(): void {
    this.api.SetIndicatorShortName('Moving Average')
    this.MABuffer = this.api.CreateBuffer()
    this.api.SetPlotCount(1)
    this.api.CreatePlot(
        0,
        this.MABuffer,
        'Moving Average',
        PlotType.LINE,
        PenStyle.SOLID,
        1,
        '#FF0000'
    )
}
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [Plot setup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup)


# OnParamsChange

Initialize and refresh derived settings after setup and while indicator inputs are evaluated.

## Signature

```typescript
OnParamsChange(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

1. FTO calls this once immediately after `OnInit`, so use it to initialize configuration derived from default input values.
2. FTO calls it again after applied input edits. Read the values being evaluated through input `.value` fields.
3. Boolean and enum changes can also trigger this hook while FTO previews which options should be enabled in the open settings dialog. Other uncommitted field values may not be synchronized during that preview.
4. Update `SetIndicatorBackOffset`, `SetPlotShift`, `SetPlotDrawBegin`, `SetLevelValue`, or other configuration that depends on inputs.
5. Keep the handler idempotent and inexpensive. Do not place one-time setup here or perform heavy full-history recomputation unless your design requires it.

Typical pattern: defaults load or the user changes a period → you recompute back offset and plot draw begin safely, even if the same values are processed more than once.

## Example

Inline offset calculation — no private helpers required. Declare `Period`, `MAType`, and `Shift` in `OnInit`.

```typescript
public Period!: InputNumber
public MAType!: InputEnum<MovingAverageType>
public Shift!: InputNumber

public override OnParamsChange(): void {
    // Simple period lookback; EMA/SMMA may need a larger warm-up in real indicators.
    const backOffset = Math.max(this.Period.value, 1)
    this.api.SetIndicatorBackOffset(backOffset + this.Shift.value)
    this.api.SetPlotShift(0, this.Shift.value)
    this.api.SetPlotDrawBegin(0, this.Period.value - 1 + this.Shift.value)
}
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [SetIndicatorBackOffset](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-back-offset)


# OnShow

Restore custom visuals when the user turns a hidden indicator back on.

## Signature

```typescript
OnShow(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

1. Override when hiding removed labels, objects, or UI state that should reappear on show.
2. Flip visibility flags or recreate lightweight visuals here.
3. Do not calculate historical buffers directly here. FTO invalidates the indicator's calculation state when it is shown and recounts the required range on a later calculation pass.
4. If `OnHide` deleted owned chart objects, either recreate lightweight objects here or let the next `OnCalculate` calls rebuild them.

Pair with [OnHide](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-hide) when you hide the same resources on toggle.

## Example

```typescript
private needsRedraw = true

public override OnShow(): void {
    this.needsRedraw = true
    // The next OnCalculate recreates this indicator's owned objects.
}
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [OnHide](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-hide)


# Inputs

Expose tunable parameters in the indicator settings dialog — periods, price sources, colors, sessions — so users can adapt your logic without editing code.

Start with [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration) for the create → store → read loop, then pick helpers below by the kind of control you need.

* [Input registration workflow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating)
* [Input and option types](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types)

## Value inputs

Numbers, text, booleans, enums, and chart-specific pickers:

* [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input)
* [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input)
* [CreateStringInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-string-input)
* [CreateBoolInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-bool-input)
* [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input)
* [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input)
* [CreateMATypeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-ma-type-input)
* [CreateApplyToPriceInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-apply-to-price-input)
* [CreateFontSizeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-font-size-input)
* [CreateTimeframeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-timeframe-input)

## Style inputs

Line appearance, fills, and visibility on the Style tab:

* [CreateColorInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-input)
* [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input)
* [CreateWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-width-input)
* [CreateStyleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-style-input)
* [CreateColorStyleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-style-input)
* [CreateColorWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-width-input)
* [CreateStyleWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-style-width-input)
* [CreateFillInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-fill-input)

## Date, time, and sessions

Calendar and session configuration (use [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating) to apply a filter):

* [CreateDateTimeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-date-time-input)
* [CreateDateOnlyInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-date-only-input)
* [CreateTimeOnlyInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-time-only-input)
* [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input)
* [CreateSessionValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-value)
* [CreateSessionsArrayInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-sessions-array-input)

## Advanced registration and metadata

Shape how settings appear, validate, and group in the dialog:

* [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input)
* [AddEnumValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/add-enum-value)
* [AddSeparator](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/add-separator)
* [SetInputRange](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-range)
* [SetInputDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-digits)
* [SetInputStep](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-step)
* [SetInputTooltip](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-tooltip)
* [SetInputShowNameWithParams](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-show-name-with-params)
* [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox)
* [SetInputEditable](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-editable)


# Registration and runtime use


# Input registration

Typed `Create*Input` helpers both register a settings row and return its live wrapper. Register in `OnInit`; store the wrapper on the instance and read it where your logic runs.

## Registration paths

| Path                                                                                                                 | What it does                                                                                                                                                                                                                          | Wrapper ownership                                                      |
| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| Typed `Create*Input` helper                                                                                          | Creates a wrapper, registers the settings row, and returns the live wrapper. Enum helpers also register all choice labels.                                                                                                            | Store the returned wrapper; registration is complete.                  |
| [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input) | Registers a wrapper that already exists. Returns `void`. For `InputType.ENUM`, [AddEnumValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/add-enum-value) supplies the labels afterward. | Requires a compatible unregistered wrapper supplied by an integration. |

The npm input types have protected constructors; there is no separate public factory for creating an unregistered number, boolean, or enum wrapper. Use the typed helper for these inputs. Registering its result again with `CreateInput` would add a duplicate row.

For dropdowns, choose between [all enum members, a custom member list](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input#example), and [zero-based indexed labels](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input#example). Each helper registers the complete choice list in one call.

## Lifecycle and ownership

1. Declare a typed field and assign it during each `OnInit` initialization pass. Do not guard registration with an instance-level “already initialized” flag: metadata discovery and active initialization can be separate passes.
2. Do not register the same wrapper again with `CreateInput`. Give controls distinct names, and use the same name for metadata setters.
3. Read `.value` or style/session members in `OnCalculate`. A number/string copied only in `OnInit` will not follow later edits. For session arrays, call `getSessions()` again because editing can replace its entries.
4. Use `OnParamsChange` when changed settings require rebuilding a dependent resource. Registration itself does not attach chart objects, change calculations, or place orders.
5. Validate values in logic where correctness matters. UI ranges and disabled controls do not replace history bounds, symbol constraints, or feature guards.

Inputs belong in the requested `InputTab`; helpers have defaults for calculation, style, and session controls. See [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab).

## Complete example

This registers a period and prints its live value only when it changes. It deliberately performs no calculation, drawing, or trading.

```typescript
import { Indicator, InputNumber } from 'forex-tester-custom-indicator-api'

export default class LiveInputIndicator extends Indicator {
    public Period!: InputNumber
    private reportedPeriod: number | undefined

    public override OnInit(): void {
        this.Period = this.api.CreateIntegerInput('Period', 14, 1, 500)
    }

    public override OnCalculate(index: number): void {
        if (index !== 0) return
        const value = this.Period.value
        if (value === this.reportedPeriod) return
        this.reportedPeriod = value
        this.api.Print('Period: ' + value)
    }
}
```

## Next steps

* Choose a [typed helper](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs) for the control.
* Apply time windows with [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating).
* Use [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input) and [AddEnumValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/add-enum-value) only for compatible low-level integrations.


# Session gating

Session inputs store configuration; they do not restrict calculation automatically. This example reads the current list, converts a known UTC instant into each session's IANA timezone, and checks whether any enabled window contains it.

## Rules used by this example

* A disabled session contributes no allowed time. An empty list, or a list with every session disabled, allows nothing.
* The start is inclusive and the end exclusive: `08:00–17:00` includes 08:00 and excludes 17:00.
* A start later than the end crosses midnight: `22:00–02:00` includes both late evening and early morning.
* Equal start/end means an empty window here, not 24-hour access. This is a choice in the recipe, not an API guarantee.
* An omitted timezone uses the input format's `America/New_York` fallback. An invalid time string or an unsupported IANA zone fails closed.
* `Intl.DateTimeFormat` applies the selected zone's DST rules at the UTC instant being tested. During an autumn repeated hour, both occurrences satisfy the same local-time window; nonexistent spring-forward times are never reached.

This version tests the opening timestamp of the newest bar with `Time(0, UTC)`, not the current tester tick. It reports the filter state and does not create a plot. For a historical buffer, apply the same helper to `Time(index, UTC)` after checking the bar index.

## Complete example

```typescript
import { Indicator, InputSession, InputSessionsArray, TimeValue, TimeZoneMode } from 'forex-tester-custom-indicator-api'

export default class SessionFilterIndicator extends Indicator {
    public Sessions!: InputSessionsArray
    private lastAllowed: boolean | undefined
    private readonly formatters = new Map<string, Intl.DateTimeFormat>()

    public override OnInit(): void {
        this.Sessions = this.api.CreateSessionsArrayInput('Allowed sessions', [
            this.api.CreateSessionValue(
                true, 'London', TimeValue['08:00'], TimeValue['17:00'],
                '#3366FF', 'Europe/London'
            ),
            this.api.CreateSessionValue(
                true, 'New York overnight', TimeValue['22:00'], TimeValue['02:00'],
                '#4CAF50', 'America/New_York'
            )
        ])
    }

    public override OnCalculate(index: number): void {
        if (index !== 0 || this.api.Bars() === 0) return
        const utcMs = this.api.Time(0, TimeZoneMode.UTC).toMilliseconds(TimeZoneMode.UTC)
        const allowed = this.Sessions.getSessions().some(session =>
            this.sessionContains(session, utcMs)
        )

        if (allowed !== this.lastAllowed) {
            this.lastAllowed = allowed
            this.api.Print('Session filter: ' + (allowed ? 'inside' : 'outside'))
        }
        if (!allowed) return
        // Run the session-restricted part of your logic here.
    }

    private sessionContains(session: InputSession, utcMs: number): boolean {
        if (!session.isEnabled || !Number.isFinite(utcMs)) return false

        const parseMinutes = (time: string): number => {
            const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(time)
            return match ? Number(match[1]) * 60 + Number(match[2]) : NaN
        }
        const start = parseMinutes(session.startTime)
        const end = parseMinutes(session.endTime)
        if (!Number.isFinite(start) || !Number.isFinite(end) || start === end) return false

        const zone = session.ianaTimezone?.trim() || 'America/New_York'
        try {
            let formatter = this.formatters.get(zone)
            if (!formatter) {
                formatter = new Intl.DateTimeFormat('en-GB', {
                    timeZone: zone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23'
                })
                this.formatters.set(zone, formatter)
            }
            const parts = formatter.formatToParts(new Date(utcMs))
            const hour = Number(parts.find(part => part.type === 'hour')?.value)
            const minute = Number(parts.find(part => part.type === 'minute')?.value)
            if (!Number.isFinite(hour) || !Number.isFinite(minute)) return false
            const now = hour * 60 + minute
            return start < end ? now >= start && now < end : now >= start || now < end
        } catch {
            return false // Unsupported timezone or invalid date: do not allow the window.
        }
    }
}
```

The helper also accepts the `UTC` timezone for UTC-only rules. It compares time of day, not an exchange calendar: weekends, holidays, and start-day attribution of overnight sessions need explicit rules if your logic requires them.

## Related API

* [Time conventions](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/date-time/time-conventions)
* [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input)
* [CreateSessionValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-value)
* [CreateSessionsArrayInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-sessions-array-input)
* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)


# Typed input helpers


# CreateApplyToPriceInput

Add the eight-choice price-source dropdown: Close, Open, High, Low, Median (HL2), Typical (HLC3), Weighted (HLCC4), and Average (OHLC4).

Returns `InputEnum<PriceType>` — pass `.value` into built-in indicators or your price selector.

## When to use

* Oscillators and MAs where input price changes behavior (close vs HL2).
* Pairs with [CreateMATypeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-ma-type-input) and period inputs for full MA configuration.
* Single fixed price — skip the input and use `PriceType.CLOSE` in code.

## Signature

```typescript
CreateApplyToPriceInput(inputName?: string, defaultValue?: PriceType, tab?: InputTab): InputEnum<PriceType>
```

## Parameters

| Name           | Type        | Required | Description                                                                                       |
| -------------- | ----------- | -------- | ------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`    | No       | Dialog label; API default when omitted. Rename if chart context needs clarity (`Apply to price`). |
| `defaultValue` | `PriceType` | No       | Starting price series. Defaults to `PriceType.CLOSE` — standard for most indicators.              |
| `tab`          | `InputTab`  | No       | Settings tab. Defaults to `InputTab.INPUTS`.                                                      |

## Returns

An `InputEnum<PriceType>` already registered. Read `.value` in `OnCalculate`.

## Usage

Pass `.value` to the price-source parameter of [iRSI](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/technical-indicators/i-rsi), [iMA](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/technical-indicators/i-ma), or your own price selector. Registration alone does not change a calculation.

## Example

Registers the price-source dropdown and reads its current member. Pass that member to a calculation to change its price source.

```typescript
public ApplyToPrice!: InputEnum<PriceType>

OnInit(): void {
    this.ApplyToPrice = this.api.CreateApplyToPriceInput(
        'Apply to',
        PriceType.CLOSE
    )
}

OnCalculate(index: number): void {
    const priceType = this.ApplyToPrice.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input)
* [CreateMATypeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-ma-type-input)
* [InputEnum](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-enum)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [PriceType](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/market-data-and-calculations/price-type)


# CreateBoolInput

Add a checkbox to the indicator’s Inputs dialog — to toggle overlays, alerts, fill areas, or optional logic branches — and keep a handle you read later with `.value`.

## When to use

* On/off features: show labels, enable fills, use alternate formulas, draw auxiliary lines.
* Pair with [SetInputEditable](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-editable) when another input should grey out this checkbox until a prerequisite is met.
* For numeric or enum choices, use [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input) or [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input) instead.

## Signature

```typescript
CreateBoolInput(inputName: string, defaultValue: boolean, tab?: InputTab): InputBool
```

## Parameters

| Name           | Type       | Required | Description                                                                                                                       |
| -------------- | ---------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`   | Yes      | Label beside the checkbox and the key used if you look the input up later. State what toggles (`Show labels`, not `Flag`).        |
| `defaultValue` | `boolean`  | Yes      | Checked state on first attach. Default to the safer or cleaner chart (`false` for noisy extras, `true` for core visuals).         |
| `tab`          | `InputTab` | No       | Which settings tab shows the checkbox. Defaults to `InputTab.INPUTS` when omitted; use `InputTab.STYLE` for display-only toggles. |

## Returns

An `InputBool` already registered in the dialog. Read the checked state with `.value` during calculation.

## Usage

Applying a changed boolean runs `OnParamsChange`, but does not by itself guarantee a general indicator recalculation. Read the live flag in calculation code and explicitly invalidate/rebuild any cached output your implementation requires.

## Example

Registers a checkbox and reads its current value. The example does not create labels or place orders; branch on the value in the feature you want to control.

```typescript
public ShowLabels!: InputBool

OnInit(): void {
    this.ShowLabels = this.api.CreateBoolInput('Show labels', true)
}

OnCalculate(index: number): void {
    const shouldShowLabels = this.ShowLabels.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input)
* [SetInputEditable](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-editable)
* [InputBool](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-bool)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateColorInput

Add a color picker on the Style tab for lines, fills, labels, or session highlights — read `.value` as a hex string when applying plot or object colors.

## When to use

* Single color without line width/style — use [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input) or [CreateColorStyleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-style-input) when those properties belong together.
* Default tab is STYLE — pass `InputTab.INPUTS` only if color is a logic parameter, not pure display.

## Signature

```typescript
CreateColorInput(inputName: string, defaultValue: Color, tab?: InputTab): InputColor
```

## Parameters

| Name           | Type       | Required | Description                                                                           |
| -------------- | ---------- | -------- | ------------------------------------------------------------------------------------- |
| `inputName`    | `string`   | Yes      | Label in the settings dialog.                                                         |
| `defaultValue` | `Color`    | Yes      | Starting color (`#RRGGBB` or `#RRGGBBAA`). Pick contrast against default chart theme. |
| `tab`          | `InputTab` | No       | Defaults to `InputTab.STYLE`.                                                         |

## Returns

An `InputColor` already registered. Read `.value` in `OnCalculate` when setting buffer or object colors.

## Usage

Apply `.value` through a drawing API when creating or refreshing the visual. Changing the input does not recolor an unrelated existing object automatically.

## Example

Registration-only example for a yellow basis-line color. It exposes the live color but does not recolor a plot automatically; apply `.value` through your plot or drawing API.

```typescript
public BasisColor!: InputColor

OnInit(): void {
    this.BasisColor = this.api.CreateColorInput(
        'Basis color',
        '#FFFF00',
        InputTab.STYLE
    )
}

OnCalculate(index: number): void {
    const color = this.BasisColor.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateColorStyleInput

Add visibility, color, and pen style on the Style tab when width is fixed or irrelevant.

Read `isVisible`, `color`, and `style` in `OnCalculate`.

## When to use

* Signal lines where width stays at 1 px in code.
* Lighter control than [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input) when width should not be user-facing.

## Signature

```typescript
CreateColorStyleInput(inputName: string, isVisible: boolean, color: Color, style: PenStyle, tab?: InputTab): InputColorStyle
```

## Parameters

| Name        | Type       | Required | Description                                           |
| ----------- | ---------- | -------- | ----------------------------------------------------- |
| `inputName` | `string`   | Yes      | Label in the settings dialog.                         |
| `isVisible` | `boolean`  | Yes      | Initial visibility.                                   |
| `color`     | `Color`    | Yes      | Starting hex color — distinguish signal vs main line. |
| `style`     | `PenStyle` | Yes      | Pen pattern for secondary series.                     |
| `tab`       | `InputTab` | No       | Defaults to `InputTab.STYLE`.                         |

## Returns

An `InputColorStyle` already registered.

## Usage

Use [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox) after registration if this control should not expose visibility. Hiding the checkbox does not change `isVisible`.

## Example

Registration-only example for a green dotted signal overlay. It exposes live color, style, and visibility values but does not apply them automatically; use them through your plot or drawing API.

```typescript
public SignalLine!: InputColorStyle

OnInit(): void {
    this.SignalLine = this.api.CreateColorStyleInput(
        'Signal line',
        true,
        '#00FF00',
        PenStyle.DOT
    )
}

OnCalculate(index: number): void {
    const style = this.SignalLine.style
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox)
* [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)
* [InputColorStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-color-style)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [PenStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/pen-style)


# CreateColorWidthInput

Add visibility, color, and width on the Style tab when pen style stays fixed (usually solid).

Read `isVisible`, `color`, and `width` in `OnCalculate`.

## When to use

* Band edges or channel lines where dash pattern is not exposed.
* Thicker colored boundaries without full [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input).

## Signature

```typescript
CreateColorWidthInput(inputName: string, isVisible: boolean, color: Color, width: number, tab?: InputTab): InputColorWidth
```

## Parameters

| Name        | Type       | Required | Description                                    |
| ----------- | ---------- | -------- | ---------------------------------------------- |
| `inputName` | `string`   | Yes      | Label in the settings dialog.                  |
| `isVisible` | `boolean`  | Yes      | Initial visibility.                            |
| `color`     | `Color`    | Yes      | Line/fill edge color.                          |
| `width`     | `number`   | Yes      | Pixel width — upper/lower bands often use `1`. |
| `tab`       | `InputTab` | No       | Defaults to `InputTab.STYLE`.                  |

## Returns

An `InputColorWidth` already registered.

## Usage

Apply `isVisible`, `color`, and `width` when refreshing the visual. Registering this option does not link it to an object by name.

## Example

Registration-only example for a red width-1 upper band. It exposes live color, width, and visibility values but does not apply them automatically; use them through your plot or drawing API.

```typescript
public UpperBand!: InputColorWidth

OnInit(): void {
    this.UpperBand = this.api.CreateColorWidthInput(
        'Upper band',
        true,
        '#FF0000',
        1
    )
}

OnCalculate(index: number): void {
    const width = this.UpperBand.width
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox)
* [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)
* [InputColorWidth](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-color-width)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateDateOnlyInput

Add a calendar-date picker when time-of-day does not matter — day boundaries, reporting dates, seasonal filters.

Read `.value` as `FTODate` in `OnCalculate`.

## When to use

* Compare bar date to a fixed calendar start/end without hour/minute UI noise.
* Full timestamp needed — [CreateDateTimeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-date-time-input).

## Signature

```typescript
CreateDateOnlyInput(inputName: string, defaultValue: FTODate, tab?: InputTab): InputDateOnly
```

## Parameters

| Name           | Type       | Required | Description                                                                        |
| -------------- | ---------- | -------- | ---------------------------------------------------------------------------------- |
| `inputName`    | `string`   | Yes      | Label in the settings dialog.                                                      |
| `defaultValue` | `FTODate`  | Yes      | Initial calendar date as an `FTODate`. Use a numeric default and an explicit mode. |
| `tab`          | `InputTab` | No       | Defaults to `InputTab.INPUTS`.                                                     |

## Returns

An `InputDateOnly` already registered.

## Usage

The picker stores a calendar date, not an absolute instant or timezone. Persistence uses `yyyy.mm.dd`; compare calendar parts in the convention your input promises. Do not assume date-only input values represent UTC midnight after a settings round-trip. See [Time conventions](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/date-time/time-conventions).

## Example

Registers a calendar-date picker and reads its current value. The example does not exclude any bars or orders.

```typescript
public StartDate!: InputDateOnly

OnInit(): void {
    const initialDate = this.api.CreateFTODate(
        Date.parse('2026-01-01T00:00:00Z'),
        TimeUnit.MILLISECONDS,
        TimeZoneMode.UTC
    )
    this.StartDate = this.api.CreateDateOnlyInput(
        'Start date',
        initialDate
    )
}

OnCalculate(index: number): void {
    const date = this.StartDate.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateDateTimeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-date-time-input)
* [FTODate](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/time-values/fto-date)
* [InputDateOnly](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-date-only)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateDateTimeInput

Add a combined date-and-time picker for backtest windows, event anchors, or session boundaries that need full timestamps.

Build the default with `CreateFTODate`, register in `OnInit`, read `.value` as `FTODate` in `OnCalculate`.

## When to use

* Start/end of custom calculation windows spanning calendar days.
* Date-only or time-only — use [CreateDateOnlyInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-date-only-input) or [CreateTimeOnlyInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-time-only-input) to simplify the UI.

## Signature

```typescript
CreateDateTimeInput(inputName: string, defaultValue: FTODate, tab?: InputTab): InputDateTime
```

## Parameters

| Name           | Type       | Required | Description                                                                                    |
| -------------- | ---------- | -------- | ---------------------------------------------------------------------------------------------- |
| `inputName`    | `string`   | Yes      | Label in the settings dialog.                                                                  |
| `defaultValue` | `FTODate`  | Yes      | Initial timestamp — pick a date inside typical chart history so first attach behaves sensibly. |
| `tab`          | `InputTab` | No       | Defaults to `InputTab.INPUTS`.                                                                 |

## Returns

An `InputDateTime` already registered.

## Usage

Use a numeric UTC timestamp for a reproducible default. The string path of `CreateFTODate` reuses host-local calendar components, so even a `Z` string is not a reliable absolute UTC default.

The settings serializer writes calendar fields as `yyyy.mm.dd HH:mm:ss`, not UTC ISO text. It does not preserve a timezone tag. Choose and document the calendar convention for the input, then normalize it deliberately before comparing with chart or tester time; see [Time conventions](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/date-time/time-conventions).

## Example

Registers a date-time picker and reads its current value. The example does not apply a start-time filter.

```typescript
public StartTime!: InputDateTime

OnInit(): void {
    const initialTime = this.api.CreateFTODate(
        Date.parse('2026-01-01T08:00:00Z'),
        TimeUnit.MILLISECONDS,
        TimeZoneMode.UTC
    )
    this.StartTime = this.api.CreateDateTimeInput(
        'Start time',
        initialTime
    )
}

OnCalculate(index: number): void {
    const time = this.StartTime.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateDateOnlyInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-date-only-input)
* [CreateTimeOnlyInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-time-only-input)
* [FTODate](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/time-values/fto-date)
* [InputDateTime](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-date-time)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateDoubleInput

Add a decimal control to the indicator’s Inputs dialog — for deviation multipliers, opacity, thresholds, or any fractional tuning — and keep a handle you read later with `.value`.

## When to use

* Fractional parameters: Bollinger deviation, ATR multipliers, risk percentages, step sizes below 1.
* Prefer this over [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input) whenever the user might need decimals; use `digits` to request precision that matches `step`, subject to the current dialog limitation below.
* When bounds and precision are known upfront, pass `min`, `max`, `step`, and `digits` here instead of calling [SetInputRange](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-range) / [SetInputStep](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-step) / [SetInputDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-digits) afterward.

## Signature

```typescript
CreateDoubleInput(inputName: string, defaultValue: number, min?: number, max?: number, step?: number, digits?: number, tab?: InputTab): InputNumber
```

## Parameters

| Name           | Type       | Required | Description                                                                                                                              |
| -------------- | ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`   | Yes      | Label in the settings dialog and the key used if you look the input up later. Use clear labels users recognize (`Deviation`, not `dev`). |
| `defaultValue` | `number`   | Yes      | Value on first attach. Pick something that already draws sensibly (e.g. `2` for standard Bollinger deviation).                           |
| `min`          | `number`   | No       | Lower bound. Stops zero or negative multipliers that would invert or break band math.                                                    |
| `max`          | `number`   | No       | Upper bound. Caps extreme values that widen bands or risk past practical limits.                                                         |
| `step`         | `number`   | No       | Spinner increment. Match the granularity users need (`0.1` for deviation, `0.01` for fine thresholds). Must be positive.                 |
| `digits`       | `number`   | No       | Requested decimal places. Current indicator settings do not consistently honor this per-input value.                                     |
| `tab`          | `InputTab` | No       | Which settings tab shows the control. Defaults to `InputTab.INPUTS` when omitted.                                                        |

## Returns

An `InputNumber` already registered in the dialog. Read the live value with `.value` during calculation.

## Usage

If you omit `min`/`max`/`step`/`digits`, the API stores its widest range, step `0.01`, two requested decimal places, and the Inputs tab.

{% hint style="warning" %}
The settings dialog may use the indicator's shared precision instead of `digits`. This setting does not round `.value`; validate or round in calculation logic when exact precision matters.
{% endhint %}

## Example

A `Deviation` input defaulting to 2.0, limited to 0.1–200 with 0.1 steps and a request for two decimal places. Read `.value` in `OnCalculate` so later dialog edits apply.

```typescript
public Deviation!: InputNumber

OnInit(): void {
    this.Deviation = this.api.CreateDoubleInput(
        'Deviation',
        2,    // standard Bollinger default
        0.1,  // no zero-width bands
        200,
        0.1,
        2
    )
}

OnCalculate(index: number): void {
    const deviation = this.Deviation.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input)
* [SetInputRange](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-range)
* [SetInputStep](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-step)
* [SetInputDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-digits)
* [InputNumber](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-number)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateEnumInput

Add a dropdown backed by your TypeScript numeric enum so users pick a typed mode — signal source, smoothing variant, display layout — and you read `.value` as the enum member, not a raw index.

Prefer this over [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input) when you already have an enum in code: refactors stay type-safe and labels stay aligned with members.

## When to use

* Fixed sets of modes defined as `enum` in your indicator (`SignalMode.CLOSE`, `SignalMode.WICK`, …).
* Subset or custom order of choices — use the `members` overload to hide deprecated values or reorder the list.
* Free-form label lists without an enum — use [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input) instead.

## Signature

```typescript
CreateEnumInput(inputName: string, defaultValue: T, enumObj: Record<string, T | string>, labels: readonly string[], members: readonly T[], tab?: InputTab): InputEnum<T>
CreateEnumInput(inputName: string, defaultValue: T, enumObj: Record<string, T | string>, labels: readonly string[], tab?: InputTab): InputEnum<T>
```

## Parameters

| Name           | Type                          | Required | Description                                                                                                             |
| -------------- | ----------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`                      | Yes      | Label in the settings dialog and the key used if you look the input up later.                                           |
| `defaultValue` | `T`                           | Yes      | Enum member selected on first attach. Pick the mode that matches common usage so the chart looks correct immediately.   |
| `enumObj`      | `Record<string, T \| string>` | Yes      | Your TypeScript numeric enum object (pass the enum itself, e.g. `SignalMode`).                                          |
| `labels`       | `readonly string[]`           | Yes      | User-facing text for each choice. Order must match the enum values (or the `members` order when that overload is used). |
| `members`      | `readonly T[]`                | No       | Explicit subset and order of enum members in the dropdown. Omit to expose all numeric members.                          |
| `tab`          | `InputTab`                    | No       | Which settings tab shows the dropdown. Defaults to `InputTab.INPUTS` when omitted.                                      |

## Returns

An `InputEnum<T>` already registered in the dialog. Read the selected member with `.value` during calculation.

## Usage

Use a numeric enum. String enums are not supported; use [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input) for plain label lists.

At runtime, `.value` is the selected enum member and `.index` is its zero-based dropdown position. Saved settings serialize the selected index, not the numeric enum member. Keep member order stable so existing saved settings reopen on the same choice.

{% hint style="warning" %}
Registration throws `StrangeError` when the label count differs from the exposed member count or `defaultValue` is not among those members. Assigning an unknown `.value` or an out-of-range `.index` also throws `StrangeError`.
{% endhint %}

## Example

The complete example below registers two independent dropdowns, one for each overload. Keep the one that matches your use case:

* **All enum members:** omit `members`; the fifth argument can be `InputTab`.
* **A subset or custom order:** pass `members` as the fifth argument; `InputTab` becomes the sixth. The labels follow that explicit member order.

The nonconsecutive enum values make the distinction visible: the first dropdown starts with `.value === SignalMode.WICK` (`20`) and `.index === 1`. The second starts with `.value === SignalMode.BODY` (`30`) and `.index === 0`.

```typescript
import { Indicator, InputEnum, InputTab } from 'forex-tester-custom-indicator-api'

enum SignalMode {
    CLOSE = 10,
    WICK = 20,
    BODY = 30
}

export default class EnumInputIndicator extends Indicator {
    public Mode!: InputEnum<SignalMode>
    public LimitedMode!: InputEnum<SignalMode>
    private reportedSelection = ''

    public override OnInit(): void {
        // Overload without members: expose every numeric enum member.
        this.Mode = this.api.CreateEnumInput(
            'Signal mode',
            SignalMode.WICK,
            SignalMode,
            ['Close', 'Wick', 'Body'],
            InputTab.INPUTS
        )

        // Overload with members: expose a subset in a custom order.
        this.LimitedMode = this.api.CreateEnumInput(
            'Limited signal mode',
            SignalMode.BODY,
            SignalMode,
            ['Body', 'Close'],
            [SignalMode.BODY, SignalMode.CLOSE],
            InputTab.INPUTS
        )
        this.reportedSelection = ''
    }

    public override OnCalculate(index: number): void {
        if (index !== 0) return
        const selection =
            'Mode: ' + this.Mode.value + ' (index ' + this.Mode.index + ')' +
            '; limited mode: ' + this.LimitedMode.value +
            ' (index ' + this.LimitedMode.index + ')'
        if (selection === this.reportedSelection) return
        this.reportedSelection = selection
        this.api.Print(selection)
    }
}
```

This example reports the live selections when they change; it does not implement the calculation associated with each mode. Compare `.value` with the named enum member in your own logic. Both calls also work with the final `InputTab.INPUTS` omitted.

For a label list with no enum object, use the complete [CreateIndexedEnumInput example](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input#example).

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input)
* [AddEnumValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/add-enum-value)
* [InputEnum](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-enum)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateFillInput

Add a fill-between-buffers control on the Style tab — color, optional second color, enable flag — for shading between two plot buffers.

Register after you know which buffer indexes form the fill area.

## When to use

* Oscillator zero-line fills, band interiors, MACD histogram areas.
* Requires two visible plot slots with drawable values on the same bars. Calculation-only buffers cannot be fill endpoints.

## Signature

```typescript
CreateFillInput(inputName: string, bufferIndex1: number, bufferIndex2: number, color1: Color, color2?: Color, isEnabled?: boolean, tab?: InputTab): InputFill
```

## Parameters

| Name           | Type       | Required | Description                                                                                                            |
| -------------- | ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`   | Yes      | Label in the settings dialog.                                                                                          |
| `bufferIndex1` | `number`   | Yes      | First zero-based visible plot slot (the index returned by `CreatePlot`), not the allocation order of an `IndexBuffer`. |
| `bufferIndex2` | `number`   | Yes      | Second zero-based visible plot slot.                                                                                   |
| `color1`       | `Color`    | Yes      | Color when the first plot is above the second. Alpha controls transparency.                                            |
| `color2`       | `Color`    | No       | Color when the first plot is below the second; omitted means `color1` on both sides. This is not a gradient.           |
| `isEnabled`    | `boolean`  | No       | Fill on by default when `true` (default).                                                                              |
| `tab`          | `InputTab` | No       | Defaults to `InputTab.STYLE`.                                                                                          |

## Returns

An `InputFill` already registered. Read fill properties in `OnCalculate` or style update hooks.

## Usage

Create the two visible plots and bind their buffers before using their plot indexes in this option. The renderer applies enabled fill options automatically, but only where both plots are visible and have drawable values. Hiding either plot also suppresses the fill.

## Example

Registration-only example for plot slots 0 and 1. It does not create or populate those plots, so this fragment alone draws no shaded area.

```typescript
public BandFill!: InputFill

OnInit(): void {
    this.BandFill = this.api.CreateFillInput(
        'Band fill',
        0,
        1,
        '#00FF0033',
        '#FF000033',
        true
    )
}

OnCalculate(index: number): void {
    const enabled = this.BandFill.isEnabled
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateColorInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-input)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)
* [InputFill](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-fill)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateFontSizeInput

Add a label font-size dropdown (five preset sizes) on the Style tab for text drawn on chart objects or buffer labels.

Returns `InputEnum<FontSize>` — use `.value` when setting label typography in `OnCalculate`.

## When to use

* Indicators that draw text labels, session names, or custom annotations.
* Style-tab grouping with [CreateColorInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-input) for label appearance.
* Custom pixel sizes beyond the five `FontSize` presets — not supported; use `CreateEnumInput` with your own enum if you need arbitrary sizes

## Signature

```typescript
CreateFontSizeInput(inputName: string, defaultValue?: FontSize, tab?: InputTab): InputEnum<FontSize>
```

## Parameters

| Name           | Type       | Required | Description                                                                          |
| -------------- | ---------- | -------- | ------------------------------------------------------------------------------------ |
| `inputName`    | `string`   | Yes      | Label in the settings dialog.                                                        |
| `defaultValue` | `FontSize` | No       | Starting size. Defaults to `FontSize.Small` — readable without dominating the chart. |
| `tab`          | `InputTab` | No       | Defaults to `InputTab.STYLE` so font sits with other display options.                |

## Returns

An `InputEnum<FontSize>` already registered.

## Usage

Pass `.value` as a pixel size when creating or updating text. The helper changes neither chart-wide typography nor existing object text automatically.

## Example

Registration-only example for a small label size. It exposes the live `FontSize` value but does not resize legend or chart text automatically; apply `.value` through your label or drawing API.

```typescript
public LabelFontSize!: InputEnum<FontSize>

OnInit(): void {
    this.LabelFontSize = this.api.CreateFontSizeInput(
        'Label font size',
        FontSize.Small,
        InputTab.STYLE
    )
}

OnCalculate(index: number): void {
    const fontSize = this.LabelFontSize.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input)
* [CreateColorInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-input)
* [FontSize](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/font-size)
* [InputEnum](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-enum)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateTimeframeInput

Add a timeframe dropdown (`Current` plus chart timeframes) so users run part of your indicator on another TF while viewing a different chart period.

`Current` is represented and saved as the numeric sentinel `0`. When chart context is available, `.value` resolves that sentinel to the attached chart timeframe in minutes.

## When to use

* Multi-timeframe indicators: higher TF filter, lower TF trigger.
* Any logic calling built-ins with explicit `timeframe` — pair with [iMA](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/technical-indicators/i-ma) etc.
* Fixed TF only — pass minutes directly in code instead of this input.

## Signature

```typescript
CreateTimeframeInput(inputName: string, defaultToCurrent?: boolean, tab?: InputTab): InputTimeframe
```

## Parameters

| Name               | Type       | Required | Description                                                                                                                   |
| ------------------ | ---------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `inputName`        | `string`   | Yes      | Label in the settings dialog. Name the role (`Calculation timeframe`, `Filter TF`).                                           |
| `defaultToCurrent` | `boolean`  | No       | When `true`, starts on `Current` (matches chart). Defaults to `true` so single-TF indicators behave intuitively first attach. |
| `tab`              | `InputTab` | No       | Defaults to `InputTab.INPUTS`.                                                                                                |

## Returns

An `InputTimeframe` already registered. Read `.value` in `OnCalculate`; it is usually timeframe minutes, but can be the `0` sentinel before `Current` has chart context to resolve against.

## Usage

When the user picks `Current`, the selected value remains the saved `0` sentinel while `.value` tracks chart changes after resolution. Re-read each bar and do not cache minutes across symbol/TF changes.

{% hint style="info" %}
Do not assume every read is positive. If code can run before chart attachment, handle `0` explicitly. `.index === 0` identifies the first dropdown item; it is not a minute value. See [Timeframe values](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/time-values/timeframe) for concrete minute constants.
{% endhint %}

## Example

Calculation TF follows chart by default. Expected outcome: `timeframeMinutes` equals chart TF until user selects e.g. H1.

```typescript
public Timeframe!: InputTimeframe

OnInit(): void {
    this.Timeframe = this.api.CreateTimeframeInput('Calculation timeframe')
}

OnCalculate(index: number): void {
    const timeframeMinutes = this.Timeframe.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [InputTimeframe](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-timeframe)
* [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [InputType](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-type)
* [Timeframe values](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/time-values/timeframe)


# CreateIndexedEnumInput

Add a dropdown whose stored value is a zero-based index when you have labeled choices but no TypeScript enum — method pickers, price-mode lists, simple algorithm variants.

You read `.value` or `.index` as a number and map it in code. Prefer [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input) when a numeric enum already exists.

## When to use

* Small fixed lists defined only in the UI (`Simple` / `Exponential`, `High-Low` / `Close-Close`).
* Prototyping before extracting a proper enum type.
* The list is set during registration — order defines index `0`, `1`, `2`, …

## Signature

```typescript
CreateIndexedEnumInput(inputName: string, defaultIndex: number, labels: readonly string[], tab?: InputTab): InputEnum<number>
```

## Parameters

| Name           | Type                | Required | Description                                                                                                                                              |
| -------------- | ------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`            | Yes      | Label in the settings dialog and the key used if you look the input up later.                                                                            |
| `defaultIndex` | `number`            | Yes      | Which label is selected on first attach (`0` = first entry). Must be an integer index present in `labels`; otherwise registration throws `StrangeError`. |
| `labels`       | `readonly string[]` | Yes      | Visible choices in dropdown order; index `i` corresponds to `labels[i]`.                                                                                 |
| `tab`          | `InputTab`          | No       | Which settings tab shows the dropdown. Defaults to `InputTab.INPUTS` when omitted.                                                                       |

## Returns

An `InputEnum<number>` already registered in the dialog. Selected index via `.value` or `.index`.

## Usage

Prepare the complete label list during initialization and keep its order stable; saved selections are indexes, so reordering labels changes their meaning.

For this helper, `.value`, `.index`, and the serialized saved value are all the selected zero-based index. Assigning an index below `0` or at/above `labels.length` throws `StrangeError`.

{% hint style="info" %}
For enum-backed dropdowns with type safety, migrate to [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input) once you define a numeric enum.
{% endhint %}

## Example

This complete example registers two choices, selects the second by default, and maps the live index back to its label. It prints the selection only when it changes. The calculation or position-sizing behavior named by the labels belongs in your own logic.

```typescript
import { Indicator, InputEnum, InputTab } from 'forex-tester-custom-indicator-api'

const METHOD_LABELS = ['Simple', 'Exponential'] as const

export default class IndexedEnumIndicator extends Indicator {
    public Method!: InputEnum<number>
    private reportedIndex: number | undefined

    public override OnInit(): void {
        this.Method = this.api.CreateIndexedEnumInput(
            'Method',
            1, // 'Exponential' is selected initially.
            METHOD_LABELS,
            InputTab.INPUTS
        )
        this.reportedIndex = undefined
    }

    public override OnCalculate(index: number): void {
        if (index !== 0) return
        const selectedIndex = this.Method.value
        if (selectedIndex === this.reportedIndex) return
        this.reportedIndex = selectedIndex
        const selectedLabel = METHOD_LABELS[selectedIndex]
        this.api.Print('Method: ' + selectedLabel + ' (index ' + selectedIndex + ')')
    }
}
```

Initially, `.value` and `.index` are both `1`, and `.count` is `2`. Selecting the first choice changes both `.value` and `.index` to `0`. The last `InputTab.INPUTS` argument is optional; omit it to use the same tab.

Pass the complete label list in this call. It creates the index mapping and registers the settings choices together; a separate `AddEnumValue` call is unnecessary.

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input)
* [AddEnumValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/add-enum-value)
* [InputEnum](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-enum)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateIntegerInput

Add an integer control to the indicator’s Inputs dialog — for example a period, shift, or lookback — and keep a handle you read later with `.value`.

## When to use

* Whole-number settings: period, bars to skip, lookback offsets, and enum indexes that you expose as integers.
* Prefer this helper over a bare `CreateInput` when you want min/max/step applied up front so the spinner rejects bad values immediately.
* For fractional values use [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input) instead.

## Signature

```typescript
CreateIntegerInput(inputName: string, defaultValue: number, min?: number, max?: number, step?: number, tab?: InputTab): InputNumber
```

## Parameters

| Name           | Type       | Required | Description                                                                                                                         |
| -------------- | ---------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`   | Yes      | Label in the settings dialog and the key used if you look the input up later. Pick a name users will recognize (`Period`, not `p`). |
| `defaultValue` | `number`   | Yes      | Value on first attach. Choose something that already produces a sensible chart (e.g. `14` for many oscillators).                    |
| `min`          | `number`   | No       | Lower bound in the UI. Stops users from setting `0` or negative periods that break your formula.                                    |
| `max`          | `number`   | No       | Upper bound. Caps extreme lookbacks that freeze calculation on large history.                                                       |
| `step`         | `number`   | No       | Spinner increment. Use `1` for periods; must be positive.                                                                           |
| `tab`          | `InputTab` | No       | Which settings tab shows the control. Defaults to `InputTab.INPUTS` when omitted.                                                   |

## Returns

An `InputNumber` already registered in the dialog. Read the live value with `.value` during calculation.

## Usage

Without explicit bounds, registration uses its widest integer range and step `1` on `InputTab.INPUTS`. Bounds configure the UI; validate a loaded or programmatically assigned value before using it as a history lookback or index.

## Example

A `Period` input defaulting to 14, limited to 1–500. Read `period` in `OnCalculate` so later dialog edits apply.

```typescript
public Period!: InputNumber

OnInit(): void {
    this.Period = this.api.CreateIntegerInput(
        'Period',
        14, // sensible default for many MA/ATR-style calculations
        1,  // reject zero/negative lookback
        500,
        1
    )
}

OnCalculate(index: number): void {
    const period = this.Period.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input)
* [SetInputRange](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-range)
* [SetInputStep](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-step)
* [InputNumber](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-number)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateMATypeInput

Add the standard moving-average-type dropdown (SMA, EMA, SMMA, LWMA) so users pick smoothing without you maintaining label lists.

Returns `InputEnum<MovingAverageType>` — pass `.value` into [iMA](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/technical-indicators/i-ma) or your own MA loop.

## When to use

* Any indicator parameterizing MA period **and** type.
* Instead of a hand-built enum via [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input) + labels.
* Custom non-MA enums — use [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input).

## Signature

```typescript
CreateMATypeInput(inputName?: string, defaultValue?: MovingAverageType, tab?: InputTab): InputEnum<MovingAverageType>
```

## Parameters

| Name           | Type                | Required | Description                                                                                           |
| -------------- | ------------------- | -------- | ----------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`            | No       | Dialog label; API default when omitted. Override when `MA type` is too generic (`Signal MA type`).    |
| `defaultValue` | `MovingAverageType` | No       | Starting average. Defaults to `MovingAverageType.SMA` — common baseline users expect on first attach. |
| `tab`          | `InputTab`          | No       | Settings tab. Defaults to `InputTab.INPUTS`.                                                          |

## Returns

An `InputEnum<MovingAverageType>` already registered. Read `.value` in `OnCalculate`.

## Usage

Pass `.value` as the moving-average type in a built-in call or your own calculation. The selected member is not a computed MA value.

## Example

Registers the standard MA dropdown and reads its selected member. A calculation changes only when you pass that member to an MA method.

```typescript
public MAType!: InputEnum<MovingAverageType>

OnInit(): void {
    this.MAType = this.api.CreateMATypeInput(
        'MA type',
        MovingAverageType.SMA
    )
}

OnCalculate(index: number): void {
    const maType = this.MAType.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input)
* [CreateApplyToPriceInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-apply-to-price-input)
* [iMA](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/technical-indicators/i-ma)
* [InputEnum](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-enum)
* [MovingAverageType](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/market-data-and-calculations/moving-average-type)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateSessionInput

Add one editable trading session row — enable flag, name, start/end times, highlight color, optional IANA timezone — on the Sessions tab.

Read session fields from the returned object in `OnCalculate` for session-aware shading or filters.

## When to use

* Single named session (London, NY open) drawn on chart.
* Multiple sessions — build each with [CreateSessionValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-value) and register via [CreateSessionsArrayInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-sessions-array-input).

## Signature

```typescript
CreateSessionInput(inputName: string, isEnabled: boolean, sessionName: string, startTime: TimeValue, endTime: TimeValue, color: Color, ianaTimezone?: string, tab?: InputTab): InputSession
```

## Parameters

| Name           | Type        | Required | Description                                                                                                                |
| -------------- | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------- |
| `inputName`    | `string`    | Yes      | Label in the settings dialog.                                                                                              |
| `isEnabled`    | `boolean`   | Yes      | Whether session highlighting applies on first attach.                                                                      |
| `sessionName`  | `string`    | Yes      | Display name in UI and legends.                                                                                            |
| `startTime`    | `TimeValue` | Yes      | Session open — use exchange-local convention users expect.                                                                 |
| `endTime`      | `TimeValue` | Yes      | Session close; overnight sessions may end before start — handle wrap in logic.                                             |
| `color`        | `Color`     | Yes      | Highlight fill/stroke; semi-transparent hex helps overlays.                                                                |
| `ianaTimezone` | `string`    | No       | IANA zone such as `Europe/London`. Omitted defaults to `America/New_York`; it does not follow the chart or local timezone. |
| `tab`          | `InputTab`  | No       | Defaults to `InputTab.SESSIONS`.                                                                                           |

## Returns

An `InputSession` already registered.

## Usage

Choose an explicit IANA zone for market-specific sessions; omission uses `America/New_York`, not the chart zone. Read the enable flag and times when applying the [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating) helper. Registration does not draw a background or enforce a filter.

## Example

Registers a London session and reads its start/end values. It does not restrict calculations or trading by itself; [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating) implements that check.

```typescript
public LondonSession!: InputSession

OnInit(): void {
    this.LondonSession = this.api.CreateSessionInput(
        'London session',
        true,
        'London',
        TimeValue['08:00'],
        TimeValue['17:00'],
        '#3366FF',
        'Europe/London'
    )
}

OnCalculate(index: number): void {
    const start = this.LondonSession.startTime
    const end = this.LondonSession.endTime
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating)
* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateSessionValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-value)
* [CreateSessionsArrayInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-sessions-array-input)
* [CreateTimeOnlyInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-time-only-input)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)
* [InputSession](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-session)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [TimeValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/time-values/time-value)


# CreateSessionValue

Build an unregistered [InputSession](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-session) to seed [CreateSessionsArrayInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-sessions-array-input). This call does not add a settings row.

Use [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input) when the session itself should appear as its own control.

## When to use

* Nested defaults for a sessions-array input, including an explicit IANA timezone.
* Empty list — `CreateSessionsArrayInput(name, [])` needs no session factory.

## Signature

```typescript
CreateSessionValue(isEnabled: boolean, name: string, startTime: TimeValue, endTime: TimeValue, color: Color, ianaTimezone?: string): InputSession
```

## Parameters

| Name           | Type        | Required | Description                                                                                                       |
| -------------- | ----------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| `isEnabled`    | `boolean`   | Yes      | Whether the session is on when the array is first attached.                                                       |
| `name`         | `string`    | Yes      | Label shown for the session, such as `London`.                                                                    |
| `startTime`    | `TimeValue` | Yes      | Session open.                                                                                                     |
| `endTime`      | `TimeValue` | Yes      | Session close; overnight sessions may end before start — handle wrap in logic.                                    |
| `color`        | `Color`     | Yes      | Color preference; registration alone does not draw a session overlay.                                             |
| `ianaTimezone` | `string`    | No       | IANA zone such as `Europe/London`. Omitted defaults to `America/New_York`; it does not follow the chart timezone. |

## Returns

An `InputSession` that is not registered. Pass it in the `defaultValue` array of `CreateSessionsArrayInput`.

## Usage

Do not use an already registered `CreateSessionInput` as an array default: that would also retain its separate UI row and share its object. Use this unregistered factory, then register the containing list. For enabled/overnight windows, see [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating).

## Example

London and New York windows as array defaults. Expected outcome: the array input is the only settings row.

```typescript
public CustomSessions!: InputSessionsArray

OnInit(): void {
    this.CustomSessions = this.api.CreateSessionsArrayInput('Custom Sessions', [
        this.api.CreateSessionValue(true, 'London', TimeValue['08:00'], TimeValue['16:00'], '#3366ff', 'Europe/London'),
        this.api.CreateSessionValue(true, 'New York', TimeValue['13:00'], TimeValue['21:00'], '#4CAF50', 'America/New_York')
    ], false)
}

OnCalculate(index: number): void {
    const sessions = this.CustomSessions.getSessions()
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating)
* [CreateSessionsArrayInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-sessions-array-input)
* [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input)
* [InputSession](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-session)
* [InputSessionsArray](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-sessions-array)
* [TimeValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/time-values/time-value)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)


# CreateSessionsArrayInput

Add a Sessions-tab list of trading sessions users can edit — enable/disable, times, colors — and read the live list with `getSessions()` in `OnCalculate`.

Build default `InputSession[]` with unregistered [CreateSessionValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-value). Do not seed the array with sessions already registered via [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input).

## When to use

* Multiple windows, each with its own times and optional IANA timezone.
* Fixed session set — set `allowAddingSessions` to `false`.
* Single session — [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input) alone is simpler.
* Empty list — `CreateSessionsArrayInput(name, [])`.

## Signature

```typescript
CreateSessionsArrayInput(inputName: string, defaultValue: InputSession[], allowAddingSessions?: boolean, tab?: InputTab): InputSessionsArray
```

## Parameters

| Name                  | Type             | Required | Description                                                                                       |
| --------------------- | ---------------- | -------- | ------------------------------------------------------------------------------------------------- |
| `inputName`           | `string`         | Yes      | Label in the settings dialog.                                                                     |
| `defaultValue`        | `InputSession[]` | Yes      | Initial sessions — each from unregistered `CreateSessionValue(...)`. Pass `[]` for an empty list. |
| `allowAddingSessions` | `boolean`        | No       | `true` lets users add rows; `false` locks the list. Default `true`.                               |
| `tab`                 | `InputTab`       | No       | Defaults to `InputTab.SESSIONS`.                                                                  |

## Returns

An `InputSessionsArray` already registered. Call `getSessions()` for current list.

## Usage

Read the current list with `getSessions()` when applying the [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating) helper. Editing can replace session objects, so do not retain the initial array as your live source.

Pass an explicit IANA zone on each `CreateSessionValue` when the session is not in `America/New_York`. Omitted timezone defaults to `America/New_York`; it does not follow the chart.

## Example

Registers London and New York presets without allowing additional rows. The example reads the live list; [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating) applies enabled windows.

```typescript
public CustomSessions!: InputSessionsArray

OnInit(): void {
    this.CustomSessions = this.api.CreateSessionsArrayInput(
        'Custom Sessions',
        [
            this.api.CreateSessionValue(true, 'London', TimeValue['08:00'], TimeValue['16:00'], '#3366ff', 'Europe/London'),
            this.api.CreateSessionValue(true, 'New York', TimeValue['13:00'], TimeValue['21:00'], '#4CAF50', 'America/New_York')
        ],
        false
    )
}

OnCalculate(index: number): void {
    const sessions = this.CustomSessions.getSessions()
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating)
* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateSessionValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-value)
* [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input)
* [SetInputShowNameWithParams](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-show-name-with-params)
* [InputSession](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-session)
* [InputSessionsArray](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-sessions-array)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateStringInput

Add a free-text field to the indicator’s Inputs dialog — for comments, prefix labels, magic tags, or format strings — and keep a handle you read later with `.value`.

## When to use

* User-visible text: chart labels, object names, export prefixes.
* Non-numeric configuration where a dropdown does not fit.
* Avoid strings for choices with a fixed set — use [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input) or [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input) so users cannot typo invalid modes.

## Signature

```typescript
CreateStringInput(inputName: string, defaultValue: string, tab?: InputTab): InputString
```

## Parameters

| Name           | Type       | Required | Description                                                                     |
| -------------- | ---------- | -------- | ------------------------------------------------------------------------------- |
| `inputName`    | `string`   | Yes      | Label in the settings dialog and the key used if you look the input up later.   |
| `defaultValue` | `string`   | Yes      | Text on first attach. Provide a short, valid example users can keep or edit.    |
| `tab`          | `InputTab` | No       | Which settings tab shows the field. Defaults to `InputTab.INPUTS` when omitted. |

## Returns

An `InputString` already registered in the dialog. Read the live text with `.value` during calculation.

## Usage

In `OnCalculate`, trim or validate if empty strings would break drawing.

Long strings can clutter the chart legend — consider [SetInputShowNameWithParams](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-show-name-with-params) with `false` for verbose fields.

{% hint style="warning" %}
Do not parse strings as numbers without validation — users can enter non-numeric text. Use [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input) for numeric parameters.
{% endhint %}

## Example

Registers a text field and reads the current string. It does not modify existing labels or orders.

```typescript
public LabelPrefix!: InputString

OnInit(): void {
    this.LabelPrefix = this.api.CreateStringInput(
        'Label prefix',
        'Session breakout' // example prefix users can replace
    )
}

OnCalculate(index: number): void {
    const prefix = this.LabelPrefix.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input)
* [SetInputShowNameWithParams](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-show-name-with-params)
* [InputString](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-string)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# CreateStrokeInput

Add one Style-tab control for full line appearance — visibility, color, pen style, and width — when all four matter for a plot or overlay.

Read `isVisible`, `color`, `style`, and `width` from the returned object in `OnCalculate`.

## When to use

* Primary plot lines where users tune complete stroke properties.
* Partial controls — [CreateColorWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-width-input), [CreateStyleWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-style-width-input), [CreateColorStyleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-style-input) when color or width is fixed in code.

## Signature

```typescript
CreateStrokeInput(inputName: string, isVisible: boolean, color: Color, style: PenStyle, width: number, tab?: InputTab): InputStroke
```

## Parameters

| Name        | Type       | Required | Description                                                     |
| ----------- | ---------- | -------- | --------------------------------------------------------------- |
| `inputName` | `string`   | Yes      | Label in the settings dialog.                                   |
| `isVisible` | `boolean`  | Yes      | Initial visibility. `false` hides line until user enables it.   |
| `color`     | `Color`    | Yes      | Starting hex color.                                             |
| `style`     | `PenStyle` | Yes      | Solid, dash, dot, etc. — match default to indicator convention. |
| `width`     | `number`   | Yes      | Line width in pixels; `1` is typical for auxiliary lines.       |
| `tab`       | `InputTab` | No       | Defaults to `InputTab.STYLE`.                                   |

## Returns

An `InputStroke` already registered.

## Usage

Apply the live members when updating your visual; registration does not associate the option with a plot or object automatically.

Stroke inputs are registered as hideable (`canHide` is enabled automatically). `isVisible` is the initial live visibility value; the dialog shows its checkbox unless you hide that checkbox with `SetInputHideIsVisibleCheckbox`.

## Example

Registration-only example for a solid blue main line, visible by default. It exposes live style values but does not apply them to a plot automatically; use those values in your plot or drawing configuration.

```typescript
public MainLine!: InputStroke

OnInit(): void {
    this.MainLine = this.api.CreateStrokeInput(
        'Main line',
        true,
        '#0000FF',
        PenStyle.SOLID,
        1
    )
}

OnCalculate(index: number): void {
    const color = this.MainLine.color
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateColorStyleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-style-input)
* [CreateColorWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-width-input)
* [CreateStyleWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-style-width-input)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)
* [InputStroke](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-stroke)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [PenStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/pen-style)


# CreateStyleInput

Add visibility and pen style (solid, dash, dot) on the Style tab when color and width are fixed.

Read `isVisible` and `style` in `OnCalculate`.

## When to use

* Dashed mean lines or dotted guides with fixed color/width from code.
* Combine with [CreateColorInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-input) if color is separate.

## Signature

```typescript
CreateStyleInput(inputName: string, isVisible: boolean, style: PenStyle, tab?: InputTab): InputStyle
```

## Parameters

| Name        | Type       | Required | Description                                                                    |
| ----------- | ---------- | -------- | ------------------------------------------------------------------------------ |
| `inputName` | `string`   | Yes      | Label in the settings dialog.                                                  |
| `isVisible` | `boolean`  | Yes      | Initial visibility.                                                            |
| `style`     | `PenStyle` | Yes      | Default pen pattern — `DASH` for reference levels, `SOLID` for primary series. |
| `tab`       | `InputTab` | No       | Defaults to `InputTab.STYLE`.                                                  |

## Returns

An `InputStyle` already registered.

## Usage

Apply both `style` and `isVisible` to the visual you control. Use [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox) only to remove the checkbox, not to force visibility.

## Example

Registration-only example for a dashed reference line. It exposes the live style and visibility but does not restyle or hide a plot automatically; apply both values through your plot or drawing API.

```typescript
public LineStyle!: InputStyle

OnInit(): void {
    this.LineStyle = this.api.CreateStyleInput(
        'Line style',
        true,
        PenStyle.DASH
    )
}

OnCalculate(index: number): void {
    const style = this.LineStyle.style
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox)
* [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input)
* [InputStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-style)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [PenStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/pen-style)


# CreateStyleWidthInput

Add visibility, pen style, and width on the Style tab when color is assigned in code or shared across lines.

Read `isVisible`, `style`, and `width` in `OnCalculate`.

## When to use

* Monochrome indicators where hue is thematic, not per-line.
* Lower band vs upper band sharing palette but differing dash/width.

## Signature

```typescript
CreateStyleWidthInput(inputName: string, isVisible: boolean, style: PenStyle, width: number, tab?: InputTab): InputStyleWidth
```

## Parameters

| Name        | Type       | Required | Description                                |
| ----------- | ---------- | -------- | ------------------------------------------ |
| `inputName` | `string`   | Yes      | Label in the settings dialog.              |
| `isVisible` | `boolean`  | Yes      | Initial visibility.                        |
| `style`     | `PenStyle` | Yes      | Dash/solid pattern to differentiate bands. |
| `width`     | `number`   | Yes      | Pixel width.                               |
| `tab`       | `InputTab` | No       | Defaults to `InputTab.STYLE`.              |

## Returns

An `InputStyleWidth` already registered.

## Usage

Apply `style`, `width`, and `isVisible` together. A separate [CreateColorInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-input) can supply a shared color for several visuals.

## Example

Registration-only example for a dashed width-2 lower band. It exposes live style, width, and visibility values but does not apply them automatically; use them through your plot or drawing API.

```typescript
public LowerBand!: InputStyleWidth

OnInit(): void {
    this.LowerBand = this.api.CreateStyleWidthInput(
        'Lower band',
        true,
        PenStyle.DASH,
        2
    )
}

OnCalculate(index: number): void {
    const width = this.LowerBand.width
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox)
* [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input)
* [InputStyleWidth](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-style-width)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [PenStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/pen-style)


# CreateTimeOnlyInput

Add a time-of-day picker for intraday session edges — open, lunch break, fix times — without calendar date UI.

Read `.value` as a time string from `TimeValue` in `OnCalculate`.

## When to use

* Daily recurring times on each session day.
* Absolute calendar datetime — [CreateDateTimeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-date-time-input).
* Full session object with color/timezone — [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input).

## Signature

```typescript
CreateTimeOnlyInput(inputName: string, defaultValue: TimeValue, tab?: InputTab): InputTimeOnly
```

## Parameters

| Name           | Type        | Required | Description                                                             |
| -------------- | ----------- | -------- | ----------------------------------------------------------------------- |
| `inputName`    | `string`    | Yes      | Label in the settings dialog.                                           |
| `defaultValue` | `TimeValue` | Yes      | Initial time, e.g. `TimeValue['08:00']` — align with market you target. |
| `tab`          | `InputTab`  | No       | Defaults to `InputTab.INPUTS`.                                          |

## Returns

An `InputTimeOnly` already registered.

## Usage

1. Pass valid `TimeValue` literals.
2. Compare bar time components to `.value` for session gating.

## Example

Registers an 08:00 time-of-day value and reads it. No time filter is applied here; see [Session gating](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/session-gating) for a complete window check.

```typescript
public SessionStart!: InputTimeOnly

OnInit(): void {
    this.SessionStart = this.api.CreateTimeOnlyInput(
        'Session start',
        TimeValue['08:00']
    )
}

OnCalculate(index: number): void {
    const startTime = this.SessionStart.value
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateDateTimeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-date-time-input)
* [CreateSessionInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-session-input)
* [InputTimeOnly](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-time-only)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [TimeValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/time-values/time-value)


# CreateWidthInput

Add visibility and line width on the Style tab when color and pen style are fixed in code or set elsewhere.

Read `isVisible` and `width` in `OnCalculate`.

## When to use

* Thickness-only tuning for preset-colored lines.
* With [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox) when visibility is always on.

## Signature

```typescript
CreateWidthInput(inputName: string, isVisible: boolean, width: number, tab?: InputTab): InputWidth
```

## Parameters

| Name        | Type       | Required | Description                                                                  |
| ----------- | ---------- | -------- | ---------------------------------------------------------------------------- |
| `inputName` | `string`   | Yes      | Label in the settings dialog.                                                |
| `isVisible` | `boolean`  | Yes      | Initial visibility for the styled element.                                   |
| `width`     | `number`   | Yes      | Pixel width. Wider lines emphasize levels; keep `1–2` for grid-like helpers. |
| `tab`       | `InputTab` | No       | Defaults to `InputTab.STYLE`.                                                |

## Returns

An `InputWidth` already registered.

## Usage

Apply `width` and `isVisible` when updating the visual. This control does not find or resize chart objects by itself.

## Example

Registration-only example for a visible width-2 auxiliary line. It exposes the live width and visibility but does not resize or hide a plot automatically; apply both values through your plot or drawing API.

```typescript
public LineWidth!: InputWidth

OnInit(): void {
    this.LineWidth = this.api.CreateWidthInput(
        'Line width',
        true,
        2
    )
}

OnCalculate(index: number): void {
    const width = this.LineWidth.width
    // Use the live value in the logic or drawing that this input controls.
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [SetInputHideIsVisibleCheckbox](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-hide-is-visible-checkbox)
* [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input)
* [InputWidth](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-width)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# Input metadata


# AddSeparator

Insert a labeled divider in the settings dialog to group related inputs — RSI block vs display block, Inputs vs advanced session options.

Separators carry no value; they only organize the UI so users find parameters faster and avoid changing the wrong control.

## When to use

* Before a cluster of related [Create\*Input](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs) calls (period, levels, colors).
* On `InputTab.STYLE` or `InputTab.SESSIONS` when those tabs grow long.
* Not a substitute for [SetInputTooltip](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-tooltip) — use both when a group needs a heading and individual fields need detail.

## Signature

```typescript
AddSeparator(separatorName: string, tab?: InputTab): void
```

## Parameters

| Name            | Type       | Required | Description                                                                          |
| --------------- | ---------- | -------- | ------------------------------------------------------------------------------------ |
| `separatorName` | `string`   | Yes      | Heading text on the divider. Name the group by task (`RSI Settings`, `Band colors`). |
| `tab`           | `InputTab` | No       | Tab that shows the divider. Defaults to `InputTab.INPUTS` when omitted.              |

## Returns

Nothing. The divider appears at the point in registration order where you call this.

## Usage

Register the separator immediately before the controls it introduces and use the same `InputTab` for the whole group. Display order follows registration order within that tab.

## Example

RSI period sits under an RSI heading. Expected outcome: dialog shows a divider then Period control.

```typescript
this.api.AddSeparator('RSI Settings')
this.Period = this.api.CreateIntegerInput('Period', 14, 1, 500)
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)


# SetInputDigits

Store the requested decimal precision for a registered numeric input.

Prefer passing `digits` to [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input) at creation when precision is fixed.

## When to use

* Doubles registered via [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input) without digit metadata.
* After changing [SetInputStep](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-step) — request matching metadata (e.g. step `0.001` → three digits), while allowing for the current display limitation.
* Fractional digit counts round down in the stored metadata; the numeric value keeps full precision.

## Signature

```typescript
SetInputDigits(inputName: string, digits: number): void
```

## Parameters

| Name        | Type     | Required | Description                                                                                       |
| ----------- | -------- | -------- | ------------------------------------------------------------------------------------------------- |
| `inputName` | `string` | Yes      | Exact label from registration.                                                                    |
| `digits`    | `number` | Yes      | Requested decimal places. Current indicator settings do not consistently use per-input precision. |

## Returns

Nothing. Precision metadata updates for a matching input; unknown names are ignored.

## Usage

1. Register a double input in `OnInit`.
2. Call `SetInputDigits` with the same `inputName`.
3. Pair with step and range, but do not rely on trailing zeros or exact per-input formatting in the current dialog.

{% hint style="warning" %}
The current indicator settings may use shared indicator precision instead of this input-specific value. `digits` does not round or truncate the stored `.value`.
{% endhint %}

## Example

Request three decimal places for a multiplier. Expected outcome: the preference is stored, but the current indicator dialog may not display `2.000`.

```typescript
this.Multiplier = this.api.CreateDoubleInput(
    'Multiplier',
    2,
    0.1,
    10
)
this.api.SetInputDigits('Multiplier', 3)
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input)
* [SetInputStep](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-step)


# SetInputHideIsVisibleCheckbox

Hide or show the visibility checkbox on style inputs (`InputStroke`, `InputWidth`, `InputStyle`, `InputColorStyle`, `InputColorWidth`, `InputStyleWidth`) when visibility is always on or controlled elsewhere.

Default behavior hides the checkbox — pass `false` when users should toggle line visibility from the Style tab.

## When to use

* Lines that are always drawn — hide the checkbox to reduce noise.
* Width/style-only tweaks where visibility is implied by [CreateBoolInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-bool-input) elsewhere.
* Unsupported input types ignore this call; verify you registered an eligible style wrapper.

## Signature

```typescript
SetInputHideIsVisibleCheckbox(inputName: string, hideIsVisibleCheckbox?: boolean): void
```

## Parameters

| Name                    | Type      | Required | Description                                                                            |
| ----------------------- | --------- | -------- | -------------------------------------------------------------------------------------- |
| `inputName`             | `string`  | Yes      | Exact label of the style input from registration.                                      |
| `hideIsVisibleCheckbox` | `boolean` | No       | `true` (default) hides the checkbox; `false` shows it so users can toggle `isVisible`. |

## Returns

Nothing. Checkbox visibility updates for supported style inputs; others unchanged.

## Usage

1. Register with [CreateWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-width-input) or related style helper.
2. Call in `OnInit` right after registration.
3. When checkbox is hidden, honor `isVisible` default you passed at creation — users cannot flip it in UI.

## Example

Line width without a visibility toggle. Expected outcome: Style tab shows width control only.

```typescript
this.LineWidth = this.api.CreateWidthInput(
    'Line width',
    true,
    2
)
this.api.SetInputHideIsVisibleCheckbox('Line width')
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateStrokeInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-stroke-input)
* [CreateWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-width-input)
* [CreateStyleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-style-input)
* [CreateColorWidthInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-color-width-input)


# SetInputRange

Tighten or widen min/max on an already registered numeric input — when you registered via [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input) or forgot bounds on a typed helper.

Prefer passing `min`/`max` to [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input) or [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input) at creation time so invalid values never appear in the spinner.

## When to use

* Hour-of-day fields (`0`–`23`), percentage clamps, threshold after manual `CreateInput`.
* Adjusting limits when one input’s meaning depends on another (call from `OnParamsChange` if needed).
* Unknown `inputName` — call has no effect; verify spelling matches registration.

## Signature

```typescript
SetInputRange(inputName: string, minValue: number, maxValue: number): void
```

## Parameters

| Name        | Type     | Required | Description                                                                                        |
| ----------- | -------- | -------- | -------------------------------------------------------------------------------------------------- |
| `inputName` | `string` | Yes      | Exact label from `CreateInput` or `Create*Input`. Must match character-for-character.              |
| `minValue`  | `number` | Yes      | Lowest allowed value. Set above zero for periods and lookbacks that break on non-positive windows. |
| `maxValue`  | `number` | Yes      | Highest allowed value. Cap extreme lookbacks that slow recalculation on full history.              |

## Returns

Nothing. Limits update immediately in the dialog. Wrong name → no change.

## Usage

This configures UI bounds, not a runtime assignment clamp. Validate values in your logic when they can be loaded or assigned outside the control.

1. Register the input first in `OnInit`.
2. Call `SetInputRange` with the same `inputName`.
3. Existing user values outside the new range may clamp on next edit — test after tightening bounds.

{% hint style="info" %}
Session hour example: bound 0–23 so users cannot pick invalid clock hours.
{% endhint %}

## Example

Configure the settings control for a session-start hour. Expected outcome: spinner stops at 0 and 23.

```typescript
this.SessionStartHour = this.api.CreateIntegerInput('Session start hour', 0)
this.api.SetInputRange('Session start hour', 0, 23)
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input)
* [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input)


# SetInputShowNameWithParams

Hide or show an input’s value in the indicator name printed on the chart legend — keep the legend readable when some settings are internal or verbose.

Included by default; call with `false` for session arrays, debug flags, or long strings that would clutter the chart title.

## When to use

* [CreateSessionsArrayInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-sessions-array-input) or bulky enum labels that explode legend width.
* UI-only or advanced toggles users need in dialog but not in the chart name.
* Leave `true` (default) for primary parameters users identify the indicator by (`Period 14`, `MA type EMA`).

## Signature

```typescript
SetInputShowNameWithParams(inputName: string, showNameWithParams: boolean): void
```

## Parameters

| Name                 | Type      | Required | Description                                                                       |
| -------------------- | --------- | -------- | --------------------------------------------------------------------------------- |
| `inputName`          | `string`  | Yes      | Exact label from registration.                                                    |
| `showNameWithParams` | `boolean` | Yes      | `true` — value appears in chart name; `false` — label omitted from legend suffix. |

## Returns

Nothing. Chart name updates according to the flag for a matching input.

## Usage

1. Register the input in `OnInit`.
2. Call immediately after when the default inclusion would clutter the legend.
3. Does not affect calculation — display only.

## Example

Custom sessions stay off the chart title. Expected outcome: legend shows indicator name without session list text.

```typescript
this.CustomSessions = this.api.CreateSessionsArrayInput(
    'Custom sessions',
    sessions,
    false
)
this.api.SetInputShowNameWithParams(
    'Custom sessions',
    false
)
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input)
* [CreateStringInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-string-input)


# SetInputStep

Set spinner increment on a registered numeric input — finer steps for thresholds, coarser steps for large lookbacks.

Prefer passing `step` to [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input) or [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input) at creation when the increment is known upfront.

## When to use

* Threshold or multiplier inputs where `0.01` steps matter after [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input) without step in the constructor.
* Integer periods where you want steps of `5` or `10` for faster tuning.
* Zero or negative step is ignored — the previous step remains.

## Signature

```typescript
SetInputStep(inputName: string, step: number): void
```

## Parameters

| Name        | Type     | Required | Description                                                                                                                                                                                                 |
| ----------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inputName` | `string` | Yes      | Exact label from registration. Typos leave the step unchanged.                                                                                                                                              |
| `step`      | `number` | Yes      | Amount added or subtracted per spinner click. Must be positive; align with [SetInputDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-digits) for doubles. |

## Returns

Nothing. Step updates immediately for a matching input; invalid step values are ignored.

## Usage

1. Register the numeric input in `OnInit`.
2. Call `SetInputStep` with the same `inputName`.
3. Match step to economic meaning — `0.01` for fine thresholds vs `1` bar periods.

## Example

Double threshold input then fine step. Expected outcome: each click changes the value by 0.01 within range.

```typescript
this.Threshold = this.api.CreateDoubleInput(
    'Threshold',
    0.5,
    0.01,
    10
)
this.api.SetInputStep('Threshold', 0.01)
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input)
* [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input)
* [SetInputDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-digits)


# SetInputTooltip

Attach hover help to a registered input so users know what a terse label affects — period vs shift, risk vs display-only flags.

Tooltips do not change values; they reduce misconfiguration on crowded settings tabs.

## When to use

* Abbreviated labels (`Period`, `Dev`, `HL`) that need one-line context.
* Advanced inputs users rarely touch — explain units (bars, pips, percent).
* After any `Create*Input` or [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input) when the label alone is ambiguous.

## Signature

```typescript
SetInputTooltip(inputName: string, tooltip: string): void
```

## Parameters

| Name        | Type     | Required | Description                                                                                                         |
| ----------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------- |
| `inputName` | `string` | Yes      | Exact label from registration.                                                                                      |
| `tooltip`   | `string` | Yes      | Short help shown on hover. State units and effect (`Number of bars in the RSI window`), not implementation details. |

## Returns

Nothing. Tooltip appears for a matching input; unknown names are ignored.

## Usage

1. Register the input in `OnInit`.
2. Call `SetInputTooltip` immediately after with the same `inputName`.
3. Keep one sentence; link to docs externally if more detail is needed.

## Example

Period field with bar-count explanation. Expected outcome: hovering Period shows the tooltip in the dialog.

```typescript
this.Period = this.api.CreateIntegerInput(
    'Period',
    14,
    1,
    500
)
this.api.SetInputTooltip(
    'Period',
    'Number of bars used in the calculation.'
)
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input)
* [AddSeparator](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/add-separator)


# SetInputEditable

Grey out or re-enable a registered setting without changing its stored value — guide users when a control only applies in certain modes.

Typical pattern: disable dependent fields when a master checkbox or enum makes them irrelevant.

## When to use

* `OnParamsChange` after reading a mode flag — enable delta-time only when combined mode is off.
* Prevent edits that would be ignored by your logic while keeping last value for when the user switches back.
* Same `inputName` as registration; wrong name → no UI change.

## Signature

```typescript
SetInputEditable(inputName: string, editable: boolean): void
```

## Parameters

| Name        | Type      | Required | Description                                                                    |
| ----------- | --------- | -------- | ------------------------------------------------------------------------------ |
| `inputName` | `string`  | Yes      | Exact label from `CreateInput` or `Create*Input`.                              |
| `editable`  | `boolean` | Yes      | `true` — interactive; `false` — greyed out. Stored value unchanged either way. |

## Returns

Nothing. Control interactivity updates immediately.

## Usage

1. Register both the master and dependent inputs in `OnInit`.
2. In `OnParamsChange`, read the master `.value` and call `SetInputEditable` for dependents.
3. Still guard in `OnCalculate` — disabled UI does not stop code from reading stale `.value`.

{% hint style="warning" %}
When disabled, users cannot edit but your code still sees the old number. Ignore or override disabled inputs in calculation if needed.
{% endhint %}

## Example

Delta time disabled while separated mode is on. Expected outcome: greyed control when `SeparatedMode` is checked.

```typescript
public override OnParamsChange(): void {
    this.api.SetInputEditable(
        'Delta time',
        !this.SeparatedMode.value
    )
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateBoolInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-bool-input)
* [OnParamsChange](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-params-change)


# Low-level registration


# AddEnumValue

Append one dropdown value to an `ENUM` input registered with [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input) — each call adds the next index in order (`0`, `1`, `2`, …).

Use after `CreateInput` when you build a custom list manually. Prefer [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input) or [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input) for new dropdowns.

## When to use

* Values that need dynamic assembly at init time (still fixed before users open settings).
* Not for typed enum helpers — those register choices automatically.

## Signature

```typescript
AddEnumValue(inputName: string, value: string): void
```

## Parameters

| Name        | Type     | Required | Description                                                                                                      |
| ----------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
| `inputName` | `string` | Yes      | Exact label passed to `CreateInput` for the dropdown. Typos mean choices attach to the wrong control or nowhere. |
| `value`     | `string` | Yes      | Text shown for this choice. Use clear, distinct values so users know what index they are picking.                |

## Returns

Nothing. The choice appears at the next index in the dropdown.

## Usage

This advanced operation appends only a settings-row label; it does not expand the member/index mapping inside an `InputEnum` or `InputIndexedEnum`. Do not append choices to a typed helper's result: selecting the new row can exceed the wrapper's known members.

For new npm-package code, prepare the full list before calling `CreateIndexedEnumInput` or `CreateEnumInput`. Manual registration requires a compatible unregistered wrapper; see [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input). The first appended row is index 0, and reordering labels changes the meaning of saved indexes.

## Example

Prefer [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input) so values are registered with the dropdown. Expected outcome: two entries; `.value` is `0` or `1`.

```typescript
this.Mode = this.api.CreateIndexedEnumInput('Mode', 0, ['Simple', 'Exponential'])
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/low-level-registration/create-input)
* [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input)
* [CreateIndexedEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-indexed-enum-input)


# CreateInput

Low-level registration for an input wrapper you already hold. Prefer typed `Create*Input` helpers — they create the wrapper, pick `InputType`, and register in one call.

This is an advanced compatibility entry point, not the normal way to create inputs from the npm package. A typed helper already registers its returned wrapper. Calling `CreateInput` on that wrapper again appends a second settings row; it does not update the first registration.

The published wrapper constructors are protected/type declarations, not a supported `new InputNumber(...)` workflow. Unless you already have a compatible unregistered wrapper from another supported integration, use a typed helper.

## Signature

```typescript
CreateInput(inputName: string, inputType: InputType, optionPtr: InputBase, tab?: InputTab): void
```

## Parameters

| Name        | Type        | Required | Description                                                                                                                              |
| ----------- | ----------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `inputName` | `string`    | Yes      | Label in the settings dialog and the key for follow-up calls (`SetInputRange`, `AddEnumValue`). Must stay consistent across those calls. |
| `inputType` | `InputType` | Yes      | Control kind the dialog renders. Must match the wrapper type (`INTEGER` for `InputNumber`, `ENUM` for indexed dropdowns, etc.).          |
| `optionPtr` | `InputBase` | Yes      | Compatible, unregistered wrapper. Do not pass the result of a typed helper: that wrapper is already registered.                          |
| `tab`       | `InputTab`  | No       | Which settings tab shows the control. Defaults to `InputTab.INPUTS` when omitted.                                                        |

## Returns

Nothing. The setting appears in the dialog after this call; read the wrapper you passed in via `.value` or its members.

## Usage

Register in `OnInit`, with an `InputType` matching the wrapper. Names must be unique within the module's settings: metadata setters resolve by name, so duplicate registration makes their target ambiguous. This call returns no wrapper.

## Example

The supported typed alternative below creates and registers the control in one call. Do not add a `CreateInput` call afterward.

```typescript
public Threshold!: InputNumber

OnInit(): void {
    this.Threshold = this.api.CreateDoubleInput('Threshold', 0.5, 0.01, 10)
}
```

## Related API

* [Input registration](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/registration-and-runtime-use/input-registration)
* [CreateDoubleInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-double-input)
* [CreateIntegerInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-integer-input)
* [CreateEnumInput](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/typed-input-helpers/create-enum-input)
* [SetInputRange](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/inputs/input-metadata/set-input-range)
* [InputBase](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-base)
* [InputTab](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-tab)
* [InputType](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/input-values/input-type)


# Indicator Configuration

Control how the indicator appears, scales, and recalculates on the chart.

## When to open this section

You are naming the indicator, choosing chart vs separate pane, fixing scale bounds, adding oscillator levels, hiding value labels, or tuning recalculation behavior.

## Common tasks

| Goal                                                       | Method                                                                                                                                                                                                                                                                                                                   |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Set the name in the UI                                     | [SetIndicatorShortName](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-short-name)                                                                                                                                                                                     |
| Draw in own pane below price                               | [SetIndicatorOutputWindow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-output-window)                                                                                                                                                                               |
| Fix oscillator scale (0–100)                               | [SetIndicatorMinMax](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-min-max)                                                                                                                                                                                           |
| Add a fixed horizontal level                               | [AddLevel](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/add-level)                                                                                                                                                                                                                 |
| Move a level when an input changes                         | [SetLevelValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-level-value)                                                                                                                                                                                                      |
| Warm up lookback before visible bars                       | [SetIndicatorBackOffset](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-back-offset)                                                                                                                                                                                   |
| Recalculate every visited bar                              | [RecalculateMeAlways](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-me-always)                                                                                                                                                                                          |
| Refresh calculations as tick-data chunks arrive            | [RecalculateOnTickDataChunks](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-on-tick-data-chunks)                                                                                                                                                                        |
| Hide value clutter on both the price scale and status line | [HideIndicatorValuesOnPriceScale](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/hide-indicator-values-on-price-scale) or [HideIndicatorValuesInStatusLine](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/hide-indicator-values-in-status-line) |

`HideIndicatorValuesOnPriceScale` and `HideIndicatorValuesInStatusLine` are currently aliases. Calling either one hides this indicator's values from both surfaces.

Levels render only for separate-window indicators. See also [indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle) for where each call belongs in `OnInit` or `OnParamsChange`.

## Methods

* [SetIndicatorShortName](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-short-name)
* [SetIndicatorId](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-id)
* [SetIndicatorOutputWindow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-output-window)
* [SetIndicatorDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-digits)
* [GetIndicatorDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/get-indicator-digits)
* [SetIndicatorEmptyValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-empty-value)
* [SetIndicatorBackOffset](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-back-offset)
* [SetIndicatorMinMax](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-min-max)
* [AddLevel](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/add-level)
* [SetLevelValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-level-value)
* [HideIndicatorValuesOnPriceScale](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/hide-indicator-values-on-price-scale)
* [HideIndicatorValuesInStatusLine](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/hide-indicator-values-in-status-line)
* [RecalculateMeAlways](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-me-always)
* [RecalculateOnTickDataChunks](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-on-tick-data-chunks)


# AddLevel

Draw a horizontal reference line in the indicator pane — typical for overbought, oversold, or zero axes.

## Signature

```typescript
AddLevel(value: number, style: PenStyle, width: number, color: Color): void
```

## Parameters

| Name    | Type       | Required | Description          |
| ------- | ---------- | -------- | -------------------- |
| `value` | `number`   | Yes      | Numeric level value. |
| `style` | `PenStyle` | Yes      | Line pen style.      |
| `width` | `number`   | Yes      | Width in pixels.     |
| `color` | `Color`    | Yes      | CSS color value.     |

## Returns

`void`.

## Usage

1. Levels render only when [SetIndicatorOutputWindow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-output-window) is set to `OutputWindow.SEPARATE`. Configure the output window in `OnInit` before adding levels.
2. Levels receive zero-based indexes in insertion order — remember that order for [SetLevelValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-level-value).
3. Add multiple lines with separate `AddLevel` calls.

## Example

```typescript
this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
this.api.AddLevel(30, PenStyle.DOT, 1, '#000000')
this.api.AddLevel(70, PenStyle.DOT, 1, '#000000')
```

## Related API

* [SetLevelValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-level-value)
* [SetIndicatorOutputWindow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-output-window)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)
* [PenStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/pen-style)


# GetIndicatorDigits

Read the decimal precision currently stored for this indicator.

## Signature

```typescript
GetIndicatorDigits(): number
```

## Parameters

None.

## Returns

The configured number of decimal places used by separate-window scaling and available to your own formatting code.

## Usage

1. Call when formatting status text, object labels, or debug output.
2. Set precision first with [SetIndicatorDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-digits) if you rely on a specific count.

This value does not report the precision currently used by the built-in cursor/status readout or the main price scale; those surfaces use the symbol's digits.

## Example

```typescript
this.api.SetIndicatorDigits(5)
const indicatorDigits = this.api.GetIndicatorDigits()
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [SetIndicatorDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-digits)


# HideIndicatorValuesInStatusLine

Hide this indicator's displayed values from both the chart status line and price scale.

## Signature

```typescript
HideIndicatorValuesInStatusLine(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

1. Call in `OnInit` when displayed values add noise (decorative overlays, background helpers).
2. Despite its name, this method currently hides values on both the chart status line and the price scale.
3. It is an alias of [HideIndicatorValuesOnPriceScale](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/hide-indicator-values-on-price-scale); calling both is unnecessary.
4. The setting affects only this indicator instance.

## Example

```typescript
this.api.HideIndicatorValuesInStatusLine()
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [HideIndicatorValuesOnPriceScale](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/hide-indicator-values-on-price-scale)


# HideIndicatorValuesOnPriceScale

Hide this indicator's displayed values from both the price scale and chart status line.

## Signature

```typescript
HideIndicatorValuesOnPriceScale(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

1. Call in `OnInit` for indicators that draw shapes or markers without meaningful displayed values.
2. Despite its name, this method currently hides values on both the price scale and the chart status line.
3. It is an alias of [HideIndicatorValuesInStatusLine](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/hide-indicator-values-in-status-line); calling both is unnecessary.
4. The setting affects only this indicator instance.

## Example

```typescript
this.api.HideIndicatorValuesOnPriceScale()
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [HideIndicatorValuesInStatusLine](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/hide-indicator-values-in-status-line)


# RecalculateMeAlways

Force FTO to revisit every bar in each requested calculation range so stateful formulas stay consistent.

## Signature

```typescript
RecalculateMeAlways(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

1. Call once in `OnInit` when each bar's result depends on how earlier bars were calculated in the same pass.
2. Expect higher CPU use — reserve this for indicators that truly need it (recursive EMA, multi-stage pipelines).
3. Set an adequate [SetIndicatorBackOffset](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-back-offset) so warm-up bars exist before visible output.

Without this setting, FTO can reuse valid cached buffer values and skip those bars. With it enabled, FTO recalculates every bar in the range currently requested by loading, scrolling, invalidation, or robot access. It does not continuously recalculate all available history, and hidden indicators still do not receive `OnCalculate`.

## Example

```typescript
public override OnInit(): void {
    this.api.RecalculateMeAlways()
}
```

## Related API

* [RecalculateOnTickDataChunks](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-on-tick-data-chunks)
* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [SetIndicatorBackOffset](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-back-offset)


# RecalculateOnTickDataChunks

Enable recalculation when additional tick-data chunks arrive for the indicator's symbol.

## Signature

```typescript
RecalculateOnTickDataChunks(): void
```

## Parameters

None.

## Returns

`void`.

## Usage

Call once in `OnInit` when the indicator's calculated values depend on tick data that can arrive after the initial calculation. The runtime records this setting for the indicator instance.

This setting is separate from [RecalculateMeAlways](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-me-always): that method controls whether cached bars are revisited during a requested calculation pass, while `RecalculateOnTickDataChunks` opts into recalculation triggered by arriving tick-data chunks. Enable both only when both behaviors are needed.

The method has no disable argument and does not return tick data. Hidden indicators still do not receive `OnCalculate`.

## Example

```typescript
public override OnInit(): void {
    this.api.SetIndicatorShortName('Tick-data calculation')
    this.api.RecalculateOnTickDataChunks()
    // Register inputs, buffers, and plots for the calculation here.
}
```

## Related API

* [RecalculateMeAlways](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-me-always)
* [OnInit](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-init)
* [OnCalculate](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/on-calculate)


# SetIndicatorBackOffset

Extend calculation backward so formulas with lookback or recursion warm up before the first visible bar.

## Signature

```typescript
SetIndicatorBackOffset(offset: number): void
```

## Parameters

| Name     | Type     | Required | Description                                                       |
| -------- | -------- | -------- | ----------------------------------------------------------------- |
| `offset` | `number` | Yes      | Non-negative calculation lookback offset in bars; use an integer. |

## Returns

`void`.

## Usage

1. Set an initial offset in `OnInit` when you know the minimum period.
2. Recompute in `OnParamsChange` when periods or smoothing types change.
3. Size the offset to cover your longest lookback, EMA warm-up, or recursive dependency — err slightly high rather than low.
4. Combine with [RecalculateMeAlways](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-me-always) for stateful indicators that read their own prior buffer values.

Back offset extends the range FTO requests; it does not create older data and does not replace a `Bars()` guard inside `OnCalculate`. Negative offsets are not a useful warm-up configuration.

## Example

```typescript
public override OnParamsChange(): void {
    const backOffset = Math.max(0, this.Period.value * 8)
    this.api.SetIndicatorBackOffset(backOffset)
}
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [RecalculateMeAlways](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/recalculate-me-always)
* [SetPlotDrawBegin](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-draw-begin)


# SetIndicatorDigits

Set the indicator precision used by separate-window scaling and by code that reads this setting explicitly.

## Signature

```typescript
SetIndicatorDigits(digits: number): void
```

## Parameters

| Name     | Type     | Required | Description                                                                      |
| -------- | -------- | -------- | -------------------------------------------------------------------------------- |
| `digits` | `number` | Yes      | Indicator precision stored for separate-window scaling and `GetIndicatorDigits`. |

## Returns

`void`.

## Usage

1. Call in `OnInit`, or in `OnParamsChange` when indicator precision should track symbol digits.
2. Separate indicator windows use this setting for their vertical-axis precision.
3. Read the active setting back with [GetIndicatorDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/get-indicator-digits) when formatting your own labels or text.
4. The chart cursor/status readout and a price-chart overlay's main price scale currently continue to use the symbol's digits; this method does not override those surfaces.

## Example

```typescript
this.api.SetIndicatorDigits(this.api.Digits())
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [GetIndicatorDigits](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/get-indicator-digits)


# SetIndicatorEmptyValue

Tell FTO which buffer value means “do not draw this bar.”

## Signature

```typescript
SetIndicatorEmptyValue(emptyValue: number): void
```

## Parameters

| Name         | Type     | Required | Description                                 |
| ------------ | -------- | -------- | ------------------------------------------- |
| `emptyValue` | `number` | Yes      | Numeric value treated as missing plot data. |

## Returns

`void`.

## Usage

1. Call in `OnInit` before you start writing buffer values.
2. Write the empty sentinel in `OnCalculate` for bars that lack enough history.
3. Common choice: `0` for separate-window indicators where zero is not a valid reading.
4. Prefer a finite non-zero sentinel outside your valid output range when `0` is a valid value (for example MACD histogram).
5. The setting applies to this indicator's buffers, including working buffers. Exclude the sentinel before feeding a stored value into a recursive formula.

The default sentinel is `0`. A value equal to the configured sentinel is skipped when plots render. `null` and `NaN` do not create the same line-gap behavior. Changing this setting does not rewrite values already stored in the buffers.

## Example

```typescript
const EMPTY = Number.MAX_VALUE
this.api.SetIndicatorEmptyValue(EMPTY)
this.OutputBuffer = this.api.CreateBuffer()
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [CreateBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/create-buffer)


# SetIndicatorId

Assign a non-empty identifier separate from the display name.

## Signature

```typescript
SetIndicatorId(id: string): void
```

## Parameters

| Name | Type     | Required | Description                            |
| ---- | -------- | -------- | -------------------------------------- |
| `id` | `string` | Yes      | Stable non-empty indicator identifier. |

## Returns

`void`.

## Usage

1. Call in `OnInit` to assign a fixed identifier.
2. Use lowercase kebab-case or another consistent scheme — the ID is not shown as the primary label.
3. Keep [SetIndicatorShortName](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-short-name) for the human-readable name.

The runtime trims surrounding whitespace and throws if the remaining identifier is empty. This identifier is separate from the display name.

## Example

```typescript
this.api.SetIndicatorId('custom-rsi')
this.api.SetIndicatorShortName('Custom RSI')
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [SetIndicatorShortName](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-short-name)


# SetIndicatorMinMax

Lock the vertical scale on a separate-window indicator so readings stay in a fixed range.

## Signature

```typescript
SetIndicatorMinMax(min: number, max: number): void
```

## Parameters

| Name  | Type     | Required | Description                |
| ----- | -------- | -------- | -------------------------- |
| `min` | `number` | Yes      | Fixed minimum scale value. |
| `max` | `number` | Yes      | Fixed maximum scale value. |

## Returns

`void`.

## Usage

1. Use with [SetIndicatorOutputWindow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-output-window) set to `OutputWindow.SEPARATE`.
2. Typical fixed ranges: `0`–`100` for percent oscillators, `-100`–`100` for centered metrics.
3. Update in `OnParamsChange` only if your design changes scale bounds dynamically.

## Example

```typescript
this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
this.api.SetIndicatorMinMax(0, 100)
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [SetIndicatorOutputWindow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-output-window)
* [AddLevel](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/add-level)


# SetIndicatorOutputWindow

Decide whether plots draw on the price chart or in a dedicated pane below it.

## Signature

```typescript
SetIndicatorOutputWindow(outputWindow: OutputWindow): void
```

## Parameters

| Name           | Type           | Required | Description                             |
| -------------- | -------------- | -------- | --------------------------------------- |
| `outputWindow` | `OutputWindow` | Yes      | Target chart or separate output window. |

## Returns

`void`.

## Usage

1. Call in `OnInit` before creating plots.
2. Use `OutputWindow.CHART` for overlays such as moving averages or bands on price.
3. Use `OutputWindow.SEPARATE` for oscillators (RSI, MACD, CCI) that need their own vertical scale.
4. Pair separate panes with [SetIndicatorMinMax](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-min-max) or [AddLevel](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/add-level) when fixed bounds help readability.

## Example

```typescript
this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
this.api.SetIndicatorMinMax(0, 100)
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [SetIndicatorMinMax](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-min-max)
* [SetPlotForceOverlay](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-force-overlay)
* [OutputWindow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/output-window)


# SetIndicatorShortName

Choose the label users see in the indicator list, legend, and settings dialog.

## Signature

```typescript
SetIndicatorShortName(shortName: string): void
```

## Parameters

| Name        | Type     | Required | Description                 |
| ----------- | -------- | -------- | --------------------------- |
| `shortName` | `string` | Yes      | User-facing indicator name. |

## Returns

`void`.

## Usage

1. Call once near the top of `OnInit`.
2. Pick a short, descriptive name — it is what traders see on the chart.
3. Use [SetIndicatorId](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-id) separately when you need a stable persisted identifier.

## Example

```typescript
this.api.SetIndicatorShortName('Moving Average')
```

## Related API

* [Indicator lifecycle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/lifecycle/indicator-lifecycle)
* [SetIndicatorId](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-id)


# SetLevelValue

Move an existing horizontal level when a user input changes its numeric value.

## Signature

```typescript
SetLevelValue(levelIndex: number, value: number): void
```

## Parameters

| Name         | Type     | Required | Description                                |
| ------------ | -------- | -------- | ------------------------------------------ |
| `levelIndex` | `number` | Yes      | Zero-based level index in insertion order. |
| `value`      | `number` | Yes      | Numeric level value.                       |

## Returns

`void`.

## Usage

1. Levels render only when [SetIndicatorOutputWindow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-output-window) is set to `OutputWindow.SEPARATE`.
2. Create levels with [AddLevel](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/add-level) in a stable order.
3. Call from `OnParamsChange` when oversold/overbought inputs should reposition lines.
4. `levelIndex` must be from `0` through the number of added levels minus one. It matches the order of `AddLevel` calls — first line is `0`.
5. Current invalid-index behavior is asymmetric: a non-negative index at or above the level count is ignored, while a negative index causes a runtime error. Validate the index before calling.

## Example

Register an `Oversold` input on a separate pane, add the level once in `OnInit`, then move it when the user edits the input in `OnParamsChange`. Expected outcome: applying a changed Oversold value repositions the horizontal line on the oscillator pane without recreating it.

```typescript
public Oversold!: InputNumber

public override OnInit(): void {
    this.api.SetIndicatorOutputWindow(OutputWindow.SEPARATE)
    this.api.SetIndicatorMinMax(0, 100)
    this.Oversold = this.api.CreateDoubleInput('Oversold', 30, 0, 100)
    this.api.AddLevel(this.Oversold.value, PenStyle.DOT, 1, '#000000')
}

public override OnParamsChange(): void {
    this.api.SetLevelValue(0, this.Oversold.value)
}
```

## Related API

* [AddLevel](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/add-level)


# Plots and buffers

Store per-bar values in buffers and expose the ones traders should see as plots.

## When to open this section

You are wiring output for the first time, splitting work buffers from visible series, detecting series crosses, or tuning how lines and histograms draw.

## Typical workflow

1. [CreateBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/create-buffer) for every series you calculate — visible or hidden.
2. [SetPlotCount](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-count), then [CreatePlot](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/create-plot) (or [SetPlotBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-buffer) + style calls) for each visible line.
3. Write values in `OnCalculate` with [IndexBuffer.setValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/index-buffer/set-value).
4. For line gaps, configure a numeric empty value with [SetIndicatorEmptyValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-empty-value) and write that value to bars that should not draw.
5. Detect series crosses with [CrossOver](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/cross-over) / [CrossUnder](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/cross-under) when your signal logic needs them.
6. Adjust draw begin, shift, fill, or visibility when the chart needs refinement.

Start with [plot setup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup) and [calculation vs visible buffers](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/calculation-vs-visible-buffers) before opening individual method pages.

Cross helpers compare raw values at `index` and `index + 1`. Validate buffer values before calling, and remember that a result for the current, still-forming bar can change before that bar closes.

## Plot indexes and errors

Plot indexes are zero-based and must identify an existing slot from `0` through `plotCount - 1`. Call `SetPlotCount` before any method that accepts a plot index.

Treat an invalid index as a programming error. Runtime handling is method-specific: some methods throw an error, while others leave the plot unchanged. Do not rely on an invalid index being ignored.

## Methods

* [SetPlotCount](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-count)
* [CreateBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/create-buffer)
* [CreatePlot](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/create-plot)
* [SetPlotBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-buffer)
* [SetPlotLabel](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-label)
* [SetPlotStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-style)
* [SetPlotForceOverlay](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-force-overlay)
* [SetPlotSymbol](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-symbol)
* [SetPlotVisibility](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-visibility)
* [SetPlotDrawBegin](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-draw-begin)
* [SetPlotShift](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-shift)
* [SetFillBetweenPlots](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-fill-between-plots)
* [GetPlotVisibility](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/get-plot-visibility)
* [GetPlotType](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/get-plot-type)
* [GetPlotColor](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/get-plot-color)
* [GetPlotWidth](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/get-plot-width)
* [GetPlotStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/get-plot-style)
* [GetPlotInfo](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/get-plot-info)
* [CrossOver](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/cross-over)
* [CrossUnder](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/cross-under)


# Calculation and visible buffers

## Purpose

Separate scratch calculation buffers from visible plot buffers so only finished series render on the chart.

## When to use this pattern

Your indicator needs scratch space — prior EMA values, true range, signal lines — that should not appear as separate chart lines.

## Workflow

1. Create every buffer with `CreateBuffer` and store it on the class.
2. Leave intermediate buffers unbound — no plot calls for them.
3. Bind output buffers with `CreatePlot` or `SetPlotBuffer`.
4. In `OnCalculate`, read older values with `buffer.getValue(index + 1)`.
5. Write both intermediate and visible results at the current `index`.

## Gaps in visible lines

Line plots break only when a buffer contains the configured numeric empty value. Call [SetIndicatorEmptyValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/indicator-configuration/set-indicator-empty-value) in `OnInit`, then write the same value at each bar that should not draw.

`IndexBuffer.setValue` accepts `null`, but `null` is not the configured numeric empty value and should not be used to create line gaps.

## Example

```typescript
public TempBuffer!: IndexBuffer
public OutputBuffer!: IndexBuffer

public override OnInit(): void {
    this.TempBuffer = this.api.CreateBuffer()
    this.OutputBuffer = this.api.CreateBuffer()
    this.api.SetPlotCount(1)
    this.api.CreatePlot(
        0,
        this.OutputBuffer,
        'Output',
        PlotType.LINE,
        PenStyle.SOLID,
        1,
        '#FF0000'
    )
}

public override OnCalculate(index: number): void {
    if (index + 1 >= this.api.Bars()) {
        return
    }
    const previous = this.TempBuffer.getValue(index + 1)
    const close = this.api.Close(index)
    // Inline smoothed value — no helper methods required
    const value = previous === 0 ? close : previous * 0.9 + close * 0.1
    this.TempBuffer.setValue(index, value)
    this.OutputBuffer.setValue(index, value)
}
```

## Related API

* [CreatePlot](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/create-plot)
* [IndexBuffer.setValue](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/index-buffer/set-value)
* [Plot setup](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup)


# CreateBuffer

Allocate storage for one per-bar numeric series your indicator calculates.

## Signature

```typescript
CreateBuffer(): IndexBuffer
```

## Parameters

None.

## Returns

A new calculation `IndexBuffer` owned by the indicator.

## Usage

1. Call in `OnInit` for every series — visible output and hidden working buffers.
2. Assign each return value to a class field so `OnCalculate` can reach it.
3. Bind output buffers to plots with `CreatePlot` or `SetPlotBuffer`. Leave scratch buffers unbound.

## Example

```typescript
this.OutputBuffer = this.api.CreateBuffer()
this.WorkBuffer = this.api.CreateBuffer()

this.api.SetPlotCount(1)
this.api.CreatePlot(
    0,
    this.OutputBuffer,
    'Output',
    PlotType.LINE,
    PenStyle.SOLID,
    1,
    '#FF0000'
)
```

## Related API

* [Plot setup workflow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup)
* [Calculation and visible buffers](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/calculation-vs-visible-buffers)
* [SetPlotCount](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-count)
* [CreatePlot](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/create-plot)
* [SetPlotBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-buffer)
* [IndexBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/index-buffer)


# CreatePlot

Bind a buffer to a plot and set its label, draw type, and colors in one `OnInit` call.

## Signature

```typescript
CreatePlot(plotIndex: number, buffer: IndexBuffer, label: string, plotType: PlotType, penStyle: PenStyle, width: number, color: Color): void
```

## Parameters

| Name        | Type          | Required | Description                                                                        |
| ----------- | ------------- | -------- | ---------------------------------------------------------------------------------- |
| `plotIndex` | `number`      | Yes      | Zero-based visible plot index.                                                     |
| `buffer`    | `IndexBuffer` | Yes      | Calculation buffer to bind to the plot.                                            |
| `label`     | `string`      | Yes      | Displayed plot label.                                                              |
| `plotType`  | `PlotType`    | Yes      | Drawing representation.                                                            |
| `penStyle`  | `PenStyle`    | Yes      | Stroke pattern.                                                                    |
| `width`     | `number`      | Yes      | Plot-type-dependent width: line thickness, histogram column width, or symbol size. |
| `color`     | `Color`       | Yes      | CSS color value.                                                                   |

## Returns

`void`.

## Usage

1. Call `SetPlotCount` first so plot slots exist.
2. Create the buffer before `CreatePlot`.
3. Pick a unique zero-based `plotIndex` for each visible series.
4. Use [SetPlotStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-style) later if you need to change appearance without rebinding the buffer.

## Example

```typescript
this.MABuffer = this.api.CreateBuffer()
this.api.SetPlotCount(1)
this.api.CreatePlot(
    0,
    this.MABuffer,
    'Moving Average',
    PlotType.LINE,
    PenStyle.SOLID,
    1,
    '#FF0000'
)
```

## Related API

* [Plot setup workflow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup)
* [Calculation and visible buffers](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/calculation-vs-visible-buffers)
* [SetPlotCount](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-count)
* [CreateBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/create-buffer)
* [SetPlotBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-buffer)
* [SetPlotStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-style)
* [SetPlotLabel](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-label)
* [Color](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/color)
* [IndexBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/index-buffer)
* [PenStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/chart-objects-and-appearance/pen-style)
* [PlotType](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/plot-type)


# CrossOver

Detect when one series moves above another between the previous bar and the current bar.

## Signature

```typescript
CrossOver(index: number, source1: IndexBuffer, source2: IndexBuffer): boolean
CrossOver(index: number, source1: IndexBuffer, source2: PriceType): boolean
CrossOver(index: number, source1: PriceType, source2: IndexBuffer): boolean
CrossOver(index: number, source1: PriceType, source2: PriceType): boolean
```

## Parameters

| Name      | Type                       | Required | Description                                         |
| --------- | -------------------------- | -------- | --------------------------------------------------- |
| `index`   | `number`                   | Yes      | Current bar index; the previous bar is `index + 1`. |
| `source1` | `IndexBuffer \| PriceType` | Yes      | First buffer or price source.                       |
| `source2` | `IndexBuffer \| PriceType` | Yes      | Second buffer or price source.                      |

## Returns

`true` when `source1` is above `source2` at `index` and was at or below at `index + 1`; otherwise `false`.

## Usage

1. Call inside `OnCalculate` at the bar where you evaluate signals — usually a confirmed bar, not necessarily `index === 0`.
2. Each argument can be an `IndexBuffer` or a `PriceType` constant.
3. Guard lookback so both `index` and `index + 1` exist before calling.
4. The helper compares raw values and does not skip a buffer's configured empty value. When either source is an `IndexBuffer`, verify that both bars contain valid values before calling.
5. A result at `index === 0` can change while the current bar is forming. Evaluate a closed-bar index when the signal must not repaint.

## Example

```typescript
const bufferOverBuffer = this.api.CrossOver(
    index,
    this.FastBuffer,
    this.SlowBuffer
)
const bufferOverPrice = this.api.CrossOver(
    index,
    this.FastBuffer,
    PriceType.CLOSE
)
const priceOverBuffer = this.api.CrossOver(
    index,
    PriceType.CLOSE,
    this.SlowBuffer
)
const priceOverPrice = this.api.CrossOver(
    index,
    PriceType.HIGH,
    PriceType.CLOSE
)
```

## Related API

* [CrossUnder](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/cross-under)
* [IndexBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/index-buffer)
* [PriceType](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/market-data-and-calculations/price-type)


# CrossUnder

Detect when one series moves below another between the previous bar and the current bar.

## Signature

```typescript
CrossUnder(index: number, source1: IndexBuffer, source2: IndexBuffer): boolean
CrossUnder(index: number, source1: IndexBuffer, source2: PriceType): boolean
CrossUnder(index: number, source1: PriceType, source2: IndexBuffer): boolean
CrossUnder(index: number, source1: PriceType, source2: PriceType): boolean
```

## Parameters

| Name      | Type                       | Required | Description                                         |
| --------- | -------------------------- | -------- | --------------------------------------------------- |
| `index`   | `number`                   | Yes      | Current bar index; the previous bar is `index + 1`. |
| `source1` | `IndexBuffer \| PriceType` | Yes      | First buffer or price source.                       |
| `source2` | `IndexBuffer \| PriceType` | Yes      | Second buffer or price source.                      |

## Returns

`true` when `source1` is below `source2` at `index` and was at or above at `index + 1`; otherwise `false`.

## Usage

1. Mirror of [CrossOver](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/cross-over) for bearish or exit signals.
2. Mix buffers and price types on either side.
3. Ensure both bars exist before evaluating the cross.
4. The helper compares raw values and does not skip a buffer's configured empty value. When either source is an `IndexBuffer`, verify that both bars contain valid values before calling.
5. A result at `index === 0` can change while the current bar is forming. Evaluate a closed-bar index when the signal must not repaint.

## Example

```typescript
const bufferUnderBuffer = this.api.CrossUnder(
    index,
    this.FastBuffer,
    this.SlowBuffer
)
const bufferUnderPrice = this.api.CrossUnder(
    index,
    this.FastBuffer,
    PriceType.CLOSE
)
const priceUnderBuffer = this.api.CrossUnder(
    index,
    PriceType.CLOSE,
    this.SlowBuffer
)
const priceUnderPrice = this.api.CrossUnder(
    index,
    PriceType.LOW,
    PriceType.CLOSE
)
```

## Related API

* [CrossOver](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/cross-over)
* [IndexBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/index-buffer)
* [PriceType](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/market-data-and-calculations/price-type)


# GetPlotInfo

Inspect buffer binding, label, draw range, and style for one plot in a single call.

## Signature

```typescript
GetPlotInfo(plotIndex: number): PlotInfo
```

## Parameters

| Name        | Type     | Required | Description                    |
| ----------- | -------- | -------- | ------------------------------ |
| `plotIndex` | `number` | Yes      | Zero-based visible plot index. |

## Returns

The plot buffer, label, draw metadata, and current style.

## Usage

1. Use during debugging or when you need to clear a bound buffer programmatically.
2. Read `drawBeginIndex` and `style.isVisible` without multiple getter calls.

## Example

```typescript
const plot = this.api.GetPlotInfo(0)
plot.buffer?.clear()

const isVisible = plot.style.isVisible
const drawBegin = plot.drawBeginIndex
```

## Related API

* [Plot setup workflow](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/plot-setup)
* [Calculation and visible buffers](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/calculation-vs-visible-buffers)
* [GetPlotStyle](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/get-plot-style)
* [SetPlotBuffer](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/plots-and-buffers/set-plot-buffer)
* [PlotInfo](https://fto-2.gitbook.io/fto-indicators-docs/api-reference/types/plots-and-buffers/plot-info)




---

[Next Page](https://fto-2.gitbook.io/fto-indicators-docs/llms-full.txt/1)

