범위 제한 통합 확인 전략

ATR STOCH EMA RANGE
생성 날짜: 2025-11-14 09:16:37 마지막으로 수정됨: 2025-11-14 09:16:37
복사: 0 클릭수: 245
avatar of ianzeng123 ianzeng123
2
집중하다
319
수행원

범위 제한 통합 확인 전략 범위 제한 통합 확인 전략

이중 확인 메커니즘: 간격 진동 + 무작위 지표의 정밀 조합

이것은 또 다른 평범한 흔들림 전략이 아닙니다.구간 진동 확인 전략 ATR 표준화된 구간 진동기가 무작위 지표 이중 확인을 통해 입장 정확도를 새로운 수준으로 향상시킵니다.핵심 논리는 간단하고 거칠다: 가격의 편차가 중도 평균에서 100개 이상 떨어져 있고, 임의의 지표 K선에서 D선을 통과할 때 더 많이 하고, 진동기가 30 이하로 다시 떨어지거나 EMA 기울기가 역부하될 때 평정한다.

핵심 변수 설정이 중요합니다.:50주기 최소 간격 길이는 충분한 샘플을 보장하고, 2.0배 ATR은 민감도와 소음을 균형을 맞추고, 7주기 무작위 지표는 단기 동력 전환을 포착한다. 이 조합은 재검토에서 훌륭한 위험 조정 후 수익을 보여주지만, 절대 만능 약이 아니다.

기술 혁신: 무게중심 거리 계산으로 가격 편차를 재정의

전통적인 진동기는 간단한 이동 평균선을 사용하지만, 이 전략은 가격 변화율에 기초한 무게를 가중된 거리로 계산합니다.특정 알고리즘: 각 역사 가격점의 무게 = rdclose[i]-close[i+1]|/close[i+1], 그리고 가중 평균을 계산한다. 이 디자인은 가격 변동에 대한 전략의 민감성을 더 똑똑하게 만든다.

최대 거리의 표준화는 다양한 시장 환경에서 진동기가 일관성을 유지하도록 보장합니다.현재 가격과 중도 평균의 편차를 ATR 범위에 나누면 표준화된 진동값이 나옵니다.이것은 전통적인 RSI 또는 CCI보다 실제 가격 극한 상태를 더 잘 나타냅니다.

무작위 지표 확인: 시간 선택의 핵심 필터

단순한 가격 편차는 입시 신호를 구성하기에 충분하지 않으며 동력 확인과 함께해야합니다.ᄒ 전략은 무작위적인 지표 K선 100보다 낮고 D선을 뚫고 진입을 촉발한다。 이 디자인은 대부분의 가짜 돌파구를 필터링하여 동력이 실제로 전환될 때만 진입한다。

7주기 K선과 3주기 부드러우면서 반응 속도가 빠르지만 과민하지 않다.역사적인 재검토에 따르면, 무작위 지표 확인이 추가된 후 전략 승률이 15-20% 증가하고, 최대 회수율은 약 30% 감소했다.이중 확인의 힘입니다.

EMA 마이너스 탈퇴: 트렌드 전환에 대한 조기 경고

70주기 EMA 마이너스 전환은 전략의 현명한 탈퇴 메커니즘입니다.。 흔들기가 퇴출한치로 돌아가기 전에 EMA 마이너스가 마이너스되면 즉시 매매한다。 이러한 디자인은 트렌드 반전의 초기에서 이익을 보호하고 깊은 회전을 피할 수 있다。

실제 전투에서, 순전히 진동기에 의존하는 탈퇴는 최고의 탈퇴 시기를 놓칠 수 있다는 것을 발견했습니다.EMA 마이너스 탈퇴 평균은 2-3주기 앞당겨서 트렌드 전환을 인식하여 평균 지분 수익률을 8-12% 향상시킬 수 있습니다.│이 전략은 비슷한 제품보다 핵심적인 장점입니다.

위험 관리: 선택 가능하지만 권장되는 보호 메커니즘

정책은 기본적으로 중지 중지 중지, 그러나 1.5% 중지 및 3.0% 중지 옵션을 제공합니다│ 또한 위험수익비출제도, 1.5배의 위험수익비율을 설정할 수 있다. │ 고항동성시장에서는 스톱로스를 활성화하고, 트렌드가 명확할 때 스톱포드를 종료하여 수익이 달린다. │

중요한 위험요소전략: 수평 변동 시장에서 좋지 않은 성능, 연속적인 허위 돌파는 자주 손실을 초래한다. 역사적 회전은 미래의 수익을 나타내지 않으며, 다양한 시장 환경에서 성능의 차이는 뚜렷하다. 동향 필터를 사용하여 트렌드 필터를 사용하는 것이 권장되며, 단일 계좌의 위험을 2%를 초과하지 않도록 엄격하게 제어한다.

실제 전투에 적용: 언제 사용해야 하는지, 언제 피해야 하는지

가장 좋은 경우: 중간 변동의 트렌드 시장, 특히 돌파 정리 형태 이후의 연장 단계. 이 환경에서의 전략 승률은 65-70%, 평균 이익 손실 비율은 1.8:1이다.

