# This file is automatically generated by pyo3_stub_gen
# ruff: noqa: E501, F401

import typing

import numpy
import numpy.typing

# Enums
class AssetType:
    Stock: "AssetType"
    Fund: "AssetType"
    Futures: "AssetType"
    Option: "AssetType"

class SettlementType:
    Physical: "SettlementType"
    Cash: "SettlementType"

class OptionType:
    Call: "OptionType"
    Put: "OptionType"

class OrderType:
    Market: "OrderType"
    Limit: "OrderType"
    StopMarket: "OrderType"
    StopLimit: "OrderType"

class OrderSide:
    Buy: "OrderSide"
    Sell: "OrderSide"

class OrderStatus:
    New: "OrderStatus"
    Submitted: "OrderStatus"
    Filled: "OrderStatus"
    Cancelled: "OrderStatus"
    Rejected: "OrderStatus"
    Expired: "OrderStatus"

class TimeInForce:
    GTC: "TimeInForce"
    IOC: "TimeInForce"
    FOK: "TimeInForce"
    Day: "TimeInForce"

class ExecutionMode:
    CurrentClose: "ExecutionMode"
    NextOpen: "ExecutionMode"
    NextAverage: "ExecutionMode"
    NextHighLowMid: "ExecutionMode"

class Instrument:
    r"""
    交易标的.

    :ivar symbol: 代码
    :ivar asset_type: 资产类型
    :ivar multiplier: 合约乘数
    :ivar margin_ratio: 保证金比率
    :ivar tick_size: 最小变动价位
    """

    symbol: str
    asset_type: "AssetType"
    multiplier: typing.Any
    margin_ratio: typing.Any
    tick_size: typing.Any
    option_type: typing.Optional["OptionType"]
    strike_price: typing.Optional[typing.Any]
    expiry_date: typing.Optional[int]
    lot_size: typing.Any
    underlying_symbol: typing.Optional[str]
    settlement_type: typing.Optional["SettlementType"]
    def __new__(
        cls,
        symbol: str,
        asset_type: "AssetType",
        multiplier: typing.Optional[typing.Any] = ...,
        margin_ratio: typing.Optional[typing.Any] = ...,
        tick_size: typing.Optional[typing.Any] = ...,
        option_type: typing.Optional["OptionType"] = ...,
        strike_price: typing.Optional[typing.Any] = ...,
        expiry_date: typing.Optional[int] = ...,
        lot_size: typing.Optional[typing.Any] = ...,
        underlying_symbol: typing.Optional[str] = ...,
        settlement_type: typing.Optional["SettlementType"] = ...,
    ) -> "Instrument": ...

class DataFeed:
    r"""数据源."""

    def __new__(cls) -> "DataFeed": ...
    def add_bar(self, bar: "Bar") -> None: ...
    def add_bars(self, bars: list["Bar"]) -> None: ...
    def sort(self) -> None: ...

class TradingSession:
    PreOpen: "TradingSession"
    Continuous: "TradingSession"
    CallAuction: "TradingSession"
    Break: "TradingSession"
    Closed: "TradingSession"
    PostClose: "TradingSession"

class ATR:
    r"""Average True Range."""

    value: typing.Optional[float]
    def __new__(cls, period: int) -> "ATR": ...
    def update(
        self, high: float, low: float, close: float
    ) -> typing.Optional[float]: ...

class BacktestResult:
    r"""回测结果."""

    equity_curve: list[tuple[int, float]]
    metrics: "PerformanceMetrics"
    trade_metrics: "TradePnL"
    metrics_df: typing.Any
    orders_df: typing.Any
    trades: list["ClosedTrade"]
    snapshots: list[tuple[int, list["PositionSnapshot"]]]
    def get_trades_dict(self) -> dict[str, list[typing.Any]]: ...
    def get_positions_dict(self) -> dict[str, list[typing.Any]]: ...
    @property
    def executions(self) -> list["Trade"]: ...

class PositionSnapshot:
    r"""每日持仓快照."""

    symbol: str
    quantity: float
    cost_basis: float
    market_value: float
    unrealized_pnl: float

