# Write an indicator

## The parts

An indicator file has one class that extends `fg.Indicator`. It holds four things: the settings, the outputs, the warm-up and the calculation.

```python
import forge as fg
from forge import param, ta

FORGE_API = 1


class Stretch(fg.Indicator):
    name = "Stretch"
    short_name = "STR"
    pane = "new"

    period = param.Int(20, min=2, max=200)

    stretch = fg.Output.histogram("Distance from the average")
    warmup = lambda self: self.period

    def calculate(self, bars, start) -> None:
        distance = bars.close - ta.sma(bars.close, self.period)
        self.out.stretch[start:] = distance[start:]
```

The class draws how far the close is from its average. `pane = "new"` puts it under the price, and `warmup` says the first `period` bars have no value.

## Choose one form

An indicator defines exactly one of two methods.

- `calculate(self, bars, start)` fills every output from bar `start` on. Use it when the result is a formula over whole arrays.
- `on_bar(self, i)` runs once per bar and keeps its memory in declared state fields. Use it when each bar depends on the last.

Both forms must give the same values, and a full run must give the same values as one that continues from earlier bars. Write the form that is simpler to read.

> **Trap.** `bars` is ordered oldest first. Index `-1` is the latest closed bar, and there is no index for a later one.

## Outputs

Each output has a kind that decides how a strategy can use it: a line or histogram is a number, a state is true or false, an event is 1, -1 or 0 on the bar it happens. Every output is read by its name.

## Limits

An indicator cannot trade. It cannot place orders or read the account, and a file that tries is refused when it loads.

Start from a template in [the examples](https://oathra.dev/examples) if you would rather change a working file than begin from nothing.
