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

Pine Script求助:实现每500美元权益对应1手期货合约交易逻辑

解决Pine Script期货策略仓位配置问题:每500美元权益对应1手合约

需求说明

本人是Pine Script新手,现有一套可正常运行的MACD交叉期货交易策略代码,希望实现每500美元账户权益对应交易1手期货合约的逻辑。需注意不能使用权益百分比或美元金额参数,必须以合约数为单位进行配置。

修改后的完整代码

//@version=5
strategy("MACD Futures", overlay=false, initial_capital = 5000,currency= currency.USD)

//SL&TP Settings
ON_OFF1 = input.bool(false, title="TP_SL ON/OFF",group="Profit Settings")
stopPercent = input.float(defval = 40, step = 1, title = "SL")
takePercent = input.float(defval =40, step = 1, title = "TP")

// Getting inputs
fast_length = input(title="Fast Length", defval=12,group="MACD Settings")
slow_length = input(title="Slow Length", defval=26,group="MACD Settings")
src = input(title="Source", defval=close,group="MACD Settings")
signal_length = input.int(title="Signal Smoothing",  minval = 1, maxval = 50, defval = 9,group="MACD Settings")
sma_source = input.string(title="Oscillator MA Type",  defval="SMA", options=["SMA", "EMA"],group="MACD Settings")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"],group="MACD Settings")

// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal

//Trading Time Settings
ON_OFF = input.bool(true, title="Time Filter ON/OFF",group="Time Settings")
inSession = input.session(title="Time Filter",defval="0830-1300", group = "Time Settings")

//Colored Background
paintBg = input.bool(title="Paint Background?", defval=true,group = "BackGround Highlighter")
timezone = input.session(title="Timezone To Highlight", defval="1600-0830", group = "BackGround Highlighter")

// InSession() determines if a price bar falls inside the specified session
InSession(sess) => na(time(timeframe.period, sess + ":1234567")) == false

// Color the background of each relevant session and/or bar
bgcolor(color=InSession(timezone) and paintBg ? color.new(color.blue, 95) : na, title="Not Insession")

//Date Range Settings
useDateFilter = input.bool(false, title="Filter Date Range of Backtest",group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 Jan 2020"),title="Start Date", group="Backtest Time Period",tooltip="This start date is in the time zone of the exchange where the chart's instrument trades. It doesn't use the time zone of the chart or of your computer.")
backtestEndDate = input.time(timestamp("1 Jan 2025"),title="End Date", group="Backtest Time Period",tooltip="This end date is in the time zone of the exchange where the chart's instrument trades. It doesn't use the time zone of the chart or of your computer.")

inTradeWindow = not useDateFilter or (time >= backtestStartDate and time < backtestEndDate)

Session = not ON_OFF or InSession(inSession)

// Plot colors
col_macd = input(#2962FF, "MACD Line  ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line  ", group="Color Settings", inline="Signal")
col_grow_above = input(#089981, "Above   Grow", group="Histogram", inline="Above")
col_fall_above = input(#089981, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#f23645, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#f23645, "Fall", group="Histogram", inline="Below")
hline(0, "Zero Line", color=color.new(#787B86, 50),linestyle=hline.style_solid)
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(macd, title="MACD", color=col_macd, linewidth =2 )
plot(signal, title="Signal", color=col_signal,linewidth =2)

// 核心仓位计算:每500美元权益对应1手合约
quantity = math.floor(strategy.equity / 500)
// 可选:确保最低交易1手(如果需要权益不足500时也交易1手,取消下面注释)
// quantity = max(1, math.floor(strategy.equity / 500))

//Long Entries
if (ta.crossover(hist, 0)and Session  and inTradeWindow and quantity > 0)
    strategy.entry("Long", strategy.long, qty=quantity, comment="Long")
if (ON_OFF1)
    strategy.exit(id="Long Close",from_entry = "Long",profit=takePercent , loss=stopPercent)

//Short Entries
if (ta.crossunder(hist, 0) and Session  and inTradeWindow and quantity > 0)
    strategy.entry("short", strategy.short, qty=quantity, comment="short" )
if (ON_OFF1)
    strategy.exit(id="Short Close",from_entry = "short",profit=takePercent , loss=stopPercent)

//Close Short Time
closeshort = not Session
if (closeshort )  
    strategy.close(id= "short")

//Close Long Positions time
closelong = not Session
if (closelong )
    strategy.close(id="Long")

关键修改说明

  • 仓位计算逻辑:使用strategy.equity获取当前账户实时权益,除以500后用math.floor()取整数,得到对应可交易的合约数量
  • 仓位参数传递:在strategy.entry()函数中添加qty=quantity参数,将计算出的合约数应用到开仓操作
  • 边界处理:加入quantity > 0的判断,避免权益不足500美元时触发无效开仓;如果需要最低1手交易,可取消注释max(1, ...)的行
  • 符合需求要求:全程未使用权益百分比或固定美元金额参数,完全以合约数为单位动态配置仓位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:45:29