# 核心模块接口说明

> 定义各 package 暴露的主要类、方法签名、数据模型及依赖关系，统一编码约束。

---

## 1. 公共类型

- 统一 Typescript 接口位于 `packages/domain/src/types.ts`，需至少包含：
  ```ts
  export type Side = 'buy' | 'sell';
  export type TimeInForce = 'GTC' | 'IOC' | 'FOK';

  export interface OrderIntent {
    symbol: string;
    side: Side;
    price: number;
    size: number;
    tif: TimeInForce;
    postOnly?: boolean;
    clientId: string;
    strategyTag: 'grid' | 'scalper' | 'hedge';
  }

  export interface FillEvent {
    orderId: string;
    clientId: string;
    symbol: string;
    side: Side;
    price: number;
    size: number;
    fee: number;
    liquidity: 'maker' | 'taker';
    timestamp: number;
  }
  ```
- 所有模块引用公共类型，不允许重复定义字段。

---

## 2. MarketData / ShadowBook

| 模块 | 文件 | 责任 |
|------|------|------|
| `ShadowBook` | `packages/utils/src/shadowBook.ts` | 聚合多标的订单簿，提供 mid/spread/OBI 等派生指标 |
| `MarketDataAdapter` | `packages/utils/src/marketDataAdapter.ts` | 拉取或订阅行情并同步至 ShadowBook |

核心接口：

```ts
class ShadowBook {
  constructor(options?: { maxDepth?: number; stalenessMs?: number });
  updateFromSnapshot(symbol: string, snapshot: OrderBook, seq?: number): void;
  applyIncrement(symbol: string, delta: OrderBookDelta): void;
  snapshot(symbol: string): OrderBook | undefined;
  mid(symbol: string): number | undefined;
  spreadBps(symbol: string): number | undefined;
  computeObi(symbol: string, depth?: number): number | undefined;
  topDepthUsd(symbol: string, depth?: number): number | undefined;
  detectDataGap(symbol: string, now?: number): boolean;
  reset(): void;
}
```

`ShadowBook` 维护每个标的的最新订单簿，与策略/风控共享数据；若底层行情支持增量更新，可通过 `applyIncrement` 合并。

```ts
class MarketDataAdapter extends EventEmitter {
  constructor(options: { symbols: string[]; shadowBook: ShadowBook; fetchSnapshot: (symbol: string) => Promise<OrderBook>; pollIntervalMs?: number });
  start(): Promise<void>;
  stop(): void;
  ingestSnapshot(symbol: string, snapshot: OrderBook, seq?: number): void;
  ingestDelta(symbol: string, delta: OrderBookDelta): void;
}
```

- 默认实现基于轮询 REST 快照，可扩展为 WebSocket 增量模式。

---

## 3. Registry 层

### 3.1 SymbolRegistry

```ts
type SymbolStatus = 'inactive' | 'active' | 'paused' | 'disabled';

interface SymbolConfig {
  symbol: string;
  maxNotional: number;
  maxBase: number;
  enabled?: boolean;
  tags?: string[];
  metadata?: Record<string, unknown>;
}

class SymbolRegistry extends EventEmitter {
  constructor(initialConfigs?: SymbolConfig[]);
  register(config: SymbolConfig): SymbolRuntimeState;
  updateConfig(symbol: string, patch: Partial<SymbolConfig>): SymbolRuntimeState;
  activate(symbol: string): SymbolRuntimeState;
  pause(symbol: string, reason: string): SymbolRuntimeState;
  disable(symbol: string, reason?: string): SymbolRuntimeState;
  remove(symbol: string): void;
  list(status?: SymbolStatus): SymbolRuntimeState[];
  listActive(): SymbolRuntimeState[];
  setAllocation(symbol: string, allocation: RiskAllocation | undefined): SymbolRuntimeState;
  setScore(symbol: string, score: number | undefined): SymbolRuntimeState;
  on(event: 'registered' | 'updated' | 'statusChanged' | 'removed', handler: (...args)=>void): this;
}
```

- 保存符号配置、当前状态、最近分配的风险预算与评分。
- 所有状态更新通过事件触发，便于 Runner / RiskAllocator 监听。

