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

如何设置卖出价格=买入价格×1.01?量化策略编写求助

量化交易策略:实现1%止盈卖出逻辑

我正在编写一套量化交易策略,希望设置卖出价格为买入价格的1.01倍(即1%止盈),例如买入价为50时,卖出价为50×1.01=50.5。以下是我目前的代码:

strategy("test",pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

rsi = rsi(close,6)  
ilong = input(23, title="period")
isig = input(3, title="signal")

bcwsma(s,l,m) => 
    _s = s
    _l = l
    _m = m
    _bcwsma = (_m*_s+(_l-_m)*nz(_bcwsma[1]))/_l
    _bcwsma

c = close
h = highest(high, ilong)
l = lowest(low,ilong)
RSV = 100*((c-l)/(h-l))
pK = bcwsma(RSV, isig, 1)
pD = bcwsma(pK, isig, 1)
pJ = 3 * pK-2 * pD

[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)

plot(pK, color=orange)
plot(pD, color=lime)
plot(pJ, color=fuchsia)

bgcolor(pJ>pD? green : red, transp=70)

entry_price = strategy.opentrades.entry_price(strategy.opentrades-1)
sell_price = entry_price * 1.01
shortCondition = sell_price
longCondition = crossover(pJ,pD) and macdLine > -0.5

strategy.entry("Buy", strategy.long, when=longCondition)
strategy.close("Buy", when=shortCondition)

问题分析

原代码的核心错误在于shortCondition = sell_price:strategy.close的when参数需要接收布尔条件(比如价格是否达到目标价),而不是直接传入价格数值。此外,当没有持仓时,strategy.opentrades-1会返回-1,导致entry_price取到空值,需要做空值处理。

修改后的代码

strategy("test",pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

rsi = rsi(close,6)  
ilong = input(23, title="period")
isig = input(3, title="signal")

bcwsma(s,l,m) => 
    _s = s
    _l = l
    _m = m
    _bcwsma = (_m*_s+(_l-_m)*nz(_bcwsma[1]))/_l
    _bcwsma

c = close
h = highest(high, ilong)
l = lowest(low,ilong)
RSV = 100*((c-l)/(h-l))
pK = bcwsma(RSV, isig, 1)
pD = bcwsma(pK, isig, 1)
pJ = 3 * pK-2 * pD

[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)

plot(pK, color=orange)
plot(pD, color=lime)
plot(pJ, color=fuchsia)

bgcolor(pJ>pD? green : red, transp=70)

// 仅当有持仓时获取入场价,空值用0填充
has_position = strategy.opentrades > 0
entry_price = has_position ? strategy.opentrades.entry_price(strategy.opentrades-1) : 0
sell_price = entry_price * 1.01

// 止盈条件:当前收盘价达到或超过目标卖出价,且有持仓
take_profit_condition = has_position and close >= sell_price
longCondition = crossover(pJ,pD) and macdLine > -0.5

strategy.entry("Buy", strategy.long, when=longCondition)
strategy.close("Buy", when=take_profit_condition)

关键修改说明

  1. 持仓状态判断:新增has_position变量,判断当前是否有持仓,避免无持仓时获取无效的入场价。
  2. 空值处理:用三元运算符给entry_price设置默认值0,防止计算sell_price时出现错误。
  3. 止盈条件修正:将take_profit_condition设置为has_position and close >= sell_price,满足布尔条件要求,确保价格达到止盈价时触发卖出。
  4. 变量命名优化:把shortCondition改为take_profit_condition,语义更清晰,避免和空头策略混淆。

内容的提问来源于stack exchange,提问作者michael tsai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:45:57