class Bar:
    r"""
    K线数据结构.

    :ivar timestamp: Unix 时间戳 (纳秒)
    :ivar open: 开盘价
    :ivar high: 最高价
    :ivar low: 最低价
    :ivar close: 收盘价
    :ivar volume: 成交量
    :ivar symbol: 标的代码
    """

    timestamp: int
    symbol: str
    extra: dict[str, float]
    open: float
    high: float
    low: float
    close: float
    volume: float
    timestamp_str: str
    def __new__(
        cls,
        timestamp: int,
        open: float,
        high: float,
        low: float,
        close: float,
        volume: float,
        symbol: str,
        extra: typing.Optional[dict[str, float]] = ...,
    ) -> "Bar": ...
    def set_open(self, value: typing.Any) -> None: ...
    def set_high(self, value: typing.Any) -> None: ...
    def set_low(self, value: typing.Any) -> None: ...
    def set_close(self, value: typing.Any) -> None: ...
    def set_volume(self, value: typing.Any) -> None: ...
    def __repr__(self) -> str: ...

class BarAggregator:
    r"""
    K线聚合器.

    用于将实时 Tick 数据聚合成 Bar 数据。
    """

    def __new__(
        cls, feed: "DataFeed", interval_min: typing.Optional[int] = ...
    ) -> "BarAggregator": ...
    def on_tick(
        self, symbol: str, price: float, volume: float, timestamp_ns: int
    ) -> None:
        r"""
        处理新的 Tick 数据.

        :param symbol: 标的代码
        :param price: 最新价
        :param volume: 累计成交量
        :param timestamp_ns: 时间戳 (纳秒)
        """
        ...

class BollingerBands:
    r"""Bollinger Bands."""

    value: typing.Optional[tuple[float, float, float]]
    def __new__(cls, period: int, multiplier: float) -> "BollingerBands": ...
    def update(self, value: float) -> typing.Optional[tuple[float, float, float]]:
        r"""Return (upper, middle, lower)."""
        ...

class ClosedTrade:
    r"""平仓交易记录."""

    symbol: str
    entry_time: int
    exit_time: int
    entry_price: float
    exit_price: float
    quantity: float
    side: str
    pnl: float
    net_pnl: float
    return_pct: float
    commission: float
    duration_bars: int
    duration: int
    mae: float
    mfe: float
    entry_tag: str
    exit_tag: str
    entry_portfolio_value: float
    max_drawdown_pct: float

class EMA:
    r"""Exponential Moving Average."""

    value: typing.Optional[float]
    is_ready: bool
    period: int
    def __new__(cls, period: int) -> "EMA": ...
    def update(self, value: float) -> typing.Optional[float]: ...