### 3.2 RiskAllocator

```ts
interface RiskBudget { totalNotional: number; totalBase: number; }

class RiskAllocator {
  constructor(budget: RiskBudget, options?: { minNotionalPerSymbol?: number; minBasePerSymbol?: number });
  allocate(states: SymbolRuntimeState[]): Map<string, RiskAllocation>;
}
```

- 根据 `SymbolRuntimeState.score` 按比例分配风险预算，自动裁剪至每个符号的配置上限。
- 若配置了 `minNotionalPerSymbol` / `minBasePerSymbol`，会确保分配不低于该最小值。

### 3.3 SymbolScorer

```ts
interface SymbolMetrics {
  spreadBps: number;
  topDepthUsd: number;
  volumePerMin: number;
  fundingCorrelation: number;
  dataLatencyMs?: number;
}

class SymbolScorer {
  constructor(options?: ScorerOptions);
  score(metrics: SymbolMetrics): number;      // 0~1，越高代表越适合启用
  shouldEnable(metrics: SymbolMetrics): boolean;
}
```

- 默认权重均分在 spread / depth / volume / funding 之间，并对过期行情加惩罚。
- `shouldEnable` 同时检查 spread、深度、资金费率等硬阈值。

---

## 4. Strategy 层

### 3.1 StrategyCoordinator

```ts
interface StrategyCoordinatorOptions {
  priorities: ('grid' | 'scalper')[];
}

class StrategyCoordinator {
  constructor(options: StrategyCoordinatorOptions);
  registerProducer(tag: 'grid' | 'scalper', producer: AsyncGenerator<OrderIntent[]>): void;
  async nextIntentBatch(): Promise<OrderIntent[]>; // 按优先级+冲突处理返回
  resolveConflicts(intents: OrderIntent[]): OrderIntent[];
}
```

- 冲突规则：同一 symbol、对向意向 → 保留优先级高的策略；同向合并尺寸。
- `nextIntentBatch` 需支持 `Promise.race` 超时，避免阻塞。

### 3.2 GridMaker

当前网格策略直接依赖 `OrderRouter` 与 `HedgeEngine`，支持“全量重建”与“增量闭环”两种模式：

```ts
class GridMaker {
  constructor(
    cfg: GridConfig,
    router: OrderRouter,
    hedgeEngine: HedgeEngine,
    shadowBook: ShadowBook
  );
  handleOrderUpdate(update: ExchangeOrderUpdate): void; // 订阅订单状态，驱动增量 reconcile
  initialize(): Promise<void>;       // 读取 mid，按配置挂出买卖网格
  onFill(fill: Fill): Promise<void>; // 补挂对手单、更新 delta、触发 hedge
  onHedgeFill(fill: Fill): Promise<void>; // Hedger 成交后，根据实际结果校准 delta
  onTick(): Promise<void>;           // 定时调用，自适应步长/层数/偏移
  reset(): Promise<void>;            // 撤销未成交挂单并重新初始化（含 cancel-all fallback）
  getStatus(): GridStatus;           // 返回监控指标
  shutdown(): Promise<void>;         // 停机流程，取消所有挂单并释放资源
}
```

- `GridConfig` 字段详见 `config/grid.example.yaml` 与 `docs/CONFIG_REFERENCE.md`，增量/闭环控制逻辑、指标及配置说明详见 `docs/MICRO_GRID_CONTROL.md`；执行排期参考 `docs/MICRO_GRID_ROADMAP.md`。
- 增量模式中，`handleOrderUpdate` 必须从 `OrderRouter` 或交易所推送中获得最新状态，以支撑 `reconcileGrid()` 执行（详见源码）。
- 未来若接入 `StrategyCoordinator`，需新增返回 `OrderIntent[]` 的变体并在此文档说明。

### 3.3 MicroScalper

```ts
class MicroScalper {
  constructor(cfg: ScalperConfig, shadow: ShadowBook, signalBus: EventEmitter);
  onBook(book: OrderBookEvent): void;
  onTrade(trade: TradeEvent): void;
  drainIntents(): OrderIntent[];
}
```

