# Fair Value Gaps

> Three-candle BISI and SIBI imbalance detection with Consequent Encroachment (CE), partial fill tracking, and Inverted FVGs.

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

`fvg` detects 3-candle price imbalances (Fair Value Gaps), tracks wick fill percentage and Consequent Encroachment (`CE` midpoint) touches, and optionally flips closed-through gaps into Inverted FVGs (`IFVG`).

## Parameters

| Parameter | Default | Range | Type | Timeframe overrides |
| --- | --- | --- | --- | --- |
| `window` | `500` | `60..2000` | integer | — |
| `minGapAtr` | `0.3` | `0.05..3` | number | `0.45` on `<= 5m` |
| `max` | `6` | `1..12` | integer | — |
| `includeInverted` | `1` | `0..1` | integer (`0` or `1`) | — |

## Algorithm & Nuances

1. **Three-candle imbalance (`fvgScan`)**:
   - **Bullish FVG (BISI)**: `c[i] > o[i]` and `l[i + 1] > h[i - 1]`, bounds `[h[i - 1], l[i + 1]]`.
   - **Bearish FVG (SIBI)**: `c[i] < o[i]` and `h[i + 1] < l[i - 1]`, bounds `[h[i + 1], l[i - 1]]`.
   - Filters out tiny gaps where `(high - low) / atr[i] < minGapAtr`. Computes Consequent Encroachment `ce = (low + high) / 2`.
2. **Lifecycle & inversion**: Walks forward `k = i + 2 .. n - 1`:
   - **Wick mitigation**: Tracks maximum penetration `fillPct` and whether price touched `ce` (`ceTested`). If a wick fills `100%` without closing through, the gap is fully mitigated and dropped; partial fills transition status to `'partial'`.
   - **Close-through → `IFVG`**: When a close breaks the far edge (`c[k] < low` for bull, `c[k] > high` for bear): if `includeInverted = 0`, the gap is dropped; if `includeInverted = 1`, it flips to `status = 'inverted'`, reverses `effectiveDir = -dir`, records `invertedAt = k`, and remains active until a subsequent close breaks back through its new far edge.
3. **Scoring & balanced selection**:
   ```
   statusMult = fresh ? 1.35 : partial ? (1 - fillPct * 0.4) : 0.9
   recency    = 0.6 + 0.4 * (created / max(1, n - 1))
   score      = r2(sizeAtr * statusMult * recency / (1 + distAtr / 5))
   ```
   Balances selection with up to `ceil(max / 2)` gaps below close and `ceil(max / 2)` above close, backfilled to `max`, sorted descending by `high`.

## Drawings & Facts

- **Drawings**: Up to `max` `zone` boxes from `createdAt` to the latest closed bar with a dashed `CE` midpoint line (`mid`). Fresh gaps render normal weight; partial and inverted gaps render `'faint'`. Color follows `effectiveDir` (`'up'` / `'down'`). Labels show `IFVG ↑|↓` or `FVG ↑|↓ · fresh|N%`.
- **Facts (`FvgFacts`)**: `lastClose`, `activeBull`, `activeBear`, `invertedCount`, and `gaps[]`.

## Activation

- **Studies menu**: `Fair value gaps: imbalances and IFVGs` (`FVG`)
- **Slash command**: `/fvg`
- **Chat phrases**: `fvg`, `fvgs`, `ifvg`, `imbalance`, `imbalances`, `gap`, `gaps`
