import ccxt

# 使用您的配置
CONFIG = {
    'apiKey': 'rFdbMs40biKImtwGnQ',
    'secret': 'JOuEiGT1uCX9l2qbn9uZuZrVFraAZAA59mqY',
    'verbose': False,
    'enableRateLimit': True,
}

def place_contract_market_order(symbol, side, amount, position_side=None, leverage=10):
    """
    在Bybit合约市场下市价单
    
    Args:
        symbol: 交易对，例如 'BTC/USDT:USDT'
        side: 方向 'buy' 或 'sell'
        amount: 合约数量
        position_side: 持仓方向 'long' 或 'short'，None为自动判断
        leverage: 杠杆倍数
    """
    try:
        # 创建交易所实例
        exchange = ccxt.bybit({
            'apiKey': CONFIG['apiKey'],
            'secret': CONFIG['secret'],
            'sandbox': False,  # 使用实盘，测试网改为 True
            'verbose': CONFIG['verbose'],
            'enableRateLimit': CONFIG['enableRateLimit'],
            'options': {
                'defaultType': 'swap',  # 使用合约交易
            }
        })
        exchange.enable_demo_trading(True)  # 模拟交易
        
        # 设置杠杆
        exchange.set_leverage(leverage, symbol)
        
        # 下市价单
        params = {}
        if position_side:
            params['positionSide'] = position_side
            
        order = exchange.create_order(
            symbol=symbol,
            type='market',
            side=side,
            amount=amount,
            params=params
        )
        
        print("合约市价单创建成功!")
        print(f"订单ID: {order['id']}")
        print(f"交易对: {order['symbol']}")
        print(f"方向: {order['side']}")
        print(f"数量: {order['amount']}")
        print(f"状态: {order['status']}")
        
        return order
        
    except Exception as e:
        print(f"合约下单失败: {e}")
        return None

def place_contract_market_order_with_cost(symbol, side, cost, leverage=10):
    """
    按金额下合约市价单
    
    Args:
        symbol: 交易对
        side: 方向
        cost: 投入金额(USDT)
        leverage: 杠杆倍数
    """
    try:
        exchange = ccxt.bybit({
            'apiKey': CONFIG['apiKey'],
            'secret': CONFIG['secret'],
            'sandbox': False,
            'options': {'defaultType': 'swap'}
        })
        
        # 获取当前价格
        ticker = exchange.fetch_ticker(symbol)
        current_price = ticker['last']
        
        # 计算合约数量
        amount = cost * leverage / current_price
        
        return place_contract_market_order(symbol, side, amount, leverage=leverage)
        
    except Exception as e:
        print(f"按金额下单失败: {e}")
        return None

# 使用示例
if __name__ == "__main__":
    # 示例1：直接按数量下单
    print("=== 按数量下单 ===")
    symbol = 'BTC/USDT:USDT'  # 永续合约
    side = 'buy'  # 开多单
    amount = 0.01  # 合约数量
    
    order_result = place_contract_market_order(symbol, side, amount, leverage=20)
    
    # 示例2：按金额下单
    print("\n=== 按金额下单 ===")
    cost = 100  # 投入100 USDT
    order_result2 = place_contract_market_order_with_cost(symbol, 'sell', cost, leverage=10)
    
    # 示例3：指定持仓方向
    print("\n=== 指定持仓方向下单 ===")
    order_result3 = place_contract_market_order(
        symbol='ETH/USDT:USDT',
        side='buy',
        amount=0.1,
        position_side='long',  # 明确开多仓
        leverage=15
    )