- 内部维护冷却时间；`drainIntents` 每个周期输出并清空累计意向。

---

## 5. Execution 层

### 4.1 GlobalOrderCoordinator

```ts
interface GlobalOrderSnapshot {
  orderId: string;
  accountId: string;
  symbol: string;
  side: Side;
  price: number;
}

class GlobalOrderCoordinator extends EventEmitter {
  constructor(options?: { stpToleranceBps?: number });
  validate(intent: { accountId: string; symbol: string; side: Side; price: number }): void;
  register(snapshot: GlobalOrderSnapshot): void;
  release(orderId: string): void;
}
```

- 维护 `(symbol, price)` 到挂单列表的索引，阻止关联账户在相同价位对向挂单触发 STP。
- `stpToleranceBps` 用于允许极小价差以内的并行挂单（默认 0 表示严格禁止）。

### 5.2 OrderRouter

```ts
interface OrderRouterConfig {
  maxBps: number;
  minIntervalMs?: number;
  forbidPostOnlyCross?: boolean;
  clientIdCacheSize?: number;
}

class OrderRouter {
  constructor(
    sendLimit: (order: Order) => Promise<{ id: string }>,
    getBook: (symbol: string) => OrderBook | undefined,
    config: OrderRouterConfig
  );
  sendLimit(order: Order): Promise<string>;
  sendLimitChild(order: Order): Promise<string>; // 兼容旧接口
  sendIOC(order: Order): Promise<string>;
}
```

- 下单前执行滑点守卫、post-only 交叉检查、clientId 去重以及最小时间间隔节流。
- `getBook` 通常由 `ShadowBook.snapshot(symbol)` 实现，确保 router 获得最新 top-of-book。

---

## 6. Risk & Hedge

### 6.1 RiskEngine

```ts
interface RiskLimits {
  maxBaseAbs: number;
  maxNotionalAbs: number;
  maxOrderSz: number;
}

interface KillSwitchConfig {
  drawdownPct: number;
  triggers?: Array<{ type: 'pnl_drawdown' | 'delta_abs' | 'hedge_failure_count' | 'data_gap_sec'; threshold: number }>;
}

class RiskEngine {
  constructor(limits: RiskLimits, killSwitch?: KillSwitchConfig);
  preCheck(order: Order, position: PositionSnapshot, midPrice: number): void;
  reportFill(pnlDelta: number): void;
  updateEquity(equity: number): void;
  updateDeltaAbs(deltaAbs: number): void;
  recordHedgeFailure(): void;
  recordHedgeSuccess(): void;
  setDataGap(seconds: number): void;
  shouldHalt(): boolean;
  getStatus(): RiskStatus;
}
```

- `preCheck` 在下单前验证名义、库存、单笔限额。
- `updateEquity`/`updateDeltaAbs`/`recordHedgeFailure` 等接口由上层定期调用，Kill-switch 根据 drawdown 与触发器自动判定停机。

### 5.2 HedgeEngine

```ts
interface HedgeCfg { kp: number; ki: number; Qmax: number; minIntervalMs: number; }
interface HedgeResult { hedged: number; orderId?: string; clientId?: string; }

class HedgeEngine {
  constructor(cfg: HedgeCfg, place: (order: Order) => Promise<{ id: string }>, getMid: () => number | undefined);
  compute(delta: number): number;        // PI 控制器输出，截断至 ±Qmax
  maybeHedge(symbol: string, delta: number): Promise<HedgeResult>; // 按节流阈值提交 IOC 对冲，返回下单信息
}
```

- 当前版本未与风险引擎集成；若需要队列、重试等特性，请扩展代码并更新文档。

-### 6.2 FundingRateMonitor

```ts
interface FundingRate { rate: number; timestamp: number; venue?: string; }

class FundingRateMonitor extends EventEmitter {
  constructor(options: { fetchPrimary: () => Promise<FundingRate>; fetchHedge: () => Promise<FundingRate>; pollIntervalMs?: number });
  start(): Promise<void>;
  stop(): void;
}
```