class Engine:
    r"""
    主回测引擎.

    :ivar feed: 数据源
    :ivar portfolio: 投资组合
    :ivar orders: 订单列表
    :ivar trades: 成交列表
    """

    portfolio: "Portfolio"
    orders: list["Order"]
    trades: list["Trade"]
    risk_manager: "RiskManager"
    def __new__(
        cls,
    ) -> "Engine": ...
    def set_history_depth(self, depth: int) -> None:
        r"""
        设置历史数据长度.

        :param depth: 历史数据长度
        """
        ...

    def set_timezone(self, offset: int) -> None:
        r"""
        设置时区偏移 (秒).

        :param offset: 偏移秒数 (例如 UTC+8 为 28800)
        """
        ...

    def use_simulated_execution(self) -> None:
        r"""
        启用模拟执行 (回测模式).

        默认模式。在内存中撮合订单。
        """
        ...

    def use_realtime_execution(self) -> None:
        r"""
        启用实盘执行 (CTP/Broker 模式).

        模拟对接 CTP 或其他 Broker API。
        在此模式下，订单会被标记为 Submitted 并等待回调 (目前仅模拟发送)。
        """
        ...

    def set_execution_mode(self, mode: "ExecutionMode") -> None:
        r"""
        设置撮合模式.

        :param mode: 撮合模式 (ExecutionMode.CurrentClose 或 ExecutionMode.NextOpen)
        :type mode: ExecutionMode
        """
        ...

    def use_simple_market(self, commission_rate: float) -> None:
        r"""
        启用 SimpleMarket (7x24小时, T+0, 无税, 简单佣金).

        :param commission_rate: 佣金率
        """
        ...

    def use_china_market(self) -> None:
        r"""启用 ChinaMarket (支持 T+1/T+0, 印花税, 过户费, 交易时段等)."""
        ...

    def use_china_futures_market(self) -> None:
        r"""
        启用中国期货市场默认配置.

        - 切换到 ChinaMarket
        - 设置 T+0
        - 保持当前交易时段配置 (需手动设置 set_market_sessions 以匹配特定品种)
        """
        ...

    def set_t_plus_one(self, enabled: bool) -> None:
        r"""
        启用/禁用 T+1 交易规则 (仅针对 ChinaMarket).

        :param enabled: 是否启用 T+1
        :type enabled: bool
        """
        ...

    def set_force_session_continuous(self, enabled: bool) -> None: ...
    def set_stock_fee_rules(
        self,
        commission_rate: float,
        stamp_tax: float,
        transfer_fee: float,
        min_commission: float,
    ) -> None: ...
    def set_future_fee_rules(self, commission_rate: float) -> None: ...
    def set_fund_fee_rules(
        self, commission_rate: float, transfer_fee: float, min_commission: float
    ) -> None: ...
    def set_option_fee_rules(self, commission_per_contract: float) -> None: ...
    def set_slippage(self, type_: str, value: float) -> None:
        r"""
        设置滑点模型.

        :param type: 滑点类型 ("fixed" 或 "percent")
        :param value: 滑点值 (固定金额 或 百分比如 0.001)
        """
        ...

    def set_volume_limit(self, limit: float) -> None:
        r"""
        设置成交量限制.

        :param limit: 限制比例 (0.0-1.0), 0.0 为不限制
        """
        ...

    def set_market_sessions(
        self, sessions: typing.Sequence[tuple[str, str, "TradingSession"]]
    ) -> None: ...
    def add_instrument(self, instrument: "Instrument") -> None:
        r"""
        添加交易标的.

        :param instrument: 交易标的对象
        :type instrument: Instrument
        """
        ...

    def set_cash(self, cash: float) -> None:
        r"""
        设置初始资金.

        :param cash: 初始资金数额
        :type cash: float
        """
        ...

    def add_data(self, feed: DataFeed) -> None:
        r"""
        添加数据源.

        :param feed: 数据源对象
        :type feed: DataFeed
        """
        ...

    def add_bars(self, bars: typing.Sequence[Bar]) -> None:
        r"""
        批量添加 K 线数据.

        :param bars: K 线列表
        """
        ...

    def run(self, strategy: typing.Any, show_progress: bool) -> str:
        r"""
        运行回测.

        :param strategy: 策略对象
        :param show_progress: 是否显示进度条
        :type strategy: object
        :type show_progress: bool
        :return: 回测结果摘要
        :rtype: str
        """
        ...

    def get_results(self) -> "BacktestResult":
        r"""
        获取回测结果.

        :return: BacktestResult
        """
        ...

    def create_context(
        self, active_orders: typing.Sequence["Order"]
    ) -> "StrategyContext": ...

class MACD:
    r"""Moving Average Convergence Divergence."""

    value: typing.Optional[tuple[float, float, float]]
    def __new__(
        cls, fast_period: int, slow_period: int, signal_period: int
    ) -> "MACD": ...
    def update(self, value: float) -> typing.Optional[tuple[float, float, float]]:
        r"""Return (macd_line, signal_line, histogram)."""
        ...

class Order:
    r"""
    订单.

    :ivar id: 订单ID
    :ivar symbol: 标的代码
    :ivar side: 交易方向
    :ivar order_type: 订单类型
    :ivar quantity: 数量
    :ivar price: 价格 (限价单有效)
    :ivar time_in_force: 订单有效期
    :ivar trigger_price: 触发价格 (止损/止盈单)
    :ivar status: 订单状态
    :ivar filled_quantity: 已成交数量
    :ivar average_filled_price: 成交均价
    :ivar created_at: 创建时间戳
    :ivar updated_at: 更新时间戳
    :ivar tag: 订单标签
    :ivar reject_reason: 拒绝原因
    """

    id: str
    symbol: str
    side: "OrderSide"
    order_type: "OrderType"
    time_in_force: "TimeInForce"
    status: "OrderStatus"
    quantity: float
    price: typing.Optional[float]
    trigger_price: typing.Optional[float]
    filled_quantity: float
    average_filled_price: typing.Optional[float]
    created_at: int
    updated_at: int
    tag: str
    reject_reason: str
    def __new__(
        cls,
        id: str,
        symbol: str,
        side: "OrderSide",
        order_type: "OrderType",
        quantity: float,
        price: typing.Optional[float] = ...,
        time_in_force: "TimeInForce" = ...,
        trigger_price: typing.Optional[float] = ...,
        created_at: typing.Optional[int] = ...,
        tag: typing.Optional[str] = ...,
    ) -> "Order": ...
    def __repr__(self) -> str: ...

