首页 > 解决方案 > Pine 脚本:成交量百分比变化和 TP/SL 退出无法正常工作

问题描述

目标 我正在尝试创建一个脚本,当用户定义的交易量百分比与 24 小时交易量相比增加时,它会打开一个头寸,并使用用户定义的 TP/SL 关闭该头寸。

示例 如果当前蜡烛的交易量与过去 24 小时的交易量相比增加了 3%,那么它将开仓并以 2% 的追踪利润或 -4% 的止损平仓。

问题 它打开了一个多头头寸,但由于某种原因它没有在 TP/SL 处关闭该头寸,因此它没有打开其他头寸。

单击此处查看我得到的输出

请帮忙!!!

代码

//@version=3
//study("Intra-bar Volume", overlay=false)
strategy("Volume check", overlay=true)

//Input Time Frame and Bars (288 bars for 24hrs in 5mins time frame)
lower_tf = input("5", title='Lower Timeframe to Assess')
bars_in_tf = input(288, title='Bars of lower Timeframe')-1 // -1 because we count from zero in the loop

//Stoploss and Take Profit inputs
sl_inp = input(2.0, title='Stop Loss %', type=float)/100
tp_inp = input(4.0, title='Take Profit %', type=float)/100

//Backtesting Date Range 
//From Date Inputs
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 9, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2019, title = "From Year", minval = 1970)

//To Date Inputs
toDay = input(defval = 29, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 9, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2019, title = "To Year", minval = 1970)

//Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate

//Calculating 24hrs Volume
buying_volume(range)=>
    vol = na
    for i = 0 to range
        if open[i] < close[i]
            vol := na(vol) ? volume[i] : vol + volume[i]
    vol

lower_buy_vol =  security(tickerid, lower_tf, buying_volume(bars_in_tf))

//Calculating Percentage Change wrt 24hrs Volume
volbuy = (volume/lower_buy_vol)

//Long Entry if Buy Volume is more than 3%
longEntry = volbuy >= 0.03

//SL and TP 
stop_level = strategy.position_avg_price * (1 - sl_inp)
take_level = strategy.position_avg_price * (1 + tp_inp)

//Submit orders
strategy.entry("Long Entry", true, when=longEntry and time_cond)
strategy.exit("Stop Loss/TP","Simple SMA Entry", stop=stop_level, limit=take_level)

//Plotting the SL/TP line
plot(stop_level, color=red, style=linebr, linewidth=2)
plot(take_level, color=green, style=linebr, linewidth=2)

标签: pine-script

解决方案


那是因为您设置了错误的要退出位置的 id:

strategy.exit("Stop Loss/TP","Simple SMA Entry", stop=stop_level, limit=take_level)

所以你有一个条目 id Simple SMA Entry,但条目是用 id 制作的Long Entry。在退出中更改它以更正一个,它将起作用:

strategy.exit("Stop Loss/TP","Long Entry", stop=stop_level, limit=take_level)

推荐阅读