- 定期抓取主账户与对冲账户的资金费率，输出是否同向支付等指标。后续可计算相关性、驱动风险降级。

---

## 7. Telemetry

```ts
class Telemetry {
  recordCounter(name: string, labels: Record<string,string>, value?: number): void;
  observeHistogram(name: string, labels: Record<string,string>, value: number): void;
  setGauge(name: string, labels: Record<string,string>, value: number): void;
}
```

- 指标定义集中于 `packages/telemetry/metrics.ts`，模块通过依赖注入使用。
- 不允许直接调用 `prom-client`，避免重复注册。

---

## 8. 依赖与初始化

最小可运行流程：

1. 读取 `config.yaml`（或 `config/grid.example.yaml`）并实例化 `GridConfig`、`HedgeCfg`、风险参数。
2. 初始化发送下单的回调（正式版应调用 `Pacifica` adapter）。
3. 创建单例 `ShadowBook`，在收到行情快照时调用 `shadowBook.set(book)`.
4. 实例化 `OrderRouter`、`HedgeEngine`、`GridMaker`，并在首个 mid 可用时调用 `gridMaker.initialize()`.
5. 将成交事件传递给 `gridMaker.onFill(fill)`，由其内部处理补单与对冲。

> 引入其他策略或协调器后，请扩展本节并保证文档与实现保持一致。

---

## 8. 错误与日志规范

- 每个模块定义自有错误类型，位于 `packages/errors`.
- 捕获异常需写入结构化日志：
  ```ts
  logger.error({ err, intent, module: 'OrderRouter' }, 'order rejected');
  ```
- 日志字段：
  - `traceId`: 贯穿意向 → 下单 → 成交 → 对冲 → 降级
  - `accountId`, `strategyTag`, `symbol`
  - `deltaBefore`, `deltaAfter` (RiskEngine / HedgeEngine)

---

## 9. 文档维护

- 本文件版本号与代码同步更新（`Version: 1.0.0` 初始）。
- 新增模块需补充章节，PR 必须更新该文档并通过审查。
### 5.3 AdapterRegistry（`packages/connectors/pacifica/src/adapterRegistry.ts`）

```ts
interface AdapterRegistryEntry {
  id: string;
  role?: string;
  adapter: PacificaAdapter;
}

class AdapterRegistry {
  register(id: string, config: PacificaConfig, role?: string): AdapterRegistryEntry;
  attach(id: string, adapter: PacificaAdapter, role?: string): AdapterRegistryEntry;
  get(id: string): PacificaAdapter;
  findByRole(role: string): PacificaAdapter | undefined;
  collectPositions(symbol: string): Promise<PositionSnapshot[]>;
}
```

- 同时管理 maker / hedger 等账户 adapter，便于在执行层动态选择账户。`collectPositions` 供 PositionManager 聚合风险使用。

### 5.4 PacificaWebSocket（`packages/connectors/pacifica/src/wsClient.ts`）

```ts
interface PacificaWebSocketConfig {
  url: string;
  apiKey?: string;      // account address
  secret?: string;      // private key
  subaccount?: string;
  reconnectIntervalMs?: number;
  maxReconnectIntervalMs?: number;
  heartbeatIntervalMs?: number;
}

class PacificaWebSocket extends EventEmitter {
  constructor(config: PacificaWebSocketConfig);
  connect(): void;
  disconnect(): void;
  subscribe(channel: string, params?: Record<string, unknown>): void;
  subscribeAuthenticated(channel: string, params?: Record<string, unknown>, authOverride?: SigningConfig): void;
  sendRaw(payload: unknown): void;
}
```

- 负责维护 WebSocket 连接、登录校验（如提供账户 address / private key）、心跳与重连，断线后自动恢复订阅。事件：`open`、`close`、`error`、`message`、`reconnected`。
- `SigningConfig` 定义复用 `packages/connectors/pacifica/src/signing.ts`。
- `subscribeAuthenticated` 可显式传入凭证（多账号时很有用），否则默认使用 constructor 配置；`orders.*` / `fills.*` / `account.*` 会自动套用签名。

---
