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

基于PineScript实现随交易结果动态调整订单规模的技术需求

PineScript 实现基于上笔交易盈亏的订单规模动态调整

以下是符合需求的完整PineScript代码,包含动态调整订单规模的逻辑,且设置pyramiding=0禁止加仓:

//@version=5
strategy("盈亏联动订单规模策略", overlay=true, pyramiding=0, default_qty_type=strategy.cash, default_qty_value=10000)

// 输入参数
adjust_pct = input.float("盈亏调整百分比", defval=10.0, minval=1.0, maxval=50.0, tooltip="盈利时增加该百分比,亏损时减少该百分比")
initial_capital = input.int("初始订单规模(美元)", defval=10000, minval=1000)

// 初始化跟踪变量:当前订单规模相对于初始值的乘数,初始为1(100%)
var float current_multiplier = 1.0

// 简单入场条件:EMA金叉/死叉(可替换为你自己的策略逻辑)
ema_short = ta.ema(close, 10)
ema_long = ta.ema(close, 20)
long_condition = ta.crossover(ema_short, ema_long)
short_condition = ta.crossunder(ema_short, ema_long)

// 当交易平仓时,更新订单规模乘数(严格按初始值累计调整)
var int profit_streak = 0
var int loss_streak = 0

if strategy.closedtrades > strategy.closedtrades[1]
    last_trade_profit = strategy.closedtrades.profit(strategy.closedtrades - 1)
    if last_trade_profit > 0
        profit_streak += 1
        loss_streak := 0
    else if last_trade_profit < 0
        loss_streak += 1
        profit_streak := 0
    // 计算乘数:初始1 + 盈利连增比例 - 亏损连减比例,最低保留10%初始规模
    current_multiplier := math.max(1 + (profit_streak * adjust_pct / 100) - (loss_streak * adjust_pct / 100), 0.1)

// 计算当前订单规模(美元)
current_order_size = initial_capital * current_multiplier

// 下单逻辑:根据条件开仓,使用计算后的订单规模
if long_condition
    strategy.entry("Long", strategy.long, qty=current_order_size / close)
if short_condition
    strategy.entry("Short", strategy.short, qty=current_order_size / close)

// 输出当前乘数和订单规模到图表
var label status_label = label.new(bar_index, high, "", color=color.blue, textcolor=color.white, style=label.style_label_down)
label.set_text(status_label, str.format("当前乘数: %.2f\n订单规模: $%.0f", current_multiplier, current_order_size))
label.set_xy(status_label, bar_index, high)

关键逻辑说明

  • 订单规模调整规则:
    • 用profit_streak和loss_streak分别跟踪连续盈利/亏损次数
    • 乘数直接基于初始值计算:1 + 连续盈利次数×调整百分比 - 连续亏损次数×调整百分比,完全匹配你给出的例子(连续3次10%亏损后乘数为0.7,订单规模7000美元)
    • 加入math.max(..., 0.1)保护,避免订单规模过低导致无效交易
  • 交易控制:
    • 设置pyramiding=0确保同一时间仅持有一单,无加仓行为
    • 通过current_order_size / close将美元规模转换为合约数,适配不同价格的交易标的
  • 可视化辅助:图表上实时显示当前乘数和订单规模,方便直观跟踪调整效果

自定义修改提示

  • 入场逻辑:可以把代码中的EMA金叉/死叉替换为你自己的交易信号
  • 调整百分比:通过输入框直接修改adjust_pct参数,无需改动代码
  • 规模下限:修改math.max中的0.1值,可调整允许的最小订单规模比例

内容的提问来源于stack exchange,提问作者Lucas Baggio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:45:33