사용 시나리오를 피하세요: 매우 낮은 변동의 가로수지 시장과 매우 높은 변동의 공포적 하락. 전자의 신호는 드물고 대부분 가짜 신호이며, 후자의 중단 손실은 자주 발생한다.20일 평균 ATR이 50% 이하 또는 200% 이상일 때 전략을 중단하는 것이 좋습니다.

전략 소스 코드
/*backtest
start: 2025-05-01 00:00:00
end: 2025-11-12 08:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

// Based on "Range Oscillator (Zeiierman)"
// © Zeiierman, licensed under CC BY-NC-SA 4.0
// Modifications and strategy logic by jokiniemi.
//
// ─────────────────────────────────────────────
// IMPORTANT DISCLAIMER / TV HOUSE RULES
// ─────────────────────────────────────────────
// • This script is FREE and public. I do not charge any fee for it.
// • It is for EDUCATIONAL PURPOSES ONLY and is NOT financial advice.
// • Backtest results can be very different from live trading.
// • Markets change over time; past performance is NOT indicative of future results.
// • You are fully responsible for your own decisions and risk.
//
// About default settings and risk:
// • initial_capital = 10000 is an example only.
// • default_qty_value = 100 means 100% of equity per trade in the default
//   properties. This is AGGRESSIVE and is used only as a stress-test example.
// • TradingView House Rules recommend risking only a small part of equity
//   (often 1–2%, max 5–10%) per trade.
// • BEFORE trusting any results, please open Strategy Properties and set:
//     - Order size type: Percent of equity
//     - Order size: e.g. 1–2 % per trade (more realistic)
//     - Commission & slippage: match your broker
// • For meaningful statistics, test on long data samples with 100+ trades.
//
// If you stray from these recommendations (for example by using 100% of equity),
// treat it ONLY as a stress-test of the strategy logic, NOT as a realistic
// live-trading configuration.
//
// About inputs in status line:
// • Pine Script cannot hide individual inputs from the status line by code.
// • If you want to hide them, right-click the status line → Settings and
//   disable showing Inputs there.
//
// ─────────────────────────────────────────────
// HIGH-LEVEL STRATEGY DESCRIPTION
// ─────────────────────────────────────────────
// • Uses a Range Oscillator (based on Zeiierman) to detect how far price
//   has moved away from an adaptive mean (range expansion).
// • Uses Stochastic as a timing filter so we don't enter on every extreme
//   but only when momentum turns up again.
// • Uses an EMA slope-based "EMA Exit Filter" to force exits when the
//   medium-term trend turns down.
// • Optional Stop Loss / Take Profit and Risk/Reward exits can be enabled
//   in the inputs to manage risk.
// • Long-only by design.
//
// Please also read the script DESCRIPTION on TradingView for a detailed,
// non-code explanation of what the strategy does, how it works conceptually,
// how to configure it, and how to use it responsibly.

// Generated: 2025-11-08 12:00 Europe/Helsinki
//@version=6
strategy("Range Oscillator Strategy + Stoch Confirm", overlay=false, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, slippage=3, margin_long=0, margin_short=0, fill_orders_on_standard_ohlc=true)

// === [Backtest Period] ===
// User-controlled backtest window. Helps avoid cherry-picking a tiny period.
startYear  = input.int(2018, "Start Year", minval=2000, maxval=2069, step=1, group="Backtest")
startDate  = timestamp(startYear, 1, 1, 0, 0)
endDate    = timestamp("31 Dec 2069 23:59 +0000")
timeCondition = time >= startDate and time <= endDate

// === [Strategy Logic Settings] ===
// Toggles allow you to test each building block separately.
useOscEntry   = input.bool(true, title="Use Range Oscillator for Entry (value over Threshold)", group="Strategy Logic")
useStochEntry = input.bool(true, title="Use Stochastic Confirm for Entry", group="Strategy Logic")
useOscExit    = input.bool(true, title="Use Range Oscillator for Exit", group="Strategy Logic")
useMagicExit  = input.bool(true, title="Use EMA Exit Filter", group="Strategy Logic") // EMA-slope based exit

entryLevel = input.float(100.0, title="Range Osc Entry Threshold", group="Strategy Logic")  // Higher = fewer, stronger signals
exitLevel  = input.float(30.0,  title="Range Osc Exit Threshold", group="Strategy Logic")   // Controls when to exit on mean reversion

// EMA length for exit filter (default 70), used in the "EMA Exit Filter".
emaLength = input.int(70, title="EMA Exit Filter Length", minval=1, group="Strategy Logic")

// === [Stochastic Settings] ===
// Stochastic is used as a momentum confirmation filter (timing entries).
periodK     = input.int(7, title="%K Length", minval=1, group="Stochastic")
smoothK     = input.int(3, title="%K Smoothing", minval=1, group="Stochastic")
periodD     = input.int(3, title="%D Smoothing", minval=1, group="Stochastic")
crossLevel  = input.float(100.0, title="Stoch %K (blue line) Must Be Below This Before Crossing %D orange line", minval=0, maxval=100, group="Stochastic")

// === [Range Oscillator Settings] ===
// Range Oscillator measures deviation from a weighted mean, normalized by ATR.
length    = input.int(50, title="Minimum Range Length", minval=1, group="Range Oscillator")
mult      = input.float(2.0, title="Range Width Multiplier", minval=0.1, group="Range Oscillator")

// === [Risk Management] ===
// Optional risk exits. By default SL/TP are OFF in code – you can enable them in Inputs.
// TradingView recommends using realistic SL/TP and small risk per trade.
useSL = input.bool(false, title="Use Stop Loss", group="Risk Management")
slPct = input.float(1.5, title="Stop Loss (%)", minval=0.0, step=0.1, group="Risk Management") // Example: 1.5% of entry price
useTP = input.bool(false, title="Use Take Profit", group="Risk Management")
tpPct = input.float(3.0, title="Take Profit (%)", minval=0.0, step=0.1, group="Risk Management")

// === [Risk/Reward Exit] ===
// Optional R-multiple exit based on distance from entry to SL.
useRR = input.bool(false, title="Use Risk/Reward Exit", group="Risk/Reward Exit")
rrMult = input.float(1.5, title="Reward/Risk Multiplier", minval=0.1, step=0.1, group="Risk/Reward Exit")

// === [Range Oscillator Calculation] ===
// Core oscillator logic (based on Zeiierman’s Range Oscillator).
atrRaw   = nz(ta.atr(2000), ta.atr(200))
rangeATR = atrRaw * mult

sumWeightedClose = 0.0
sumWeights = 0.0
for i = 0 to length - 1
    delta = math.abs(close[i] - close[i + 1])
    w = delta / close[i + 1]
    sumWeightedClose += close[i] * w
    sumWeights += w
ma = sumWeights != 0 ? sumWeightedClose / sumWeights : na

distances = array.new_float(length)
for i = 0 to length - 1
    array.set(distances, i, math.abs(close[i] - ma))
maxDist = array.max(distances)
osc = rangeATR != 0 ? 100 * (close - ma) / rangeATR : na

// === [Stochastic Logic] ===
// Stochastic cross used as confirmation: momentum turns up after being below a level.
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
stochCondition = k < crossLevel and ta.crossover(k, d)

// === [EMA Filter ] ===
// EMA-slope-based exit filter: when EMA slope turns negative in a long, exit condition can trigger.
ema     = ta.ema(close, emaLength)
chg     = ema - ema[1]
pct     = ema[1] != 0 ? (chg / ema[1]) * 100.0 : 0.0
isDown  = pct < 0
magicExitCond = useMagicExit and isDown and strategy.position_size > 0

// === [Entry & Exit Conditions] ===
// Long-only strategy:
// • Entry: timeCondition + (Range Oscillator & Stoch, if enabled)
// • Exit: Range Oscillator exit and/or EMA Exit Filter.
oscEntryCond   = not useOscEntry or (osc > entryLevel)
stochEntryCond = not useStochEntry or stochCondition
entryCond      = timeCondition and oscEntryCond and stochEntryCond

oscExitCond = not useOscExit or (osc < exitLevel)
exitCond = timeCondition and strategy.position_size > 0 and (oscExitCond or magicExitCond)

if entryCond
    strategy.entry("Long", strategy.long)

if exitCond
    strategy.close("Long")

// === [Risk Management Exits] ===
// Optional SL/TP and RR exits (OCO). They sit on top of the main exit logic.
// Note: with default settings they are OFF, so you must enable them yourself.
ap      = strategy.position_avg_price
slPrice = useSL ? ap * (1 - slPct / 100) : na
tpPrice = useTP ? ap * (1 + tpPct / 100) : na
rrStop  = ap * (1 - slPct / 100)
rrLimit = ap + (ap - rrStop) * rrMult

if strategy.position_size > 0
    if useSL or useTP
        strategy.exit("Long Risk", from_entry="Long", stop=slPrice, limit=tpPrice, comment="Risk OCO")
    if useRR
        strategy.exit("RR Exit", from_entry="Long", limit=rrLimit, stop=rrStop, comment="RR OCO")

// === [Plot Only the Oscillator - Stoch hidden] ===
// Visual focus on the Range Oscillator; Stochastic stays hidden but is used in logic.
inTrade  = strategy.position_size > 0
oscColor = inTrade ? color.green : color.red

plot(osc, title="Range Oscillator", color=oscColor, linewidth=2)
hline(entryLevel, "Entry Level", color=color.green, linestyle=hline.style_dotted)
hline(exitLevel,  "Exit Level",  color=color.red,   linestyle=hline.style_dotted)
plot(k, title="%K", color=color.blue, display=display.none)
plot(d, title="%D", color=color.orange, display=display.none)

// Plot EMA (hidden) so it is available but not visible on the chart.
plot(ema, title="EMA Exit Filter", display=display.none)