"""
订单管理完整示例

本示例演示了 Lean 中的所有主要订单类型和订单管理功能：
1. 市价单 (Market Order)
2. 限价单 (Limit Order)
3. 止损单 (Stop Market Order)
4. 止损限价单 (Stop Limit Order)
5. OrderTicket 对象的使用
6. 订单状态跟踪
7. 订单更新和取消
8. Bracket Orders（组合订单）
"""

from AlgorithmImports import *

class OrderManagementDemoAlgorithm(QCAlgorithm):
    """
    订单管理演示策略

    演示各种订单类型和订单管理技术
    """

    def Initialize(self):
        """初始化算法"""
        self.SetStartDate(2023, 1, 1)
        self.SetEndDate(2023, 3, 31)
        self.SetCash(100000)

        # 添加高流动性股票用于演示
        self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
        self.aapl = self.AddEquity("AAPL", Resolution.Minute).Symbol

        # 创建指标用于交易信号
        self.sma_short = self.SMA(self.spy, 20, Resolution.Hour)
        self.sma_long = self.SMA(self.spy, 50, Resolution.Hour)

        # RSI 用于超买超卖判断（RSI 的第 3 个参数是 MovingAverageType，第 4 个才是 Resolution）
        self.rsi = self.RSI(self.spy, 14, MovingAverageType.Simple, Resolution.Hour)

        # 设置预热
        self.SetWarmUp(TimeSpan.FromDays(50))

        # ========== 交易参数 ==========
        self.position_size = 10           # 每次交易股数
        self.stop_loss_pct = 0.02        # 止损百分比
        self.take_profit_pct = 0.05      # 止盈百分比
        self.trailing_stop_pct = 0.015   # 追踪止损百分比

        # ========== 订单跟踪 ==========
        self.active_tickets = {}          # 活跃订单
        self.entry_price = None           # 入场价格
        self.highest_price = None         # 最高价（用于追踪止损）
        self.trade_count = 0              # 交易计数
        self.starting_cash = self.Portfolio.TotalPortfolioValue  # 记录初始资金

        self.Debug("=" * 60)
        self.Debug("Order Management Demo - Initialized")
        self.Debug("=" * 60)


    def OnData(self, data):
        """
        主数据处理函数
        """
        # 等待指标准备
        if not self.sma_short.IsReady or not self.rsi.IsReady:
            return

        # 检查数据可用性
        if not data.ContainsKey(self.spy) or data[self.spy] is None:
            return

        current_price = data[self.spy].Price

        # 获取持仓状态
        holdings = self.Portfolio[self.spy]

        # ========== 没有持仓时，寻找入场机会 ==========
        if not holdings.Invested:
            self.CheckEntrySignal(current_price)

        # ========== 有持仓时，管理现有持仓 ==========
        else:
            self.ManagePosition(current_price)


    def CheckEntrySignal(self, price):
        """
        检查入场信号

        条件：
        1. 短期均线上穿长期均线（金叉）
        2. RSI 不超买（< 70）
        """
        short_ma = self.sma_short.Current.Value
        long_ma = self.sma_long.Current.Value
        rsi_value = self.rsi.Current.Value

        # 金叉且 RSI 不超买
        if short_ma > long_ma and rsi_value < 70:
            self.EnterLong(price)
            return True
        return False


    def EnterLong(self, price):
        """
        开多仓，演示市价单
        """
        # 计算股数（使用 50% 的资金）
        available_cash = self.Portfolio.Cash * 0.5
        quantity = int(available_cash / price)

        if quantity < 1:
            return

        # ========== 演示 1: 市价单 ==========
        ticket = self.MarketOrder(self.spy, quantity)

        if ticket.Status == OrderStatus.Submitted:
            self.entry_price = price
            self.highest_price = price

            self.Debug(f"\n{'='*60}")
            self.Debug(f"[MARKET ORDER] {self.Time}")
            self.Debug(f"  Symbol: {ticket.Symbol}")
            self.Debug(f"  Quantity: {quantity}")
            self.Debug(f"  Entry Price: ${price:.2f}")
            self.Debug(f"  Order ID: {ticket.OrderId}")
            self.Debug(f"{'='*60}\n")

            # 设置止损止盈
            self.SetStopLossAndTakeProfit(price, quantity)


    def SetStopLossAndTakeProfit(self, entry_price, quantity):
        """
        设置止损和止盈订单

        演示止损单和限价单的使用
        """
        stop_price = entry_price * (1 - self.stop_loss_pct)
        profit_price = entry_price * (1 + self.take_profit_pct)

        # ========== 演示 2: 止损市价单 ==========
        stop_ticket = self.StopMarketOrder(self.spy, -quantity, stop_price)

        # ========== 演示 3: 限价单（止盈）==========
        profit_ticket = self.LimitOrder(self.spy, -quantity, profit_price)

        self.active_tickets['stop'] = stop_ticket
        self.active_tickets['profit'] = profit_ticket

        self.Debug(f"[STOP LOSS & TAKE PROFIT SET]")
        self.Debug(f"  Stop Price: ${stop_price:.2f} ({-self.stop_loss_pct*100}%)")
        self.Debug(f"  Profit Price: ${profit_price:.2f} ({self.take_profit_pct*100}%)")


    def ManagePosition(self, current_price):
        """
        管理现有持仓

        演示订单更新和追踪止损
        """
        # 更新最高价
        if current_price > self.highest_price:
            self.highest_price = current_price

        # ========== 演示 4: 追踪止损 ==========
        self.UpdateTrailingStop(current_price)

        # 检查止盈条件（主动平仓）
        profit_pct = (current_price / self.entry_price - 1)
        if profit_pct >= self.take_profit_pct:
            self.ExitPosition("Take Profit Hit")


    # 未完结（开放）订单的状态集合：没有 OrderStatus.Open，用排除法判断
    OPEN_STATUSES = (OrderStatus.Filled, OrderStatus.Canceled, OrderStatus.Invalid)

    def UpdateTrailingStop(self, current_price):
        """
        更新追踪止损

        演示订单更新功能
        """
        stop_ticket = self.active_tickets.get('stop')
        if not stop_ticket:
            return

        # 只有在订单处于未完结状态时才能更新
        if stop_ticket.Status in self.OPEN_STATUSES:
            return

        # 计算新的追踪止损价
        new_stop_price = self.highest_price * (1 - self.trailing_stop_pct)

        # 获取当前止损价
        current_stop = stop_ticket.Get(OrderField.StopPrice)

        # 只有当新止损价更有利时才更新
        if new_stop_price > current_stop:
            # ========== 演示 5: 订单更新 ==========
            stop_ticket.Update(UpdateOrderFields(
                StopPrice = new_stop_price
            ))

            self.Debug(f"[TRAILING STOP UPDATED]")
            self.Debug(f"  Old Stop: ${current_stop:.2f}")
            self.Debug(f"  New Stop: ${new_stop_price:.2f}")
            self.Debug(f"  Highest: ${self.highest_price:.2f}")


    def ExitPosition(self, reason=""):
        """
        平仓

        演示订单取消和市价平仓
        """
        # ========== 演示 6: 取消未成交订单 ==========
        for name, ticket in self.active_tickets.items():
            if ticket and ticket.Status not in self.OPEN_STATUSES:
                ticket.Cancel()
                self.Debug(f"[ORDER CANCELED] {name} - {ticket.OrderId}")

        # 清空活跃订单
        self.active_tickets = {}

        # 市价平仓
        holdings = self.Portfolio[self.spy]
        if holdings.Invested:
            self.Liquidate(self.spy)
            self.Debug(f"\n{'='*60}")
            self.Debug(f"[EXIT POSITION] {self.Time}")
            self.Debug(f"  Reason: {reason}")
            self.Debug(f"  Exit Price: ${self.Securities[self.spy].Price:.2f}")
            self.Debug(f"  P&L: {(self.Securities[self.spy].Price / self.entry_price - 1) * 100:.2f}%")
            self.Debug(f"{'='*60}\n")

        # 重置状态
        self.entry_price = None
        self.highest_price = None


    # ========== 演示其他订单类型 ==========

    def DemoLimitOrder(self):
        """
        演示限价单的使用
        """
        current_price = self.Securities[self.aapl].Price

        # 限价买入：价格低于当前价 1%
        limit_price = current_price * 0.99

        # ========== 演示 7: 限价单 ==========
        ticket = self.LimitOrder(self.aapl, 10, limit_price)

        self.Debug(f"[LIMIT ORDER PLACED]")
        self.Debug(f"  Symbol: AAPL")
        self.Debug(f"  Limit Price: ${limit_price:.2f}")
        self.Debug(f"  Current Price: ${current_price:.2f}")

        # 如果需要，可以更新限价（UpdateOrderFields 只有默认构造函数，
        # 要先创建对象再给属性赋值，不能传关键字参数）
        # update_fields = UpdateOrderFields()
        # update_fields.LimitPrice = new_price
        # ticket.Update(update_fields)


    def DemoStopLimitOrder(self):
        """
        演示止损限价单的使用

        止损限价单：触发后转为限价单
        """
        current_price = self.Securities[self.aapl].Price

        # 止损价：比当前价低 2%
        stop_price = current_price * 0.98

        # 限价：比止损价低 0.5%（防止大幅滑点）
        limit_price = stop_price * 0.995

        # ========== 演示 8: 止损限价单 ==========
        ticket = self.StopLimitOrder(
            self.aapl,
            -10,              # 卖出 10 股
            stop_price,       # 触发价格
            limit_price       # 限价
        )

        self.Debug(f"[STOP LIMIT ORDER PLACED]")
        self.Debug(f"  Stop Price: ${stop_price:.2f}")
        self.Debug(f"  Limit Price: ${limit_price:.2f}")


    def DemoSetHoldings(self):
        """
        演示 SetHoldings 的使用
        """
        # ========== 演示 9: SetHoldings - 按比例分配 ==========

        # 使用 100% 资金买入 SPY
        self.SetHoldings(self.spy, 1)

        # 使用 50% 资金买入 AAPL
        self.SetHoldings(self.aapl, 0.5)

        # 平均分配多只股票：SetHoldings 单次调用只接受一个 Symbol 和权重，
        # 多标的用循环分别下单
        symbols = [self.spy, self.aapl]
        for symbol in symbols:
            self.SetHoldings(symbol, 1.0 / len(symbols))

        # 自定义比例分配
        target_weights = {
            self.spy: 0.6,   # 60% 给 SPY
            self.aapl: 0.4   # 40% 给 AAPL
        }
        for symbol, weight in target_weights.items():
            self.SetHoldings(symbol, weight)


    # ========== 订单事件处理 ==========

    def OnOrderEvent(self, orderEvent):
        """
        订单事件处理

        这是监控订单状态的主要入口
        """
        status = orderEvent.Status

        # 根据订单状态处理
        if status == OrderStatus.Submitted:
            self.OnOrderSubmitted(orderEvent)

        elif status == OrderStatus.PartiallyFilled:
            self.OnOrderPartiallyFilled(orderEvent)

        elif status == OrderStatus.Filled:
            self.OnOrderFilled(orderEvent)

        elif status == OrderStatus.Canceled:
            self.OnOrderCanceled(orderEvent)

        elif status == OrderStatus.Invalid:
            self.OnOrderInvalid(orderEvent)


    def OnOrderSubmitted(self, orderEvent):
        """订单已提交"""
        self.Debug(f"[ORDER SUBMITTED] ID: {orderEvent.OrderId}")


    def OnOrderPartiallyFilled(self, orderEvent):
        """订单部分成交"""
        filled = orderEvent.FillQuantity
        remaining = orderEvent.Quantity - filled
        self.Debug(f"[ORDER PARTIAL FILL] Filled: {filled}, Remaining: {remaining}")


    def OnOrderFilled(self, orderEvent):
        """订单完全成交"""
        fill_price = orderEvent.FillPrice
        fill_qty = orderEvent.FillQuantity
        fee = orderEvent.OrderFee

        self.trade_count += 1

        self.Debug(f"\n{'─'*60}")
        self.Debug(f"[ORDER FILLED] #{self.trade_count}")
        self.Debug(f"  Order ID: {orderEvent.OrderId}")
        self.Debug(f"  Symbol: {orderEvent.Symbol}")
        self.Debug(f"  Direction: {'BUY' if orderEvent.Quantity > 0 else 'SELL'}")
        self.Debug(f"  Quantity: {abs(fill_qty)}")
        self.Debug(f"  Fill Price: ${fill_price:.2f}")
        self.Debug(f"  Commission: ${fee.Value.Amount:.2f}")
        self.Debug(f"  Time: {self.Time}")
        self.Debug(f"{'─'*60}\n")

        # 更新活跃订单跟踪
        self.UpdateActiveTickets(orderEvent)


    def OnOrderCanceled(self, orderEvent):
        """订单已取消"""
        self.Debug(f"[ORDER CANCELED] ID: {orderEvent.OrderId}")

        # 从活跃订单中移除
        self.RemoveActiveTicket(orderEvent.OrderId)


    def OnOrderInvalid(self, orderEvent):
        """订单无效"""
        self.Debug(f"[ORDER INVALID] ID: {orderEvent.OrderId}")
        self.Debug(f"  Message: {orderEvent.Message}")


    def UpdateActiveTickets(self, orderEvent):
        """更新活跃订单跟踪"""
        for name, ticket in self.active_tickets.items():
            if ticket and ticket.OrderId == orderEvent.OrderId:
                # 如果是止损或止盈订单被成交，移除它
                if orderEvent.Status in [OrderStatus.Filled, OrderStatus.Canceled]:
                    self.active_tickets[name] = None


    def RemoveActiveTicket(self, order_id):
        """从活跃订单中移除"""
        for name, ticket in list(self.active_tickets.items()):
            if ticket and ticket.OrderId == order_id:
                self.active_tickets[name] = None


    # ========== 其他事件 ==========

    def OnEndOfDay(self, symbol):
        """每日收盘处理"""
        if symbol == self.spy:
            portfolio = self.Portfolio
            holdings = portfolio[self.spy]

            self.Debug(f"\n[EOD {self.Time.date()}]")
            self.Debug(f"  Portfolio Value: ${portfolio.TotalPortfolioValue:,.2f}")
            self.Debug(f"  Cash: ${portfolio.Cash:,.2f}")

            if holdings.Invested:
                unreal_pnl = holdings.UnrealizedProfit
                unreal_pnl_pct = holdings.UnrealizedProfitPercent * 100
                self.Debug(f"  SPY Position: {holdings.Quantity}")
                self.Debug(f"  Unrealized P&L: ${unreal_pnl:.2f} ({unreal_pnl_pct:.2f}%)")


    def OnEndOfAlgorithm(self):
        """算法结束"""
        self.Debug("\n" + "="*60)
        self.Debug("BACKTEST COMPLETED")
        self.Debug("="*60)
        self.Debug(f"Total Trades: {self.trade_count}")
        self.Debug(f"Final Portfolio Value: ${self.Portfolio.TotalPortfolioValue:,.2f}")
        self.Debug(f"Total Return: {(self.Portfolio.TotalPortfolioValue / self.starting_cash - 1) * 100:.2f}%")
        self.Debug("="*60)


