本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ============================================================================
// [] ## PyneSys
// [] [] ## ##
// [] [] [] ## ## ##
// [] [] [] [] ## ## ## ##
// [] [] [] [] [] ## ## ## ## ##
// || ||
// ============================================================================
// MACD + 200 EMA + Support/Resistance
// © 2026 PyneSys LLC. Licensed under MPL-2.0: https://mozilla.org/MPL/2.0/
//
// A trend-following pullback strategy. Longs are taken only above the 200 EMA,
// after price has tested a support level, when the MACD line crosses up
// through its signal line below the zero line. Shorts are the mirror image.
// The stop sits at the 200 EMA and the target is 1.5 times the risk. The idea
// comes from TradingLab's video; this code is our own. The support and
// resistance levels come from the AutoSRZones library.
//
// How we read the rules
// - The video says "200 day moving average" but adds an exponential moving
// average on the chart's own timeframe; we follow the chart.
// - "Cross below the zero line": the MACD line is below zero on the bar of
// the cross (above zero for a short).
// - "Once the price hits the support, wait for the cross": the support test
// must happen on or after the previous opposite MACD cross.
// - A "key" level is one the library considers significant: its peak stood
// out by at least the minimum prominence, measured in ATR.
// - Entry at the next bar's open. Stop at the 200 EMA's value on the signal
// bar; target 1.5 times the distance from the actual entry to that stop.
// One position at a time, and no new entry on the bar a trade closed on.
//
// Our additions (off by default)
// - The two-filter version from the middle of the video (no S/R test), a
// fixed test window in bars, and a stop buffer beyond the EMA in ATR.
//
// Before you test it
// The video uses 15-minute crypto charts. Commission and slippage are zero,
// so markets can be compared before costs. Set your own in Properties before
// you judge the results. Turn on "On order fill" (Properties, Script
// execution) to place the target from the real entry on the entry bar itself;
// section 6 explains why it is off by default.
// ============================================================================
// Reading guide: sections 1-5 build the default strategy from top to bottom.
// Section 6 places the orders, section 7 draws the chart and the research
// diagnostics.
strategy("MACD + 200 EMA + Support/Resistance [PyneSys]", shorttitle="MACD200SR", overlay=true,
initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10,
commission_value=0, slippage=0, pyramiding=0)
import PyneSys/AutoSRZones/1 as sr
// ---------------------------------------------------------------------------
// 1. Inputs
// ---------------------------------------------------------------------------
// The defaults follow the video: MACD 12/26/9, a 200 EMA, a 1.5 reward ratio.
// The support/resistance settings are the AutoSRZones library defaults.
int macdFast = input.int(12, "MACD fast length", minval=1, group="MACD")
int macdSlow = input.int(26, "MACD slow length", minval=1, group="MACD")
int macdSignal = input.int(9, "MACD signal length", minval=1, group="MACD")
int trendLength = input.int(200, "Trend EMA length", minval=1, group="Trend")
bool useSupportResistance = input.bool(true, "Require a support/resistance test", group="Support/resistance")
string testWindow = input.string("Since the previous cross", "Test window", options=["Since the previous cross", "Last N bars"], group="Support/resistance", tooltip="When the level test must have happened: after the previous opposite MACD cross, or within the last N bars. The signal bar counts in both.")
int testBars = input.int(10, "N bars", minval=1, group="Support/resistance")
float minProminenceAtr = input.float(10.0, "Minimum prominence (ATR)", minval=0, step=1, group="Support/resistance", tooltip="How far price must move away from a peak on both sides for the peak to start a level. Higher means fewer, more significant levels.")
float toleranceAtr = input.float(1.0, "Tolerance band (ATR)", minval=0.05, step=0.05, group="Support/resistance", tooltip="How close price must come to a level to count as a test of it.")
float stopBufferAtr = input.float(0.0, "Stop beyond the EMA (ATR 14)", minval=0, step=0.25, group="Risk", tooltip="0 puts the stop exactly at the 200 EMA's value on the signal bar.")
float rewardRatio = input.float(1.5, "Reward-to-risk ratio", minval=0.1, step=0.1, group="Risk")
string tradeDirection = input.string("Both", "Trade direction", options=["Both", "Long only", "Short only"], group="Risk")
// ---------------------------------------------------------------------------
// 2. Indicators
// ---------------------------------------------------------------------------
// All indicators run on every bar, so their history never has gaps.
[macdLine, signalLine, histogram] = ta.macd(close, macdFast, macdSlow, macdSignal)
float trendEma = ta.ema(close, trendLength)
float atr14 = ta.atr(14)
// ---------------------------------------------------------------------------
// 3. Trend: the 200 EMA
// ---------------------------------------------------------------------------
// Above the EMA the market counts as an uptrend, below it as a downtrend.
bool upTrend = close > trendEma
bool downTrend = close < trendEma
// ---------------------------------------------------------------------------
// 4. Support and resistance tests
// ---------------------------------------------------------------------------
// The library stores every significant turning point and forms levels from
// them. A support test is a bar that reaches down into a level's tolerance
// band and closes above the level; a resistance test is the mirror image.
[srLevels, srTolerance] = sr.levels(4.0, minProminenceAtr, 2.0, toleranceAtr)
bool supportTest = sr.atSupport(srLevels, srTolerance)
bool resistanceTest = sr.atResistance(srLevels, srTolerance)
bool bullCross = ta.crossover(macdLine, signalLine)
bool bearCross = ta.crossunder(macdLine, signalLine)
// "Since the previous cross": a bearish cross starts a new pullback, so it
// clears the memory of support tests; every support test after it is
// remembered until the next bullish cross uses it. Resistance works the
// other way round.
var bool supportSinceCross = false
var bool resistanceSinceCross = false
if bearCross
supportSinceCross := false
if bullCross
resistanceSinceCross := false
supportSinceCross := supportSinceCross or supportTest
resistanceSinceCross := resistanceSinceCross or resistanceTest
// "Last N bars": a test on this bar or on one of the N - 1 bars before it.
int barsSinceSupport = ta.barssince(supportTest)
int barsSinceResistance = ta.barssince(resistanceTest)
bool supportRecent = not na(barsSinceSupport) and barsSinceSupport < testBars
bool resistanceRecent = not na(barsSinceResistance) and barsSinceResistance < testBars
bool supportGate = testWindow == "Since the previous cross" ? supportSinceCross : supportRecent
bool resistanceGate = testWindow == "Since the previous cross" ? resistanceSinceCross : resistanceRecent
// ---------------------------------------------------------------------------
// 5. The setup: MACD cross on the far side of zero, with the trend
// ---------------------------------------------------------------------------
// A long needs the MACD line to cross up through the signal line while it is
// still below zero: momentum turns up after a pullback inside an uptrend.
bool longSetup = bullCross and macdLine < 0 and upTrend
bool shortSetup = bearCross and macdLine > 0 and downTrend
bool longSignal = longSetup and (not useSupportResistance or supportGate) and tradeDirection != "Short only"
bool shortSignal = shortSetup and (not useSupportResistance or resistanceGate) and tradeDirection != "Long only"
// ---------------------------------------------------------------------------
// 6. Orders
// ---------------------------------------------------------------------------
// The entry is a market order on the signal bar's close, so it fills at the
// next bar's open. The stop is fixed at the EMA's value on the signal bar and
// goes out with the entry. The target depends on the real entry price, which
// is only known once the order fills. Until then the exit uses the signal
// bar's close as the expected entry. Once the fill is known, the target is
// measured from the real entry: at the entry bar's close by default, or right
// after the fill with "On order fill", still inside the entry bar.
// "On order fill" is off by default because TradingView marks every strategy
// that uses it with a lookahead warning: on historical bars, the extra run
// after a fill sees the bar's final high, low and close. In that extra run
// this script's orders depend only on the fill price and the stop, never on
// the bar's later prices.
// No entry is taken on the bar a trade closed on. With "On order fill", the
// script also runs right after an exit fills, and an entry placed then would
// fill in the middle of the bar. The rule applies in both modes, so the next
// signal comes from the next bar either way.
var float stopLevel = na
var float targetLevel = na
bool flat = strategy.position_size == 0
bool exitedThisBar = strategy.closedtrades > strategy.closedtrades[1]
bool canEnter = flat and not exitedThisBar
if canEnter and longSignal
stopLevel := trendEma - stopBufferAtr * atr14
targetLevel := close + rewardRatio * (close - stopLevel)
strategy.entry("Long", strategy.long)
strategy.exit("Long exit", "Long", stop=stopLevel, limit=targetLevel)
else if canEnter and shortSignal
stopLevel := trendEma + stopBufferAtr * atr14
targetLevel := close - rewardRatio * (stopLevel - close)
strategy.entry("Short", strategy.short)
strategy.exit("Short exit", "Short", stop=stopLevel, limit=targetLevel)
// Once the entry has filled: risk = distance from the real entry to the stop,
// target = entry + 1.5 x risk. If the open already gapped past the stop, the
// stop order has closed the trade at that open and there is nothing to adjust.
if strategy.position_size != 0 and strategy.position_size[1] == 0
float entryPrice = strategy.position_avg_price
bool isLong = strategy.position_size > 0
float risk = isLong ? entryPrice - stopLevel : stopLevel - entryPrice
if risk > 0
targetLevel := isLong ? entryPrice + rewardRatio * risk : entryPrice - rewardRatio * risk
strategy.exit(isLong ? "Long exit" : "Short exit", isLong ? "Long" : "Short", stop=stopLevel, limit=targetLevel)
// ---------------------------------------------------------------------------
// 7. Chart and research diagnostics
// ---------------------------------------------------------------------------
bool inTrade = strategy.position_size != 0
plot(trendEma, "Trend EMA", color=color.new(color.orange, 0), linewidth=2)
plot(sr.supportBelow(srLevels), "Nearest support", color=color.new(color.green, 30), style=plot.style_linebr)
plot(sr.resistanceAbove(srLevels), "Nearest resistance", color=color.new(color.red, 30), style=plot.style_linebr)
plot(inTrade ? stopLevel : na, "Stop", color=color.new(color.red, 0), style=plot.style_linebr)
plot(inTrade ? targetLevel : na, "Target", color=color.new(color.green, 0), style=plot.style_linebr)
plotshape(longSignal and canEnter, "Long signal", shape.triangleup, location.belowbar, color.new(color.green, 0))
plotshape(shortSignal and canEnter, "Short signal", shape.triangledown, location.abovebar, color.new(color.red, 0))
plot((longSignal or shortSignal) and canEnter ? stopLevel : na, "Signal stop", display=display.data_window)
plot(longSetup ? 1 : shortSetup ? -1 : 0, "Setup", display=display.data_window)
plot(supportTest ? 1 : resistanceTest ? -1 : 0, "Level test", display=display.data_window)
plot(macdLine, "MACD", display=display.data_window)
plot(signalLine, "MACD signal", display=display.data_window)
plot(strategy.position_size, "Position", display=display.data_window)