EMA를 기반으로 하는 신호등 거래 전략

저자:차오장, 날짜: 2023-11-24 15:46:48
태그:

img

전반적인 설명

이 전략은 빨간색, 노란색 및 녹색 신호등과 유사한 배열 순서에 따라 거래 신호를 생성하기 위해 다른 기간의 4 개의 EMA 라인을 사용합니다. 따라서 트래픽 라이트 거래 전략이라고합니다. 트렌드 및 역전 관점에서 시장을 포괄적으로 판단하여 거래 결정의 정확성을 향상시키는 것을 목표로합니다.

전략 원칙

  1. 빠른 (8주기), 중간 (14주기) 및 느린 (16주기) 에 3개의 EMA 라인을 설정하고, 필터로 1개의 긴 (100주기) EMA 라인을 설정합니다.

  2. 3개의 EMA 라인의 순서와 필터와의 교차를 기반으로 긴 기회와 짧은 기회를 결정합니다.

  • 빠른 선이 중간 선 위에 넘어가거나 중간 선이 느린 선 위에 넘어가면, 그것은 긴 신호로 결정됩니다.

  • 중간 선이 빠른 선 아래를 통과하면 긴 신호로 결정됩니다.

  • 빠른 선이 중간 선 아래로 넘어가거나 중간 선이 느린 선 아래로 넘어가면, 이는 짧은 신호로 결정됩니다.

  • 중간 선이 빠른 선 위에 넘어가면, 그것은 가까운 짧은 신호로 결정됩니다.

  1. 트렌드 방향과 강도를 3개의 EMA 라인의 순서를 통해 판단하고, 트렌드 추종과 역전 거래를 유기적으로 통합하는 전환점을 결정하기 위해 EMA 라인과 필터 사이의 교차와 결합합니다.

이점 분석

이 전략은 시장 기회를 잘 파악할 수 있는 트렌드 추적 및 역전 거래의 장점을 통합합니다. 주요 장점은 다음과 같습니다.

  1. 여러 EMA 라인을 사용하면 판단이 더 확실해지고 잘못된 신호를 줄입니다.
  2. 긴 조건과 짧은 조건에 대한 유연한 설정은 거래 기회를 놓치지 않도록합니다.
  3. 장기 및 단기 EMA 라인의 조합은 포괄적 인 판단을 제공합니다.
  4. 사용자 정의 가능한 수익 취득 및 스톱 손실은 더 나은 위험 통제를 허용합니다.

매개 변수 최적화를 통해 이 전략은 더 많은 제품에 적응할 수 있으며 백테스트에서 강력한 수익성과 안정성을 입증했습니다.

위험 분석

이 전략의 주요 위험은 다음과 같습니다.

  1. 여러 EMA 라인의 순서가 엉망이 되면 판단의 어려움이 커지고 거래에 주저감을 유발합니다.
  2. 이는 시장의 비정상적인 변동으로부터 잘못된 신호를 효과적으로 필터링할 수 없으며 이는 상당한 변동성 손실을 일으킬 수 있습니다.
  3. 부적절한 매개 변수 설정은 너무 느슨하거나 너무 엄격한 스톱 이익/손실 기준을 초래할 수 있으며, 이로 인해 손실이 부족하거나 손실이 너무 많을 수 있습니다.

매개 변수를 최적화하고, 스톱 로스 레벨을 설정하고, 조심스럽게 거래함으로써 전략의 안정성을 더욱 향상시키고 위험을 통제하는 것이 좋습니다.

최적화 방향

이 전략의 주요 최적화 방향:

  1. EMA 라인의 사이클 매개 변수를 조정하여 더 많은 제품에 적응합니다.
  2. 판단의 정확성을 높이기 위해 MACD, 볼링거 밴드 등과 같은 다른 지표를 추가하십시오.
  3. 리스크와 수익 사이의 최적의 균형을 이루기 위해 수익/손실 중단 비율을 최적화합니다.
  4. ATR Stop Loss 같은 적응식 스톱 로스 메커니즘을 추가하여 하향 리스크를 더욱 제어합니다.

전략의 안정성과 수익성을 지속적으로 향상시키는 것은 여러 측면의 매개 변수 조정 및 위험 관리 조치를 도입함으로써 달성 할 수 있습니다.

결론

이 트래픽 라이트 트레이딩 전략은 트레이딩 신호를 형성하기 위해 4 세트 EMA 라인을 사용하여 트렌드 추적 및 역전 거래를 통합합니다. 더 많은 제품에 적응하기 위해 매개 변수 최적화를 통해 강력한 수익성을 입증했습니다. 앞으로 위험 통제를 더욱 강화하고 다양화된 지표를 도입함으로써 안정적이고 효율적인 양적 거래 전략이 될 가능성이 있습니다.


