# 布林线 (BBANDS)

> 已核验的 StratForge C++23 API、计算与预热行为。

**Route**: `/indicators/bbands/`

固定使用简单移动平均和总体标准差（除以 n，而不是 n - 1）。三条轨道与输入价格单位相同。此构造函数没有 movav 选项。

`mid = SMA(period)`

`top = mid + devfactor * sqrt(sum((price - mid)^2) / period)`

`bottom = mid - devfactor * sqrt(sum((price - mid)^2) / period)`

## 参数

- `period = 20`
- `devfactor = 2.0`

## 计算示例

period = 4，价格 [2, 4, 6, 8] 的均值为 5，偏差平方为 [9, 1, 1, 9]，方差为 5，标准差为 sqrt(5)。devfactor = 2 时：mid = 5，top = 9.472136，bottom = 0.527864（六位小数）。前三根柱输出 NaN，第 4 根首次有效；默认周期需要 20 根柱。

使用有限价格及正数周期和回看长度。此版本把零周期或零回看长度归一为 1，不校验自定义安全值，也不保证非有限价格的输出有意义。示例计算不是交易信号或收益证据。

## C++23 API — StratForge

```cpp
#include <stratforge/indicators/bollinger.hpp>
#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>

int main() {
    stratforge::Line<double> close;
    stratforge::BollingerBands bands(close, 4, 2.0);
    assert(bands.minimum_period() == 4);
    for (double price : {2.0, 4.0, 6.0, 8.0}) {
        close.forward(price);
        bands.next();
        if (close.size() < 4) {
            assert(std::isnan(bands.mid()[0]));
            assert(std::isnan(bands.top()[0]));
            assert(std::isnan(bands.bottom()[0]));
        }
    }
    assert(std::abs(bands.mid()[0] - 5.0) < 1e-9);
    assert(std::abs(bands.top()[0] - 9.472135955) < 1e-9);
    assert(std::abs(bands.bottom()[0] - 0.527864045) < 1e-9);
    std::cout << std::fixed << std::setprecision(6)
              << bands.mid()[0] << " " << bands.top()[0] << " "
              << bands.bottom()[0] << "\n";
}
```

## 复现

StratForge `d25404dcf2c3842ba304ddc60ac19cfec1f8aa37` (2026-08-28); GCC 14, C++23; scalar build, no xsimd dependency.

```sh
git clone https://github.com/StratCraftsAI/StratForge.git StratForge
git -C StratForge checkout --detach d25404dcf2c3842ba304ddc60ac19cfec1f8aa37
g++-14 -std=c++23 -O2 -Wall -Wextra -pedantic -IStratForge/include example.cpp -o example
./example
```

`example.cpp`: C++23 API. stdout:

```text
5.000000 9.472136 0.527864
```

## 来源

- [StratForge bollinger.hpp](https://github.com/StratCraftsAI/StratForge/blob/d25404dcf2c3842ba304ddc60ac19cfec1f8aa37/include/stratforge/indicators/bollinger.hpp)
- [StratForge Line](https://github.com/StratCraftsAI/StratForge/blob/d25404dcf2c3842ba304ddc60ac19cfec1f8aa37/include/stratforge/core/line.hpp)
- [StratForge population variance](https://github.com/StratCraftsAI/StratForge/blob/d25404dcf2c3842ba304ddc60ac19cfec1f8aa37/include/stratforge/simd/simd_ops.hpp)