class PerformanceMetrics:
    r"""绩效指标."""

    total_return: float
    annualized_return: float
    max_drawdown: float
    max_drawdown_pct: float
    sharpe_ratio: float
    sortino_ratio: float
    volatility: float
    ulcer_index: float
    upi: float
    equity_r2: float
    std_error: float
    win_rate: float
    initial_market_value: float
    end_market_value: float
    total_return_pct: float
    start_time: int
    end_time: int
    duration: int
    total_bars: int

class Portfolio:
    r"""
    投资组合管理.

    :ivar cash: 当前现金余额
    :ivar positions: 当前持仓 (symbol -> quantity)
    :ivar available_positions: 可用持仓 (symbol -> quantity)
    """

    cash: float
    positions: dict[str, float]
    available_positions: dict[str, float]
    def __new__(cls, cash: typing.Any) -> "Portfolio": ...
    def get_position(self, symbol: str) -> float: ...
    def get_available_position(self, symbol: str) -> float: ...
    def __repr__(self) -> str: ...

class RSI:
    r"""Relative Strength Index."""

    value: typing.Optional[float]
    def __new__(cls, period: int) -> "RSI": ...
    def update(self, value: float) -> typing.Optional[float]: ...

class RiskConfig:
    r"""
    风控配置.

    :ivar max_order_size: 单笔最大下单数量
    :ivar max_order_value: 单笔最大下单金额
    :ivar max_position_size: 最大持仓数量 (绝对值)
    :ivar restricted_list: 限制交易标的列表
    :ivar active: 是否启用风控
    """

    max_order_size: typing.Optional[float]
    max_order_value: typing.Optional[float]
    max_position_size: typing.Optional[float]
    restricted_list: list[str]
    active: bool
    safety_margin: float
    def __new__(cls) -> "RiskConfig": ...

class RiskManager:
    r"""
    风控管理器.

    :ivar config: 风控配置
    """

    config: RiskConfig
    def check(
        self,
        order: "Order",
        portfolio: "Portfolio",
        instruments: dict[str, "Instrument"],
        active_orders: list["Order"],
    ) -> typing.Optional[str]: ...

class SMA:
    r"""Simple Moving Average."""

    value: typing.Optional[float]
    is_ready: bool
    def __new__(cls, period: int) -> "SMA": ...
    def update(self, value: float) -> typing.Optional[float]: ...

