

from typing import Any, Dict, Optional, Tuple
import time
from utils.loader import get_config_loader

# 获取配置加载器
_config = get_config_loader()

# 代码用于计算交易所的订单异常情况，例如订单连续失败，订单连续产生较大下单延迟等。

def exchange_order_failure_check(index: int, order_receipt: Dict[str, Any]) -> bool:
    """
    检查交易所订单回执是否失败
    """
    if not isinstance(order_receipt, dict):
        return False
    return "Ok" in order_receipt
    
def exchange_order_slippage_check(order: Dict[str, Any], threshold_bps: Optional[float] = None) -> Tuple[bool, Optional[float], float]:
    """
    交易所层面滑点检查
    - 以下单 price 与成交均价 filled_avg_price 计算滑点（bps）
    - 如果未指定 threshold_bps，则从配置文件读取
    """
    if threshold_bps is None:
        threshold_bps = _config.get_order_config()['abnormal_order_slippage_threshold']
    try:
        price = float(order.get("price"))
        filled = float(order.get("filled", 0.0) or 0.0)
        filled_avg_price = float(order.get("filled_avg_price")) if filled > 0 else None
    except Exception:
        return False, None, threshold_bps

    if not price or filled_avg_price is None or price <= 0:
        return False, None, threshold_bps
    slippage_bps = abs(filled_avg_price - price) / price * 10000.0
    return slippage_bps > threshold_bps, slippage_bps, threshold_bps
    
def exchange_order_latency_check(order: Dict[str, Any], threshold_ms: Optional[int] = None) -> Tuple[bool, Optional[int], int]:
    """
    交易所层面下单延迟检查
    - 以当前时间与 order['timestamp'] 相差计算下单延迟
    - 如果未指定 threshold_ms，则从配置文件读取
    """
    if threshold_ms is None:
        threshold_ms = _config.get_order_config()['abnormal_order_latency_threshold']
    try:
        ts = int(order.get("timestamp"))
    except Exception:
        return False, None, threshold_ms
    now_ms = int(time.time() * 1000)
    latency = max(0, now_ms - ts)
    return latency > threshold_ms, latency, threshold_ms

