首页 > 解决方案 > (TradingView) Pine 脚本 - 为回测设置止损、追踪止损和获利者

问题描述

我一直在尝试让 pine 脚本正常工作,但我有点卡住了。

我想测试的策略是:如果RSI低于60,价格在200SMA以上,MACD刚刚发生交叉;买。实施 3% 的止损。如果利润为 3%,则卖出一半股票,并对剩余一半实施 2% 的追踪止损。

有任何想法吗?我无法让交易平仓正常工作。

//@version=4
strategy('MACDTester')

// Generate MACD Values
[macd_line, signal_line, hist_line] = macd(close, 12, 26, 9)
plot(hist_line, color=color.red, style=plot.style_histogram)
plot(macd_line, color=color.blue)
plot(signal_line, color=color.orange)

// Generate RSI Values
rsiSource = input(title="RSI Source", type=input.source, defval=close)
rsiLength = input(title="RSI Length", type=input.integer, defval=14)
rsi_value = rsi(rsiSource, rsiLength)

is_bull_trend = close > ema(close, 200) 

buy_signal = is_bull_trend and crossover(macd_line, signal_line) and rsi_value <= 60

// Plot Buy Signals
plotshape(series=buy_signal, title="Long", style=shape.arrowup, location=location.bottom, color=color.green, size=size.small)

profit_exit_price  = strategy.position_avg_price * (1 + .03)
stop_loss_price  = strategy.position_avg_price * (1 - .05)

strategy.entry("buy", strategy.long, 1000.0, when=buy_signal)

if (strategy.position_size > 0)
    strategy.exit("Stop Loss/TP","Simple SMA Entry", stop=stop_loss_price, limit=profit_exit_price)

// Implement 3% Profit Taking on half the shares
// Trailing Stop Loss for the remaining shares
// if price is at or below stop_loss_price then sell

标签: pine-scriptstocktradingscript

解决方案


推荐阅读