class StrategyContext:
    r"""
    策略上下文.

    :ivar orders: 订单列表 (内部使用)
    :ivar cash: 当前现金
    :ivar positions: 当前持仓
    :ivar available_positions: 可用持仓
    :ivar session: 当前交易时段
    """

    orders: list[Order]
    canceled_order_ids: list[str]
    active_orders: list[Order]
    session: "TradingSession"
    last_closed_trade: typing.Optional[ClosedTrade]
    closed_trades: list[ClosedTrade]
    recent_trades: list[Trade]
    cash: float
    positions: dict[str, float]
    available_positions: dict[str, float]
    risk_config: RiskConfig
    def __new__(
        cls,
        cash: typing.Any,
        positions: typing.Mapping[str, float],
        available_positions: typing.Mapping[str, float],
        session: typing.Optional["TradingSession"],
        active_orders: typing.Optional[typing.Sequence[Order]],
        closed_trades: typing.Optional[typing.Sequence[ClosedTrade]],
        recent_trades: typing.Optional[typing.Sequence[Trade]],
        risk_config: typing.Optional[RiskConfig],
    ) -> "StrategyContext": ...
    def history(
        self, symbol: str, field: str, count: int
    ) -> typing.Optional[numpy.typing.NDArray[numpy.float64]]:
        r"""
        获取历史数据.

        :param symbol: 标的代码
        :param field: 字段名 (open, high, low, close, volume)
        :param count: 获取的数据长度
        :return: numpy array or None
        """
        ...

    def schedule(self, timestamp: int, payload: str) -> None:
        r"""
        注册定时器.

        :param timestamp: 触发时间戳 (纳秒)
        :param payload: 携带的数据 (如回调函数名)
        """
        ...

    def cancel_order(self, order_id: str) -> None:
        r"""
        取消订单.

        :param order_id: 订单 ID
        """
        ...

    def buy(
        self,
        symbol: str,
        quantity: float,
        price: typing.Optional[float] = ...,
        time_in_force: typing.Optional["TimeInForce"] = ...,
        trigger_price: typing.Optional[float] = ...,
        tag: typing.Optional[str] = ...,
    ) -> str: ...
    def sell(
        self,
        symbol: str,
        quantity: float,
        price: typing.Optional[float] = ...,
        time_in_force: typing.Optional["TimeInForce"] = ...,
        trigger_price: typing.Optional[float] = ...,
        tag: typing.Optional[str] = ...,
    ) -> str: ...
    def get_position(self, symbol: str) -> float: ...
    def get_available_position(self, symbol: str) -> float: ...

class Tick:
    r"""
    Tick 数据结构.

    :ivar timestamp: Unix 时间戳 (纳秒)
    :ivar price: 最新价
    :ivar volume: 成交量
    :ivar symbol: 标的代码
    """

    timestamp: int
    symbol: str
    price: float
    volume: float
    timestamp_str: str
    def __new__(
        cls, timestamp: typing.Any, price: typing.Any, volume: typing.Any, symbol: str
    ) -> "Tick": ...
    def set_price(self, value: typing.Any) -> None: ...
    def set_volume(self, value: typing.Any) -> None: ...
    def __repr__(self) -> str: ...

class Trade:
    r"""
    成交记录.

    :ivar id: 成交ID
    :ivar order_id: 订单ID
    :ivar symbol: 标的代码
    :ivar side: 交易方向
    :ivar quantity: 成交数量
    :ivar price: 成交价格
    :ivar commission: 手续费
    :ivar timestamp: Unix 时间戳 (纳秒)
    """

    id: str
    order_id: str
    symbol: str
    side: "OrderSide"
    timestamp: int
    bar_index: int
    quantity: float
    price: float
    commission: float
    def __new__(
        cls,
        id: str,
        order_id: str,
        symbol: str,
        side: "OrderSide",
        quantity: typing.Any,
        price: typing.Any,
        commission: typing.Any,
        timestamp: int,
        bar_index: int,
    ) -> "Trade": ...
    def __repr__(self) -> str: ...

class TradePnL:
    r"""交易盈亏统计 (FIFO)."""

    gross_pnl: float
    net_pnl: float
    total_commission: float
    total_closed_trades: int
    won_count: int
    lost_count: int
    won_pnl: float
    lost_pnl: float
    win_rate: float
    loss_rate: float
    unrealized_pnl: float
    avg_pnl: float
    avg_return_pct: float
    avg_trade_bars: float
    avg_profit: float
    avg_profit_pct: float
    avg_winning_trade_bars: float
    avg_loss: float
    avg_loss_pct: float
    avg_losing_trade_bars: float
    largest_win: float
    largest_win_pct: float
    largest_win_bars: float
    largest_loss: float
    largest_loss_pct: float
    largest_loss_bars: float
    max_wins: int
    max_losses: int
    profit_factor: float
    total_profit: float
    total_loss: float

def from_arrays(
    timestamps: typing.Any,
    opens: typing.Any,
    highs: typing.Any,
    lows: typing.Any,
    closes: typing.Any,
    volumes: typing.Any,
    symbol: typing.Optional[str],
    symbols: typing.Optional[typing.Sequence[str]],
    extra: typing.Optional[typing.Mapping[str, typing.Any]],
) -> list[Bar]:
    r"""从数组批量创建 Bar 列表 (Python 优化用 - Zero Copy)."""
    ...
