编辑代码

import time
from binance.client import Client
from binance.enums import *

api_key = '***'
api_secret = '***'

client = Client(api_key, api_secret)

symbol = 'BTCUSDT'
quantity = 1   # 每个订单购买的合约数量(币)
distance_pct = 0.01 # 确定买单间的价格间隔的百分比
levelsCount = 5  # 包括初始买入,总共想要挂5个买单

orders_status = {}  # 订单状态跟踪

# 设置杠杆倍数为5倍
client.futures_change_leverage(symbol=symbol, leverage=5)

# 设置为全仓模式
client.futures_change_margin_type(symbol=symbol, marginType='CROSSED')

# 设置为单项持仓模式(单向持仓)
client.futures_change_position_mode(dualSidePosition=False)  

def check_position():
    positions = client.futures_account()['positions']
    for position in positions:
        if position['symbol'] == symbol and float(position['positionAmt']) > 0:
            return True
    return False

def place_orders(initial_price):
    prices = [initial_price * (1 - distance_pct * i) for i in range(levelsCount)]
    target_prices = [price * 1.01 for price in prices]   # 平仓单涨1%止盈

    for i, price in enumerate(prices):
        if price not in orders_status or orders_status[price].get('order_status') in ['FILLED', 'CANCELED']:
            # 下买单
            order = client.futures_create_order(
                symbol=symbol,
                side=SIDE_BUY,
                type=ORDER_TYPE_LIMIT,
                timeInForce=TIME_IN_FORCE_GTC,
                quantity=quantity,
                price=str(price),
                positionSide='LONG'  # 由于设置了单向持仓,此参数明确指示为多头
            )
            print(f"买入单已下:{order}")

            # 下对应的平仓单
            tp_order = client.futures_create_order(
                symbol=symbol,
                side=SIDE_SELL,
                type=ORDER_TYPE_LIMIT,
                timeInForce=TIME_IN_FORCE_GTC,
                quantity=quantity,
                price=str(target_prices[i]),
                positionSide='LONG'  # 由于设置了单向持仓,此参数明确指示为多头
            )
            print(f"止盈单已下:{tp_order}")

            # 记录订单状态
            orders_status[price] = {'buy_order_id': order['orderId'], 'tp_order_id': tp_order['orderId'], 'order_status': 'NEW'}
        else:
            print(f"价格 {price} 的订单已存在或未平仓,跳过此价格级别的订单")

def check_order_status():
    for price, order_info in list(orders_status.items()):
        order_status = client.futures_get_order(symbol=symbol, orderId=order_info['buy_order_id'])['status']
        tp_order_status = client.futures_get_order(symbol=symbol, orderId=order_info['tp_order_id'])['status']
        
        # 更新买单状态
        orders_status[price]['order_status'] = order_status
        
        # 如果平仓单已完成或买单被取消,允许重新在该价格级别买入
        if tp_order_status == 'FILLED' or order_status == 'CANCELED':
            print(f"价格 {price} 的买单或平仓单已完成或取消,可以重新下单")
            del orders_status[price]

if not check_position():
    latest_price = float(client.futures_symbol_ticker(symbol=symbol)['price'])
    place_orders(latest_price)
    
    while True:
        check_order_status()
        time.sleep(400)  # 每400秒检查一次订单状态
else:
    print("已有开仓的多单,不执行买入操作。")