You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

python-binance期货如何设置止盈止损(TP/SL)及自动计算下单数量

实现方案

1. 开仓后添加止盈、止损逻辑

币安合约的止盈(TP)、止损(SL)通过条件市价单实现,需要注意设置reduceOnly=True保证订单仅用于平仓,不会反向开新仓。

核心实现代码(以开多仓位为例)

在市价开仓代码后添加以下逻辑:

import math # 后续计算数量精度需要,提前导入

# 自定义止盈止损比例,可按需修改
tp_rate = 0.01 # 止盈比例1%
sl_rate = 0.005 # 止损比例0.5%

# 计算止盈、止损触发价
tp_price = round(Price * (1 + tp_rate), 4) # 价格精度可根据对应币种调整
sl_price = round(Price * (1 - sl_rate), 4)

# 止盈单
self.client.futures_create_order(
    symbol=symbol,
    side="SELL",
    type="TAKE_PROFIT_MARKET",
    stopPrice=tp_price,
    reduceOnly=True,
    quantity=quantity
)

# 止损单
self.client.futures_create_order(
    symbol=symbol,
    side="SELL",
    type="STOP_MARKET",
    stopPrice=sl_price,
    reduceOnly=True,
    quantity=quantity
)

注意:如果你的账户是双向持仓模式,需要在所有订单参数中额外添加positionSide="LONG"(多单)或positionSide="SHORT"(空单),否则会报错。如果是单向持仓模式无需添加该参数。


2. 兼容任意币种的下单数量正确计算

你原代码的数量计算逻辑完全反向,且没有适配不同币种的数量精度要求,会触发交易所的LOT_SIZE过滤错误。

正确计算逻辑

  1. 理论可开数量公式:可开数量 = (投入稳定币金额 * 杠杆倍数) / 标的当前价格
  2. 调用币安接口获取对应币种的最小下单量、数量步长规则,按照步长对理论数量进行舍入,保证符合交易所要求。

实现代码

先在Main类中添加数量合法性校验方法:

def get_valid_quantity(self, symbol, theoretical_quantity):
    # 获取对应币种的交易规则
    exchange_info = self.client.futures_exchange_info()
    symbol_info = next(s for s in exchange_info["symbols"] if s["symbol"] == symbol)
    # 提取数量精度规则
    lot_size_filter = next(f for f in symbol_info["filters"] if f["filterType"] == "LOT_SIZE")
    step_size = float(lot_size_filter["stepSize"])
    min_qty = float(lot_size_filter["minQty"])
    # 按照步长舍入
    precision = int(round(-math.log(step_size, 10), 0))
    valid_quantity = round(theoretical_quantity // step_size * step_size, precision)
    # 校验最小下单量
    if valid_quantity < min_qty:
        raise ValueError(f"下单数量{valid_quantity}小于{symbol}最小要求{min_qty},请提高投入金额")
    return valid_quantity

替换你原代码中的数量计算逻辑:

price = float(self.client.get_symbol_ticker(symbol=symbol)["price"])
print(price)
# 替换原quantity计算逻辑
theoretical_quantity = (amount * leverage) / price
quantity = self.get_valid_quantity(symbol, theoretical_quantity)
print(quantity)

内容的提问来源于stack exchange,提问作者Doğan Ali ŞAN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 14:33:00