다중 SMA 간격 돌파 및 동적 이익 잠금 양적 거래 전략

SMA
생성 날짜: 2024-12-20 16:28:54 마지막으로 수정됨: 2024-12-20 16:28:54
복사: 0 클릭수: 441
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

다중 SMA 간격 돌파 및 동적 이익 잠금 양적 거래 전략

개요

이것은 SMA 지표에 기반한 동적 트렌드 추적 거래 전략으로, 가격 간격, 무작위 지표, 그리고 다중 이익 보호 장치가 결합되어 있다. 이 전략은 단기 및 장기 이동 평균의 교차 신호를 결합하여 가격의 움직임을 모니터링하고, 동시에 시장 상태와 트렌드 강도를 결정하기 위해 무작위 지표를 사용하여 효율적인 트렌드 캡처를 수행한다. 이 전략은 퍼센트 및 고정 점 두 가지의 스톱 장치를 설계하여 수익과 위험을 효과적으로 균형을 맞추고 있다.

전략 원칙

전략의 핵심 논리는 다음과 같은 핵심 부분으로 구성됩니다.

  1. 19주기 및 74주기 SMA를 사용하여 트렌드 프레임워크를 구축
  2. 60주기 무작위 지표를 통해 시장 상태를 판단하고, SMA의 색깔을 노란색, 녹색, 빨간색, 황색으로 구분한다.
  3. 가격의 강점을 판단하기 위해 5개의 중요한 레벨을 가격 범위에 나누고
  4. 다음 진입 조건을 동시에 충족해야 합니다.
    • SMA는 녹색 또는 노란색 상태입니다.
    • 오렌지색 지역에서의 가격 상승
    • 마감 가격은 단기 SMA보다 높습니다.
  5. 두 가지의 차단 장치가 설치되어 있습니다.
    • 최대 가격에 따른 백분율 철회 보호
    • 고정 점수를 기반으로 수익을 잠금

전략적 이점

  1. 복수확인 메커니즘이 가짜 신호를 줄여줍니다.
  2. 동적인 구역분열은 시장환경에 적응합니다.
  3. 더 나은 위험 통제를 제공하는 이중 차단 장치
  4. 명확한 시장 상태 분류는 시장의 속도를 파악하는 데 도움이 됩니다.
  5. 실시간 거래 상태 모니터링으로 전략 수정이 가능합니다.
  6. 기술 지표와 가격 행동 분석

전략적 위험

  1. 위기 시장에서 과도한 거래가 발생할 수 있습니다.
  2. 정지점 번호를 정지하는 것은 큰 일을 놓칠 수 있습니다.
  3. 매개변수 최적화로 인해 과적합이 발생할 수 있습니다.
  4. 시장의 급격한 전환으로 인해 수익을 잃을 수 있습니다.
  5. 다중 확인 조건은 일부 거래 기회를 놓칠 수 있습니다. 해결책:
  • 변동율 필터에 추가
  • 동적으로 정지 변수를 조정
  • 시장환경 식별 메커니즘 강화
  • 출전 타이밍을 최적화

전략 최적화 방향

  1. 변동률 지표의 동적 조정 파라미터를 도입
  2. 시장 상황에 따라 자동으로 조정되는 정지 조건
  3. 거래량 확인 메커니즘 추가
  4. 트렌드 강도 필터를 추가하세요
  5. 시장의 특성을 고려하여 지역 분할 방법을 최적화하십시오.
  6. 위험 관리 제도를 개선합니다.
    • 일일 상쇄 손실
    • 최대 철회 제어
    • 보유 기간 제한

요약하다

이 전략은 여러 가지 기술 지표와 가격 행동 분석 방법을 통합하여 전체적인 거래 시스템을 구축합니다. 전략의 장점은 여러 가지 확인 메커니즘과 유연한 차단 시스템입니다. 그러나 시장 환경이 전략의 성과에 미치는 영향을 고려해야합니다. 지속적인 최적화와 위험 관리를 개선함으로써 전략은 다양한 시장 환경에서 안정적인 성과를 유지할 것으로 예상됩니다.