/*backtest
start: 2023-01-01 00:00:00
end: 2023-11-23 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © maxits

// 4HS Crypto Market Strategy
// This strategy uses 4 ema to get Long or Short Signals
// Length are: 8, 14, 16, 100
// We take long positions when the order of the emas is the following:
// green > yellow > red (As the color of Traffic Lights) and they are above white ema (Used as a filter for long positions)
  
// We take short positions when the order of the emas is the following:
// green < yellow < red (As the color of inverse Traffic Lights) and they are below white ema (Used as a filter for short positions)

//@version=4
strategy(title="Trafic Lights Strategy",
         shorttitle="TLS",
         overlay=true,
         initial_capital=1000,
         default_qty_value=20,
         default_qty_type=strategy.percent_of_equity,
         commission_value=0.1,
         pyramiding=0
         )

// User Inputs
// i_time         = input(defval = timestamp("28 May 2017 13:30 +0000"), title = "Start Time", type = input.time) //Starting time for Backtesting

sep1           = input(title="============ System Conditions ============", type=input.bool, defval=false)

enable_Long    = input(true, title="Enable Long Positions")   // Enable long  Positions
enable_Short   = input(true, title="Enable Short Positions") // Enable short Positions

sep2           = input(title="============ Indicator Parameters ============", type=input.bool, defval=false)

f_length       = input(title="Fast EMA Length",   type=input.integer, defval=8,   minval=1) 
m_length       = input(title="Medium EMA Length", type=input.integer, defval=14,   minval=1) 
s_length       = input(title="Slow EMA Length",   type=input.integer, defval=16,  minval=1) 
filter_L       = input(title="EMA Filter",        type=input.integer, defval=100, minval=1) 
filterRes      = input(title="Filter Resolution", type=input.resolution, defval="D")        // ema Filter Time Frame

sep3           = input(title="============LONG Profit-Loss Parameters============", type=input.bool, defval=false)

e_Long_TP      = input(true, title="Enable a Profit Level?")
e_Long_SL      = input(false, title="Enable a S.Loss Level?")
e_Long_TS      = input(true, title="Enable a Trailing Stop?")           
long_TP_Input  = input(40.0,   title='Take Profit %',   type=input.float,   minval=0)/100
long_SL_Input  = input(1.0,   title='Stop Loss %',     type=input.float,   minval=0)/100 
atrLongMultip  = input(2.0,   title='ATR Multiplier',  type=input.float,   minval=0.1)   // Parameters to calculate Trailing Stop Loss
atrLongLength  = input(14,    title='ATR Length',      type=input.integer, minval=1)

sep4           = input(title="============SHORT Profit-Loss Parameters============", type=input.bool, defval=false)

e_Short_TP     = input(true, title="Enable a Profit Level?")
e_Short_SL     = input(false, title="Enable a S.Loss Level?")
e_Short_TS     = input(true, title="Enable a Trailing Stop?")
short_TP_Input = input(30.0,   title='Take Profit %',   type=input.float,   minval=0)/100
short_SL_Input = input(1.0,   title='Stop Loss %',     type=input.float,   minval=0)/100
atrShortMultip = input(2.0,   title='ATR Multiplier',  type=input.float,   minval=0.1)
atrShortLength = input(14,    title='ATR Length',      type=input.integer, minval=1)

// Indicators

fema   = ema(close, f_length)
mema   = ema(close, m_length)
sema   = ema(close, s_length)
filter = security(syminfo.tickerid, filterRes, ema(close, filter_L))

plot(fema,   title="Fast EMA",   color=color.new(color.green,  0))
plot(mema,   title="Medi EMA",   color=color.new(color.yellow, 0))
plot(sema,   title="Slow EMA",   color=color.new(color.red,    0))
plot(filter, title="EMA Filter", color=color.new(color.white,  0))

// Entry Conditions

longTrade  = strategy.position_size >  0
shortTrade = strategy.position_size <  0
notInTrade = strategy.position_size == 0
inTrade    = strategy.position_size != 0
priceEntry = strategy.position_avg_price

goLong  = fema > mema and mema > sema and fema > filter and  enable_Long  and (crossover (fema, mema) or crossover (mema, sema) or crossover (sema, filter))
goShort = fema < mema and mema < sema and fema < filter and  enable_Short and (crossunder (fema, mema) or crossunder (mema, sema) or crossunder (sema, filter))

close_L = crossunder(fema, mema)
close_S = crossover (fema, mema)

// Profit and Loss conditions

// Long
 
long_TP = priceEntry * (1 + long_TP_Input)  // Long Position Take Profit Calculation
long_SL = priceEntry * (1 - long_SL_Input)  // Long Position Stop Loss Calculation
atrLong = atr(atrLongLength)                // Long Position ATR Calculation
long_TS = low - atrLong * atrLongMultip

long_T_stop  = 0.0                          // Code for calculating Long Positions Trailing Stop Loss/
long_T_stop := if (longTrade)
    longStop = long_TS
    max(long_T_stop[1], longStop)
else 
    0
    
//Short

short_TP = priceEntry * (1 - short_TP_Input) // Long  Position Take Profit Calculation
short_SL = priceEntry * (1 + short_SL_Input) // Short Position Stop Loss Calculation
atrShort = atr(atrShortLength)               // Short Position ATR Calculation
short_TS = high + atrShort * atrShortMultip

short_T_stop   = 0.0                // Code for calculating Short Positions Trailing Stop Loss/
short_T_stop  := if shortTrade
    shortStop  = short_TS
    min(short_T_stop[1], shortStop)
else 
    9999999

// Strategy Long Entry

if goLong and notInTrade 
    strategy.entry("Go Long", long=strategy.long, comment="Go Long", alert_message="Open Long Position")

if longTrade and close_L
    strategy.close("Go Long", when=close_L, comment="Close Long", alert_message="Close Long Position")
    
if e_Long_TP    // Algorithm for Enabled Long Position Profit Loss Parameters
    if (e_Long_TS and not e_Long_SL)
        strategy.exit("Long TP & TS", "Go Long", limit = long_TP, stop = long_T_stop)
    else
        if (e_Long_SL and not e_Long_TS)
            strategy.exit("Long TP & TS", "Go Long",limit = long_TP, stop = long_SL)
        else 
            strategy.exit("Long TP & TS", "Go Long",limit = long_TP)
else
    if not e_Long_TP 
        if (e_Long_TS and not e_Long_SL)
            strategy.exit("Long TP & TS", "Go Long", stop = long_T_stop)
        else
            if (e_Long_SL and not e_Long_TS)
                strategy.exit("Long TP & TS", "Go Long",stop = long_SL)
    

// Strategy Short Entry

if goShort and notInTrade 
    strategy.entry("Go Short", long=strategy.short, comment="Go Short", alert_message="Open Short Position")

if shortTrade and close_S
    strategy.close("Go Short", comment="Close Short", alert_message="Close Short Position")

if e_Short_TP   // Algorithm for Enabled Short Position Profit Loss Parameters
    if (e_Short_TS and not e_Short_SL)
        strategy.exit("Short TP & TS", "Go Short", limit = short_TP, stop = short_T_stop)
    else
        if (e_Short_SL and not e_Short_TS)
            strategy.exit("Short TP & SL", "Go Short",limit = short_TP, stop = short_SL)
        else 
            strategy.exit("Short TP & TS", "Go Short",limit = short_TP)
else
    if not e_Short_TP 
        if (e_Short_TS and not e_Short_SL)
            strategy.exit("Short TS", "Go Short", stop = short_T_stop)
        else
            if (e_Short_SL and not e_Short_TS)
                strategy.exit("Short SL", "Go Short",stop = short_SL)

// Long  Position Profit and Loss Plotting

plot(longTrade and e_Long_TP  and long_TP                          ? long_TP      : na, title="TP Level", color=color.green, style=plot.style_linebr, linewidth=2)
plot(longTrade and e_Long_SL  and long_SL and not e_Long_TS        ? long_SL      : na, title="SL Level", color=color.red,   style=plot.style_linebr, linewidth=2)
plot(longTrade and e_Long_TS  and long_T_stop and not e_Long_SL    ? long_T_stop  : na, title="TS Level", color=color.red,   style=plot.style_linebr, linewidth=2)

// Short Position Profit and Loss Plotting

plot(shortTrade and e_Short_TP and short_TP                        ? short_TP     : na, title="TP Level", color=color.green, style=plot.style_linebr, linewidth=2)
plot(shortTrade and e_Short_SL and short_SL and not e_Short_TS     ? short_SL     : na, title="SL Level", color=color.red,   style=plot.style_linebr, linewidth=2)
plot(shortTrade and e_Short_TS and short_T_stop and not e_Short_SL ? short_T_stop : na, title="TS Level", color=color.red,   style=plot.style_linebr, linewidth=2)



더 많은