# Trendlines

> Zero-close-violation diagonal support and resistance rays fitted across fractal pivots with touch deduplication.

Canonical page: [https://docs.kami.trade/studies/trend/](https://docs.kami.trade/studies/trend/)

`trend` fits diagonal rising support and falling resistance trendlines across recent fractal pivots, rejecting any candidate line violated by a candle close beyond tolerance.

## Parameters

| Parameter | Default | Range | Type | Timeframe overrides |
| --- | --- | --- | --- | --- |
| `window` | `500` | `60..2000` | integer | — |
| `pivotSpan` | `3` | `2..10` | integer | `4` on `<= 5m`, `2` on `>= 1d` |
| `tolAtr` | `0.25` | `0.05..1.5` | number | — |
| `maxPivots` | `24` | `4..40` | integer | — |
| `minTouches` | `3` | `2..10` | integer | — |
| `max` | `2` | `1..5` | integer (per side) | — |

## Algorithm & Nuances

1. **Directional pivot pairs**: Evaluates pairs `(a, b)` among the most recent `maxPivots` swing lows (`slope > 0`, rising support) and swing highs (`slope < 0`, falling resistance).
2. **Anti-degenerate guards**: Rejects pairs closer than `4` bars (`b - a < 4`) or steeper than `1.5 * atr[b]` per bar.
3. **Zero close violations**: Walks every bar `k` from `a` to `n - 1`. If any candle closes past the line by more than `atr[k] * tolAtr`, the candidate is discarded (`closesBeyond` is always `0`).
4. **Touch deduplication**: Counts touches where `|price[k] - line(k)| <= atr[k] * tolAtr`, enforcing at least `TOUCH_GAP = 3` bars between touches so a tight sideways cluster cannot inflate touch counts.
5. **Composite score**:
   ```
   tightness = max(0, 1 - min(1, (errSum / touches) / max(tolAtr, 1e-6)))
   spanRatio = min(1, (lastTouch - a) / max(1, 0.4 * n))
   score     = touches + 0.8 * (lastTouch / (n - 1)) + 0.6 * spanRatio
               + 0.4 * tightness - 0.35 * min(maxWickAtr, 2)
   ```
6. **Two-touch fallback**: If a side produces zero lines meeting `minTouches` (when `minTouches > 2`), the engine retries with `minTouches = 2` and flags `facts.relaxed = true`.
7. **Deduplication**: Keeps up to `max` lines per side, rejecting candidates that share anchor `a` or `b` or project within `0.5 * atr[n - 1]` of an already selected line at bar `n - 1`.

## Drawings & Facts

- **Drawings**: Up to `2 * max` extended `trendline` rays (`extend: true`) labeled `Rising · N touches` (`'up'`) or `Falling · N touches` (`'down'`).
- **Facts (`TrendFacts`)**: `up[]`, `down[]`, and `relaxed` boolean. Each line reports `dir`, `from`, `to`, `slope`, `touches`, `touchTimes`, `closesBeyond`, `maxWickAtr`, `tightness`, `atEnd`, and `score`.

## Activation

- **Studies menu**: `Trendlines` (`Trend`)
- **Slash command**: `/trend`
- **Chat phrases**: `trend`, `trendline`, `trendlines`, `tl`, `tls`
