# 核心流程时序图

> 描述行情处理、策略执行、下单、对冲和降级的关键步骤，确保团队在实现与调试时对事件顺序达成共识。

---

## 1. 行情 → 网格执行

```mermaid
sequenceDiagram
    participant WS as Pacifica WS
    participant MD as MarketDataAdapter
    participant SB as ShadowBook
    participant GM as GridMaker
    participant SC as StrategyCoordinator
    participant GOC as GlobalOrderCoordinator
    participant RE as RiskEngine
    participant OR as OrderRouter

    WS->>MD: book.BTC update (seq, bids, asks)
    MD->>SB: applyIncrement()
    Note right of SB: 校验 seq<br/>更新 mid, spread
    loop tradingInterval
        GM->>SB: getMid()
        SB-->>GM: mid price
        GM->>GM: 计算网格差额 / Delta
        GM->>SC: emit intents[]
        SC->>SC: 按优先级去冲突
        SC->>GOC: intents[]
        GOC->>GOC: STP / 自成交检查
        GOC->>RE: intent
        RE->>RE: preCheck()
        RE-->>GOC: OK
        GOC->>OR: sendLimit()
        OR->>OR: 滑点守卫 / 节流
        OR->>Pacifica: POST /orders
        OR-->>GOC: orderId
    end
```

- `GridMaker` 在 `onTimer` 内调用一次，返回的意向批量处理。
- 若 `RiskEngine.preCheck` 抛错，`StrategyCoordinator` 记录失败并等待下一周期。

> **当前实现差异**：代码中尚未启用 `StrategyCoordinator` / `GlobalOrderCoordinator`，`GridMaker` 会直接调用 `OrderRouter.sendLimitChild()`。待协调器上线后，请将实现与上述流程对齐并更新此注释。

---

## 2. 成交 → 对冲流程

```mermaid
sequenceDiagram
    participant WS as Pacifica WS
    participant MD as MarketDataAdapter
    participant SB as ShadowBook
    participant GM as GridMaker
    participant HE as HedgeEngine
    participant RE as RiskEngine
    participant OR as OrderRouter

    WS->>MD: fills.maker fillEvent
    MD->>SB: update position snapshot
    MD->>GM: onFill(fill)
    GM->>GM: 更新 Delta / 重挂对手单
    GM-->>HE: enqueueDelta(symbol, delta)
    HE->>HE: PI 控制计算需要对冲量
    HE->>RE: preCheck(intent: hedge)
    RE-->>HE: OK
    HE->>OR: sendIOC()
    OR->>Pacifica: POST /orders (IOC)
    Pacifca-->>OR: fill | partial | reject
    alt success
        OR-->>HE: orderId
        HE->>RE: reportFill()
    else failure
        OR-->>HE: error
        HE->>HE: 重试 <= retryMax
        HE->>Telemetry: hedge_failure_count++
    end
```

- 对冲在独立工作线程执行，遵守 `minIntervalMs` 与 `maxExposureSec`。
- 超时未完成 → `HE` 触发强制市价平仓并记录 incident。

---

## 3. 剥头皮执行路径

```mermaid
sequenceDiagram
    participant WS as Pacifica WS
    participant MD as MarketDataAdapter
    participant SB as ShadowBook
    participant MS as MicroScalper
    participant SC as StrategyCoordinator
    participant GOC as GlobalOrderCoordinator
    participant RE as RiskEngine
    participant OR as OrderRouter

    WS->>MD: trade stream
    MD->>SB: update trade stats
    SB-->>MS: onTrade()
    MD->>MS: onBook() (spread, OBI)
    MS->>MS: 判断触发条件 / 冷却
    MS-->>SC: intents (passive + taker legs)
    SC->>SC: 合并 grid & scalper
    Note right of SC: 剥头皮优先级低于网格<br/>冲突时保留网格
    SC->>GOC: intents
    GOC->>RE: preCheck
    RE-->>GOC: OK
    GOC->>OR: sendLimit / sendIOC
```

- Scalper 意向可能包含组合单：先下被动单，再设 OCO；`StrategyCoordinator` 需按顺序传递。
- 若 `strategy_mode='both'`，GridMaker 生成的挂单优先。

---

## 4. Kill-switch / 降级流程

```mermaid
sequenceDiagram
    participant RE as RiskEngine
    participant DP as DegradationPolicy
    participant OR as OrderRouter
    participant STR as StrategyCoordinator
    participant RUN as Runner

    Note over RE: 每 1s 检查指标<br/>PnL / Delta / HedgeFailure / DataGap
    RE->>RE: checkKillSwitch()
    alt 无异常
        RE-->>DP: { action: 'NONE' }
    else Kill-switch
        RE-->>DP: { action: 'HALT', reason }
        DP->>OR: cancelAll()
        DP->>STR: pauseStrategies()
        DP->>Telemetry: emit incident
        DP->>RUN: notify operator
    else 降级
        RE-->>DP: { action: 'REDUCE_ONLY' }
        DP->>STR: enterReduceOnly()
    end
```

- 降级状态需持久化（文件或内存镜像），重启时恢复。
- 运维可通过 API 覆盖状态（参见 Operations Playbook）。

---

## 5. 配置热更新金丝雀

```mermaid
sequenceDiagram
    participant OPS as Operator
    participant CFG as ConfigService
    participant TEST as Backtest Harness
    participant CAN as Canary Runner
    participant PROD as Live Runner

    OPS->>CFG: 提交新 config.yaml
    CFG->>CFG: zod 校验
    CFG-->>OPS: 校验通过/失败
    OPS->>TEST: 触发 backtest --smoke
    TEST-->>OPS: 结果 (EV, Sharpe, delta_abs)
    alt 结果合格
        OPS->>CAN: reload config (single symbol)
        CAN->>Telemetry: 推送 KPI (10 分钟)
        CAN-->>OPS: KPI 达标?
        alt 达标
            OPS->>PROD: reload config 全量
            PROD->>Telemetry: 监控 30 分钟
        else 回滚
            OPS->>CAN: rollback config
        end
    else 回滚
        CFG->>CFG: restore previous version
    end
```

- 全流程写审计日志：提交人、时间、版本差异、结果。

---

## 6. 日志 trace 链

```
TRACE_ID 生命周期：
  StrategyIntentCreated → IntentValidated → OrderSubmitted → OrderAcknowledged →
  FillReceived → HedgeTriggered → HedgeCompleted → ExposureSnapshotUpdated → TelemetryFlushed
```

- 所有模块必须将 `traceId` 传递下去，便于事故回放。

---

## 7. 开发注意事项

- 新增流程需同时更新本文件与相关模块文档。
- 时序图采用 Mermaid 语法，PR 中通过预览确认可视化正常。
