本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ╔══════════════════════════════════════════════════════════════╗
// ║ CNPS Universal Bot Template — Pine Script v6 ║
// ║ Instrument: VN30! | SMA 7/50 Cross Trend Following ║
// ║ Version: CNPS 07 3SMA Cross ║
// ║ Recommended timeframe: M15 | Slippage = 3 ║
// ╚══════════════════════════════════════════════════════════════╝
//*The cost to open a position in futures trading is roughly VND 30,000,000 per contract.
//For VN Future Trading, the commission value is set at VND 10,000 per contract traded. Tax is not yet included.
strategy(
title = "CNPS 07 3SMA Cross",
shorttitle = "CNPS 07",
overlay = true,
initial_capital = 100000000,
default_qty_type = strategy.fixed,
default_qty_value = 3,
margin_long = 0,
margin_short = 0,
slippage = 3,
commission_type = strategy.commission.cash_per_contract,
commission_value = 10000,
fill_orders_on_standard_ohlc = true
)
// ════════════════════════════════════════════════════════════════
// SECTION 1: INPUTS
// ════════════════════════════════════════════════════════════════
// ── Indicator settings ──────────────────────────────────────────
fastLen = input.int(
7,
title="Fast SMA Length",
minval=1,
group="Indicator Settings"
)
slowLen = input.int(
50,
title="Slow SMA Length",
minval=1,
group="Indicator Settings"
)
// ── SMA trend filter ────────────────────────────────────────────
useTrendFilter = input.bool(
true,
title="Use SMA Trend Filter?",
group="Trend Filter"
)
smaLen = input.int(
200,
title="SMA Length",
minval=1,
group="Trend Filter"
)
// ── Trade direction ─────────────────────────────────────────────
tradeDir = input.string(
"Both",
title="Trade Direction",
options=["Long", "Short", "Both"],
group="Trade Direction"
)
// ── Stop loss / Take profit ─────────────────────────────────────
slPoints = input.float(
10.0,
title="Stop Loss Points",
minval=0.1,
step=0.5,
group="Stop Loss / Take Profit"
)
useTP = input.bool(
true,
title="Use Take Profit?",
group="Stop Loss / Take Profit"
)
tpPoints = input.float(
20.0,
title="Take Profit Points",
minval=0.1,
step=0.5,
group="Stop Loss / Take Profit"
)
// ── Time filter ─────────────────────────────────────────────────
useTimeFilter = input.bool(
true,
title="Use Time Filter?",
group="Time Filter"
)
startHour = input.int(
9,
title="Start Hour",
minval=0,
maxval=23,
group="Time Filter"
)
startMinute = input.int(
0,
title="Start Minute",
minval=0,
maxval=59,
group="Time Filter"
)
endHour = input.int(
14,
title="End Hour",
minval=0,
maxval=23,
group="Time Filter"
)
endMinute = input.int(
30,
title="End Minute",
minval=0,
maxval=59,
group="Time Filter"
)
// ── Display settings ────────────────────────────────────────────
showSignalShapes = input.bool(
false,
title="Show Signal Arrows?",
group="Display"
)
// ════════════════════════════════════════════════════════════════
// SECTION 2: INDICATORS
// ════════════════════════════════════════════════════════════════
// ── SMA trend filter ────────────────────────────────────────────
smaTrend = ta.sma(close, smaLen)
isBull = smaTrend >= smaTrend[1]
isBear = smaTrend < smaTrend[1]
// ── Main SMA cross indicators ───────────────────────────────────
smaFast = ta.sma(close, fastLen)
smaSlow = ta.sma(close, slowLen)
// ════════════════════════════════════════════════════════════════
// SECTION 3: STRATEGY RATIONALE
// ════════════════════════════════════════════════════════════════
// This strategy uses a fast SMA and a slow SMA to detect trend changes.
//
// The fast SMA reacts more quickly to recent price movement,
// while the slow SMA represents a broader and more stable trend direction.
//
// A Long signal occurs when the fast SMA crosses above the slow SMA.
// This may indicate that short-term momentum is turning upward.
//
// A Short signal occurs when the fast SMA crosses below the slow SMA.
// This may indicate that short-term momentum is turning downward.
//
// However, SMA crossover signals can become noisy in sideways markets.
// For that reason, this strategy can use an additional SMA trend filter.
//
// When the trend filter is enabled,
// Long trades require the trend SMA to be rising,
// and Short trades require the trend SMA to be falling.
//
// This combination is designed to reduce counter-trend entries
// and improve the overall quality of trend-following signals.
// ════════════════════════════════════════════════════════════════
// SECTION 4: SIGNAL LOGIC
// ════════════════════════════════════════════════════════════════
// Signals are confirmed at candle close.
// Orders are executed on the next candle open.
//
// Long signal:
// Fast SMA crosses above Slow SMA.
//
// Short signal:
// Fast SMA crosses below Slow SMA.
rawLong = ta.crossover(smaFast, smaSlow)
rawShort = ta.crossunder(smaFast, smaSlow)
// ── Apply SMA trend filter ──────────────────────────────────────
// When the SMA filter is enabled,
// Long trades require a rising SMA,
// and Short trades require a falling SMA.
longSignal = rawLong and (useTrendFilter ? isBull : true)
shortSignal = rawShort and (useTrendFilter ? isBear : true)
// ── Apply trade direction ───────────────────────────────────────
canLongDir = tradeDir == "Long" or tradeDir == "Both"
canShortDir = tradeDir == "Short" or tradeDir == "Both"
// ════════════════════════════════════════════════════════════════
// SECTION 5: TIME FILTER
// ════════════════════════════════════════════════════════════════
sessionStart = startHour * 60 + startMinute
sessionEnd = endHour * 60 + endMinute
currentMinutes = hour(time) * 60 + minute(time)
inSession = useTimeFilter
? currentMinutes >= sessionStart and currentMinutes < sessionEnd
: true
// Detect the first candle outside the trading session.
sessionJustEnded = useTimeFilter and not inSession and inSession[1]
// ════════════════════════════════════════════════════════════════
// SECTION 6: ENTRY / EXIT / REVERSE
// ════════════════════════════════════════════════════════════════
// ── Detect SMA trend filter reversals ───────────────────────────
smaFlipBear = useTrendFilter and isBear and isBull[1]
smaFlipBull = useTrendFilter and isBull and isBear[1]
// ── Close Long position when the SMA trend filter turns bearish ─
if smaFlipBear and strategy.position_size > 0
strategy.close(
"Long",
comment="SMA Reversal"
)
// ── Close Short position when the SMA trend filter turns bullish ─
if smaFlipBull and strategy.position_size < 0
strategy.close(
"Short",
comment="SMA Reversal"
)
// ── Close all positions after the trading session ends ──────────
if sessionJustEnded and strategy.position_size != 0
strategy.close_all(comment="Session End")
// ── Entry conditions ────────────────────────────────────────────
canLong = longSignal and inSession and canLongDir
canShort = shortSignal and inSession and canShortDir
// ── Stop loss and take profit levels ────────────────────────────
longSL = strategy.position_avg_price - slPoints
longTP = strategy.position_avg_price + tpPoints
shortSL = strategy.position_avg_price + slPoints
shortTP = strategy.position_avg_price - tpPoints
// ── Entries / reversals ─────────────────────────────────────────
// When a valid Long signal appears, the strategy opens a Long position.
// When a valid Short signal appears, the strategy opens a Short position.
// If an opposite position already exists, strategy.entry handles the reversal.
if canLong
strategy.entry("Long", strategy.long)
if canShort
strategy.entry("Short", strategy.short)
// ── Stop loss / take profit exits ───────────────────────────────
// Stop Loss is calculated from the average entry price.
// Take Profit is used only when the Use Take Profit option is enabled.
// All positions are also closed after the trading session ends.
if strategy.position_size > 0
strategy.exit(
"Exit Long",
"Long",
stop=longSL,
limit=useTP ? longTP : na
)
if strategy.position_size < 0
strategy.exit(
"Exit Short",
"Short",
stop=shortSL,
limit=useTP ? shortTP : na
)
// ════════════════════════════════════════════════════════════════
// SECTION 7: PLOTTING
// ════════════════════════════════════════════════════════════════
// ── SMA trend filter plot ───────────────────────────────────────
plot(
useTrendFilter ? smaTrend : na,
title="SMA Trend Filter",
color=isBull ? color.new(color.green, 40) : color.new(color.red, 40),
linewidth=2
)
// ── Fast and slow SMA plots ─────────────────────────────────────
plot(
smaFast,
title="Fast SMA",
color=color.new(color.blue, 0),
linewidth=1
)
plot(
smaSlow,
title="Slow SMA",
color=color.new(color.orange, 0),
linewidth=1
)
// ── Stop loss / take profit plots ───────────────────────────────
isLong = strategy.position_size > 0
isShort = strategy.position_size < 0
plot(
isLong ? longSL : na,
title="Long Stop Loss",
color=color.red,
style=plot.style_linebr,
linewidth=1
)
plot(
isShort ? shortSL : na,
title="Short Stop Loss",
color=color.red,
style=plot.style_linebr,
linewidth=1
)
plot(
isLong and useTP ? longTP : na,
title="Long Take Profit",
color=color.green,
style=plot.style_linebr,
linewidth=1
)
plot(
isShort and useTP ? shortTP : na,
title="Short Take Profit",
color=color.green,
style=plot.style_linebr,
linewidth=1
)
// ── Entry signal arrows ─────────────────────────────────────────
longEntryShape = showSignalShapes and canLong and strategy.position_size <= 0
shortEntryShape = showSignalShapes and canShort and strategy.position_size >= 0
plotshape(
longEntryShape,
title="Long Signal",
location=location.belowbar,
color=color.new(color.green, 0),
style=shape.triangleup,
size=size.small
)
plotshape(
shortEntryShape,
title="Short Signal",
location=location.abovebar,
color=color.new(color.red, 0),
style=shape.triangledown,
size=size.small
)
// ── Background outside the trading session ──────────────────────
bgcolor(
useTimeFilter and not inSession ? color.new(color.gray, 90) : na,
title="Outside Trading Session"
)