전략 소스 코드
/*backtest
start: 2019-12-23 08:00:00
end: 2024-12-18 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy(title="SMA Color Strategy", 
     overlay=true, 
     initial_capital=10000,
     max_bars_back=5000,
     max_labels_count=500,
     max_boxes_count=500,
     default_qty_type=strategy.fixed,
     default_qty_value=1,
     currency=currency.NONE,
     process_orders_on_close=true)

// === INPUTS ===
zoneLength = input.int(20, "Price Zone Length", minval=5)
profitLockPct = input.float(50, "Profit Lock Percentage", minval=1, maxval=100, step=5) / 100
ticksToLock = input.int(12, "Ticks to Activate Lock", minval=1, tooltip="Number of ticks price must move up to activate tick-based lock")
ticksToSecure = input.int(10, "Ticks to Secure", minval=1, tooltip="Number of ticks to lock in once activated")

// Calculate tick values
tickSize = syminfo.mintick
ticksToLockPoints = ticksToLock * tickSize
ticksToSecurePoints = ticksToSecure * tickSize

// Calculate price zones
h = ta.highest(high, zoneLength)
l = ta.lowest(low, zoneLength)
priceRange = h - l
lvl5 = h
lvl4 = l + (priceRange * 0.75)  // Orange line
lvl3 = l + (priceRange * 0.50)  // Yellow line
lvl2 = l + (priceRange * 0.25)  // Green line
lvl1 = l

// Calculate SMAs
sma19 = ta.sma(close, 19)
sma74 = ta.sma(close, 74)

// Stochastic calculation for color logic
k = ta.stoch(close, high, low, 60)
d = ta.sma(k, 10)

// SMA Color Logic with state tracking
var color currentSMAColor = color.orange
var color previousSMAColor = color.orange
var string currentColorName = "ORANGE"
var string previousColorName = "ORANGE"

smaColor = if d >= 80 or d <= 20
    color.rgb(255, 215, 0)
else if d > d[1]
    color.green
else if d < d[1]
    color.red
else
    color.orange

// Update color state and names
if smaColor != currentSMAColor
    previousSMAColor := currentSMAColor
    currentSMAColor := smaColor
    previousColorName := currentColorName
    currentColorName := if smaColor == color.rgb(255, 215, 0)
        "YELLOW"
    else if smaColor == color.green
        "GREEN"
    else if smaColor == color.red
        "RED"
    else
        "ORANGE"

// Color logic for SMA74
sma74Color = if smaColor == color.rgb(255, 215, 0)
    color.rgb(255, 215, 0)                          
else if sma74 < sma19                               
    color.green
else                                                
    color.red

// === ENTRY CONDITIONS ===
smaIsGreen = smaColor == color.green
greenCandle = close > open
candleAboveOrange = close > lvl4
candleAboveSMA = close > sma19
crossedAboveOrange = ta.crossover(close, lvl4)
smaIsYellow = smaColor == color.rgb(255, 215, 0)

longCondition1 = smaIsGreen and greenCandle and candleAboveOrange and candleAboveSMA and crossedAboveOrange
longCondition2 = smaIsYellow and crossedAboveOrange and candleAboveSMA

// === PROFIT LOCK SYSTEM ===
var float entryPrice = na
var float maxPrice = na
var float profitLockLevel = na
var bool tickLockActivated = false
var float tickBasedLockLevel = na

// Reset variables on new trade entry
if (longCondition1 or longCondition2)
    entryPrice := close
    maxPrice := close
    profitLockLevel := close * (1 - profitLockPct)
    tickLockActivated := false
    tickBasedLockLevel := na

// Update maximum price and profit locks when in a trade
if strategy.position_size > 0
    maxPrice := math.max(maxPrice, high)
    profitLockLevel := math.max(profitLockLevel, maxPrice * (1 - profitLockPct))
    
    // Check if price has moved up enough to activate tick-based lock
    if not tickLockActivated and (maxPrice - entryPrice) >= ticksToLockPoints
        tickLockActivated := true
        tickBasedLockLevel := entryPrice + ticksToSecurePoints

// === EXIT CONDITIONS ===
exitOnYellowLine = close < lvl3
exitOnProfitLock = low < profitLockLevel and strategy.position_size > 0
exitOnTickLock = tickLockActivated and low < tickBasedLockLevel

// === TRADE MANAGEMENT ===
if (longCondition1 or longCondition2)
    strategy.entry("Long", strategy.long)

if strategy.position_size > 0
    if exitOnYellowLine
        strategy.close("Long", comment="Close below yellow")
    if exitOnProfitLock
        strategy.close("Long", comment="Profit lock triggered")
    if exitOnTickLock
        strategy.close("Long", comment="Tick-based lock triggered")

// Plot indicators
plot(sma19, "SMA 19", color=smaColor, linewidth=2)
plot(sma74, "SMA 74", color=sma74Color, linewidth=2)
plot(lvl5, "Upper Zone Top", color=color.red, linewidth=2)
plot(lvl4, "Upper Zone Bottom", color=color.orange, linewidth=2)
plot(lvl3, "Middle Line", color=color.yellow, linewidth=2)
plot(lvl2, "Lower Zone Top", color=color.green, linewidth=2)
plot(lvl1, "Lower Zone Bottom", color=color.blue, linewidth=2)

// Plot profit lock levels
plot(strategy.position_size > 0 ? profitLockLevel : na, "Profit Lock Level", color=color.purple, style=plot.style_linebr, linewidth=2)
plot(strategy.position_size > 0 and tickLockActivated ? tickBasedLockLevel : na, "Tick Lock Level", color=color.fuchsia, style=plot.style_linebr, linewidth=2)

// Fill zones
var p1 = plot(lvl5, display=display.none)
var p2 = plot(lvl4, display=display.none)
var p3 = plot(lvl2, display=display.none)
var p4 = plot(lvl1, display=display.none)
fill(p1, p2, color=color.new(color.red, 90))
fill(p3, p4, color=color.new(color.green, 90))

// Debug Table
if barstate.islast
    var table debugTable = table.new(position.top_right, 2, 13, bgcolor=color.new(color.black, 70), frame_width=1)
    
    table.cell(debugTable, 0, 0, "Current Color", text_color=color.white)
    table.cell(debugTable, 1, 0, currentColorName, text_color=currentSMAColor)
    
    table.cell(debugTable, 0, 1, "Previous Color", text_color=color.white)
    table.cell(debugTable, 1, 1, previousColorName, text_color=previousSMAColor)
    
    table.cell(debugTable, 0, 2, "Entry 1 (Green)", text_color=color.white)
    table.cell(debugTable, 1, 2, str.tostring(longCondition1), text_color=color.white)
    
    table.cell(debugTable, 0, 3, "Entry 2 (Yellow)", text_color=color.white)
    table.cell(debugTable, 1, 3, str.tostring(longCondition2), text_color=color.white)
    
    table.cell(debugTable, 0, 4, "Current Position", text_color=color.white)
    table.cell(debugTable, 1, 4, str.tostring(strategy.position_size), text_color=color.white)
    
    table.cell(debugTable, 0, 5, "Entry Price", text_color=color.white)
    table.cell(debugTable, 1, 5, str.tostring(entryPrice), text_color=color.white)
    
    table.cell(debugTable, 0, 6, "Max Price", text_color=color.white)
    table.cell(debugTable, 1, 6, str.tostring(maxPrice), text_color=color.white)
    
    table.cell(debugTable, 0, 7, "Profit Lock Level", text_color=color.white)
    table.cell(debugTable, 1, 7, str.tostring(profitLockLevel), text_color=color.white)
    
    table.cell(debugTable, 0, 8, "Tick Lock Active", text_color=color.white)
    table.cell(debugTable, 1, 8, str.tostring(tickLockActivated), text_color=color.white)
    
    table.cell(debugTable, 0, 9, "Tick Lock Level", text_color=color.white)
    table.cell(debugTable, 1, 9, str.tostring(tickBasedLockLevel), text_color=color.white)
    
    table.cell(debugTable, 0, 10, "Price Move (Ticks)", text_color=color.white)
    table.cell(debugTable, 1, 10, str.tostring(strategy.position_size > 0 ? (maxPrice - entryPrice) / tickSize : 0), text_color=color.white)
    
    table.cell(debugTable, 0, 11, "Locked Profit %", text_color=color.white)
    table.cell(debugTable, 1, 11, str.tostring(strategy.position_size > 0 ? ((maxPrice - entryPrice) / entryPrice * 100) : 0.0) + "%", text_color=color.white)
    
    table.cell(debugTable, 0, 12, "Exit Signals", text_color=color.white)
    table.cell(debugTable, 1, 12, "Y:" + str.tostring(exitOnYellowLine) + " P:" + str.tostring(exitOnProfitLock) + " T:" + str.tostring(exitOnTickLock), text_color=color.white)