# ========== 辅助类：订单管理工具 ==========

class OrderManager:
    """
    订单管理辅助类

    提供常用的订单管理功能
    """

    def __init__(self, algorithm):
        self.algorithm = algorithm
        self.active_orders = {}
        self.order_history = []

    def PlaceBracketOrder(self, symbol, quantity, stop_loss_pct, take_profit_pct):
        """
        下组合订单（包含止损止盈）

        Args:
            symbol: 证券 Symbol
            quantity: 数量（正数做多，负数做空）
            stop_loss_pct: 止损百分比
            take_profit_pct: 止盈百分比
        """
        current_price = self.algorithm.Securities[symbol].Price

        # 主订单
        entry_ticket = self.algorithm.MarketOrder(symbol, quantity)

        # 计算止损止盈价格
        if quantity > 0:  # 做多
            stop_price = current_price * (1 - stop_loss_pct)
            profit_price = current_price * (1 + take_profit_pct)
            stop_qty = -quantity
            profit_qty = -quantity
        else:  # 做空
            stop_price = current_price * (1 + stop_loss_pct)
            profit_price = current_price * (1 - take_profit_pct)
            stop_qty = -quantity
            profit_qty = -quantity

        # 止损订单
        stop_ticket = self.algorithm.StopMarketOrder(
            symbol, stop_qty, stop_price
        )

        # 止盈订单
        profit_ticket = self.algorithm.LimitOrder(
            symbol, profit_qty, profit_price
        )

        return {
            'entry': entry_ticket,
            'stop': stop_ticket,
            'profit': profit_ticket
        }

    def CancelAllOrders(self, symbol=None):
        """取消所有未成交订单"""
        if symbol:
            self.algorithm.Transactions.CancelOpenOrders(symbol)
        else:
            self.algorithm.Transactions.CancelOpenOrders()

    def GetOpenOrders(self):
        """获取所有未成交订单"""
        return self.algorithm.Transactions.GetOpenOrderTickets()
