평균 회전선 전략

저자:차오장, 날짜: 2023-12-29 11:33:04
태그:

img

전반적인 설명

평균 회전 라인 전략은 이동 평균 반전을 기반으로 한 단기 거래 전략입니다. 그것은 볼링거 밴드, RSI, CCI 및 기타 지표를 결합하여 단기 시장 변동을 파악하고 낮은 구매와 높은 판매의 목표를 달성합니다.

이 전략은 주식 지수, 외화 및 귀금속과 같은 유동성 높은 상품에 주로 사용됩니다. 거래의 전반적인 위험 수익률을 제어하면서 거래 당 수익을 극대화하는 것을 추구합니다.

전략 원칙

  1. 가격 오차 구역을 판단하기 위해 볼링거 밴드를 사용하십시오. 가격이 상부 볼링거 밴드에 접근 할 때 짧은 것을 고려하고 가격이 하부 볼링거 밴드에 접근 할 때 긴 것을 고려하십시오.

  2. RSI 지표를 결합하여 과반 구매 및 과반 판매 상황을 결정할 수 있습니다. RSI 지표는 과반 구매 및 과반 판매 상황을 효과적으로 식별 할 수 있습니다.

  3. CCI 지표를 사용하여 가격 반전 신호를 결정합니다. CCI 지표는 이상에 상대적으로 민감하며 가격 반전 기회를 효과적으로 파악 할 수 있습니다.

  4. 가격이 5 일 이동 평균 이상으로 넘어갈 때 길게 이동하고 아래로 넘어갈 때 짧게 이동합니다. 이동 평균의 위치는 현재 주요 가격 범위를 나타냅니다. 가격과 이동 평균 사이의 관계는 잠재적 인 트렌드 변화를 반영합니다.

  5. 진입 신호가 확정된 후, 수익을 얻기 위해 빠르게 포지션을 닫습니다. 높은 승률을 실현하기 위해 리트레이싱에 기반한 스톱 로스를 설정하십시오.

전략 의 장점

  1. 여러 지표의 조합은 신호의 정확성을 향상시킵니다.

평균 회전 라인 전략은 볼링거 밴드, RSI, CCI 및 기타 지표를 결합합니다. 이러한 지표는 가격 변화에 매우 민감하며, 그 조합은 신호 정확성을 향상시키고 잘못된 신호를 줄일 수 있습니다.

  1. 엄격한 진입 규칙은 트렌드를 쫓는 것을 피합니다

이 전략은 단일 지표에 의해 오해를 피하기 위해 동기화 된 지표 신호와 가격을 요구합니다. 또한 관련 위험을 줄이기 위해 명백한 가격 반전을 요구합니다.

  1. 효율적인 스톱 로스 메커니즘은 단일 거래 손실을 통제합니다.

장기 또는 단위로 가든 전략은 상대적으로 엄격한 스톱 로스 라인을 설정합니다. 가격이 불리한 방향으로 스톱 로스 라인을 넘으면 전략은 거래당 큰 손실을 피하기 위해 신속하게 손실을 멈추게됩니다.

  1. 합리적인 수익은 거래당 수익을 극대화하는 것을 추구합니다.

이 전략은 이윤을 단계적으로 실현하기 위해 두 가지 수익 목표를 설정할 것입니다. 동시에 이윤을 취한 후 거래 당 수익 공간을 확장하기 위해 작은 단계 조정 추적 스톱 손실을 사용할 것입니다.

위험 분석

  1. 가격 변동이 스톱 로스를 유발합니다.

극심 한 가격 변동 의 경우, 스톱 로스 라인 이 깨질 수 있으며, 불필요한 손실 을 초래 할 수 있다. 이 같은 상황 은 보통 주요 사건 으로 인해 발생하는 비정상적 인 가격 변동 도중 발생 한다.

이 위험은 스톱 로스 범위를 확장하고 주요 이벤트 중 거래를 피함으로써 완화 될 수 있습니다.

  1. 과열 상승 후 역행 할 수 없습니다

상승 추세가 너무 치열할 때, 가격은 시간이 지남에 따라 되돌릴 수 없을 정도로 너무 빨리 상승합니다. 이 경우 단축을 계속하면 상승 추세를 쫓는 위험이 발생할 수 있습니다.

이 경우 일시적으로 기다린다면 더 좋고 상승 동력이 크게 약화 된 후에야 단축을 고려하는 것이 좋습니다.

최적화 방향

  1. 신호 정확성을 향상시키기 위해 지표 매개 변수를 최적화

백테스트 결과는 최적의 매개 변수를 선택하기 위해 다른 매개 변수 조합에 따라 테스트 할 수 있습니다. 예를 들어, RSI 매개 변수, CCI 매개 변수 최적화 할 수 있습니다.

  1. 실제 반전 시기를 결정하기 위해 부피 표시기를 포함합니다.

거래량이나 볼링거 대역폭과 같은 볼륨 지표가 추가 될 수 있습니다. 이것은 가격이 약간만 조정 될 때 잘못된 신호를 생성하는 것을 피할 수 있습니다.

  1. 단일 수익을 극대화하기 위해 수익을 취하고 손실을 멈추는 전략을 최적화하십시오.

각 거래당 수익을 극대화하기 위해 다른 수익 취지와 스톱 로스 포인트를 테스트 할 수 있습니다. 동시에 위험도 균형 잡혀 스톱 로스가 쉽게 유발되는 것을 방지해야합니다.

결론

평균회전선 전략은 여러 지표 판단을 종합적으로 활용하고 정확한 신호, 건전한 운영 및 제어 가능한 위험의 특성을 가지고 있습니다. 시장 변화에 매우 민감하고 상대적으로 강한 유동성을 가진 제품에 적합합니다. 그것은 낮은 구매와 높은 판매의 목표를 달성하기 위해 볼링거 밴드와 주요 이동 평균 사이의 가격 역전 기회를 포착 할 수 있습니다.

실제 응용 분야에서는 여전히 지표 매개 변수 최적화에주의를 기울여야하며, 실제 반전의 시기를 결정하기 위해 볼륨 지표를 결합해야합니다. 또한 극단적인 가격 변동에 대한 적절한 위험 관리가 이루어져야합니다. 올바르게 사용하면이 전략은 비교적 안정적인 알파 수익을 얻을 수 있습니다.


/*backtest
start: 2022-12-22 00:00:00
end: 2023-12-28 00:00:00
period: 1d
basePeriod: 1h
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/
// © sg1999

//@version=4


// >>>>>strategy name
strategy(title = "CCI-RSI MR", shorttitle = "CCI-RSI MR", overlay = true)

// >>>>input variables

// 1. risk per trade as % of initial capital
risk_limit = input(title="Risk Limit (%)", type=input.float, minval=0.1, defval=2.0, step=0.1)

// 2. drawdown
Draw_down = input(title="Max Drawdown (x ATR)", type=input.float, minval=0.5, maxval=10, defval=2.0, step=0.1)

// 3. type of stop loss to be used
original_sl_type  = input(title="SL Based on", defval="Close Price", options=["Close Price","Last Traded Price"])

// 4. entry signal validity for bollinger strategies
dist_from_signal= input(title="Entry distance from signal", type=input.integer, minval=1, maxval=20, defval=3, step=1)

// 5. multiple exit points
exit_1_pft_pct          = input(title="1st exit when reward is", type=input.float, minval=0.5, maxval=100, defval=1.0, step=0.1)
exit_1_qty_pct          = input(title="1st exit quantity %", type=input.float, minval=1, maxval=100, defval=100, step=5)
exit_2_pft_pct          = input(title="2nd exit when reward is", type=input.float, minval=0.5, maxval=100, defval=1.5, step=0.1)
sl_trail_pct            = input(title="Trailing SL compared to original SL", type=input.float, minval=0.5, maxval=100, defval=0.5, step=0.5)

//show signal bool
plotBB = input(title="Show BB", type=input.bool, defval=true)
plotSignals  = input(title="Show Signals", type=input.bool, defval=true)

// 6. date range to be used for backtesting
fromMonth = input(defval = 1,    title = "From Month",      type = input.integer, minval = 1, maxval = 12)
fromDay   = input(defval = 1,    title = "From Day",        type = input.integer, minval = 1, maxval = 31)
fromYear  = input(defval = 1990, title = "From Year",       type = input.integer, minval = 1970)
thruMonth = input(defval = 1,    title = "Thru Month",      type = input.integer, minval = 1, maxval = 12)
thruDay   = input(defval = 1,    title = "Thru Day",        type = input.integer, minval = 1, maxval = 31)
thruYear  = input(defval = 2022, title = "Thru Year",       type = input.integer, minval = 1970)

start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)        // backtest start window
finish    = timestamp(thruYear, thruMonth, thruDay, 23, 59)        // backtest finish window
window()  => true

// >>>>>strategy variables

//input variables 
current_high = highest(high, 5)     // swing high (5 period)
current_low = lowest(low, 5)        // swing low (5 period)
current_ma = sma(close, 5)          // Simple Moving average (5 period)
atr_length = atr(20)                // ATR (20 period)  
CCI = cci(close,20)                 // CCI (20 period)
RSI = rsi(close,14)                 // RSI (14 period)
RSI_5 = sma (RSI, 5)                // Simple moving average of RSI (5 period)


// 1. for current candle

long_entry              = false 
short_entry             = false
risk_reward_ok          = false
sl_hit_flag             = false
tsl_hit_flag            = false
sl_cross                = false

// 2. across candles

var RSI_short           = false     //short signal boolean
var RSI_long            = false     //long signal boolean
var cci_sell            = false     //sellsignal crossunder boolean
var cci_buy             = false     //buy signal crossover boolean
var bar_count_long      = 0         // Number of bars after a long signal 
var bar_count_short     = 0         // Number of bars after a short signal
var candles_on_trade    = 0         
var entry_price         = 0.00
var sl_price            = 0.00
var qty                 = 0
var exit_1_qty          = 0
var exit_2_qty          = 0
var exit_1_price        = 0.0
var exit_2_price        = 0.0
var hold_high           = 0.0       // variable used to calculate Trailing sl
var hold_low            = 0.0       // variable used to calculate Trailing sl
var tsl_size            = 0.0       // Trailing Stop loss size(xR)
var sl_size             = 0.0       // Stop loss size (R)
var tsl_price           = 0.0       //Trailing stoploss price


// >>>>>strategy conditions.
// Bollinger bands (2 std)
[mBB0,uBB0,lBB0] = bb(close,20,2)
uBB0_low= lowest(uBB0,3) // lowest among upper BB of past 3 periods
lBB0_high= highest(lBB0,3) //highest among upper BB of past 3 periods


//RSI and CCI may not necessarily crossunder on the same candle
t_sell_RSI = sum( crossunder(RSI,RSI_5)? 1 : 0, 2) == 1 // checks if crossunder has happened in the last 3 candles (including the current candle)
t_sell_CCI = sum( crossunder(CCI,100)? 1 : 0, 2) == 1 //and (CCI >50)
t_buy_RSI  = sum( crossover(RSI,RSI_5)? 1 : 0, 2) == 1  //checks if crossover has happened in the last 3 candles (including the current candle)
t_buy_CCI  = sum( crossover(CCI,-100) ? 1 : 0, 2) == 1 //and (CCI<-50)

// CONDITIONS FOR A SELL signal
if t_sell_RSI and t_sell_CCI and (current_high >= uBB0_low) 
    cci_sell := true
    bar_count_short := 0
 
if  cci_sell and strategy.position_size ==0 
    bar_count_short := bar_count_short + 1
    
if  cci_sell and bar_count_short<= dist_from_signal and close <= current_ma  and strategy.position_size ==0
    RSI_short := true

//conditions for a BUY signal
if t_buy_RSI and t_buy_CCI and (current_low <= lBB0_high) // or current_low_close <= lBB01_high)
    cci_buy := true
    bar_count_long := 0

if  cci_buy and strategy.position_size ==0 
    bar_count_long := bar_count_long + 1
    
if  cci_buy and  bar_count_long<= dist_from_signal and close >= current_ma and strategy.position_size ==0
    RSI_long := true

if RSI_long and RSI_short
    RSI_long := false
    RSI_short := false



// >>>>>entry and target specifications

if strategy.position_size == 0 and RSI_short 
    short_entry         := true
    entry_price         := close
    sl_price            := current_high + syminfo.mintick // (swing high + one tick) is the stop loss
    sl_size             := abs(entry_price - sl_price)
    candles_on_trade    := 0
    tsl_size            := abs(entry_price - sl_price)*sl_trail_pct // Here sl_trail_pct is the multiple of R which is used to calculate TSL size

if strategy.position_size == 0 and RSI_long 
    long_entry          := true
    entry_price         := close
    sl_price            := current_low -  syminfo.mintick //(swing low - one tick) is the stop loss
    candles_on_trade    := 0
    sl_size             := abs(entry_price - sl_price)
    tsl_size            := abs(entry_price - sl_price)*sl_trail_pct // Here sl_trail_pct is the multiple of R which is used to calculate TSL size
    
if long_entry and short_entry
    long_entry          := false
    short_entry         := false
    
    
// >>>>risk evaluation criteria
    
//>>>>> quantity determination and exit point specifications.
    
if (long_entry or short_entry) and strategy.position_size == 0 // Based on our risk (R), no.of lots is calculated by considering a risk per trade limit formula
    qty                 := round((strategy.equity) * (risk_limit/100)/(abs(entry_price - sl_price)*syminfo.pointvalue))
    exit_1_qty          := round(qty * (exit_1_qty_pct/100))
    exit_2_qty          := qty - (exit_1_qty)
    if long_entry
        exit_1_price    := entry_price + (sl_size * exit_1_pft_pct) 
        exit_2_price    := entry_price + (sl_size * exit_2_pft_pct)
    if short_entry
        exit_1_price    := entry_price - (sl_size * exit_1_pft_pct) 
        exit_2_price    := entry_price - (sl_size * exit_2_pft_pct)
        
        
// trail SL after 1st target is hit
if abs(strategy.position_size) == 0
    hold_high   := 0
    hold_low    := 0

if strategy.position_size > 0 and high > exit_1_price
    if high > hold_high or hold_high == 0
        hold_high    := high
    tsl_price        := hold_high - tsl_size
    

if strategy.position_size < 0 and low < exit_1_price
    if low  < hold_low or hold_low == 0
        hold_low     := low
    tsl_price        := hold_low + tsl_size

    
//>>>> entry conditons

if long_entry and strategy.position_size == 0
    strategy.cancel("BUY", window())   // add another window condition which considers day time (working hours)
    strategy.order("BUY", strategy.long, qty, comment="BUY @ "+ tostring(entry_price),when=window())

if short_entry and strategy.position_size == 0
    strategy.cancel("SELL", window()) // add another window condition which considers day time (working hours)
    strategy.order("SELL", strategy.short, qty, comment="SELL @ "+ tostring(entry_price),when=window())

//>>>> exit conditons

tsl_hit_flag     := false

//exit at tsl
if strategy.position_size > 0 and close < tsl_price  and abs(strategy.position_size)!=qty 
    strategy.order("EXIT at TSL", strategy.short, abs(strategy.position_size),  comment="EXIT TSL @ "+ tostring(close))
    RSI_short                := false   
    RSI_long                 := false
    bar_count_long            := 0
    bar_count_short           := 0
    tsl_hit_flag              := true
    cci_sell := false
    cci_buy := false
    strategy.cancel("EXIT 1", true)
    strategy.cancel("EXIT 2", true)
    strategy.cancel("Exit Drawd",true)
    strategy.cancel("EXIT at SL",true)

if strategy.position_size < 0 and close > tsl_price  and abs(strategy.position_size)!=qty 
    strategy.order("EXIT at TSL", strategy.long, abs(strategy.position_size), comment="EXIT TSL @ "+ tostring(close))
    RSI_short                := false   
    RSI_long                 := false
    bar_count_long            := 0
    bar_count_short           := 0   
    tsl_hit_flag              := true
    cci_sell := false
    cci_buy := false
    strategy.cancel("EXIT 1", true)
    strategy.cancel("EXIT 2", true)
    strategy.cancel("Exit Drawd",true)
    strategy.cancel("EXIT at SL",true)

//>>>>exit at sl
    
if strategy.position_size > 0 and original_sl_type == "Close Price" and close < sl_price and abs(strategy.position_size)==qty
    strategy.cancel("EXIT at SL", true)
    strategy.order("EXIT at SL", strategy.short, abs(strategy.position_size),stop= sl_price,  comment="EXIT SL @ "+ tostring(close))
    RSI_short                := false   
    RSI_long                 := false
    bar_count_long            := 0
    bar_count_short           := 0
    cci_buy := false
    cci_sell := false
    sl_hit_flag               := true
    strategy.cancel("EXIT 1", true)
    strategy.cancel("EXIT 2", true)
    strategy.cancel("Exit Drawd",true)
    strategy.cancel("EXIT at TSL",true)
    

if strategy.position_size < 0 and original_sl_type == "Close Price" and close > sl_price and abs(strategy.position_size)==qty
    strategy.cancel("EXIT at SL", true)
    strategy.order("EXIT at SL", strategy.long, abs(strategy.position_size), stop = sl_price, comment="EXIT SL @ "+ tostring(close))
    RSI_short               := false   
    RSI_long                := false
    bar_count_long           := 0
    bar_count_short          := 0   
    cci_buy := false
    cci_sell := false
    sl_hit_flag              := true
    strategy.cancel("EXIT 1", true)
    strategy.cancel("EXIT 2", true)
    strategy.cancel("Exit Drawd",true)
    strategy.cancel("EXIT at TSL",true)
    

    
//>>>>>for ltp sl setting

if strategy.position_size > 0 and original_sl_type == "Last Traded Price" and abs(strategy.position_size) ==qty
    strategy.order("EXIT at SL", strategy.short, abs(strategy.position_size),stop= sl_price,  comment="EXIT SL @ "+ tostring(close))
    RSI_short              := false   
    RSI_long               := false
    bar_count_long          := 0
    bar_count_short         := 0
    cci_buy := false
    cci_sell := false
    strategy.cancel("EXIT 1", true)
    strategy.cancel("EXIT 2", true)
    strategy.cancel("Exit Drawd",true)
    strategy.cancel("EXIT at TSL",true)
    
if strategy.position_size < 0 and original_sl_type == "Last Traded Price" and abs(strategy.position_size) ==qty
    strategy.order("EXIT at SL", strategy.long, abs(strategy.position_size), stop = sl_price, comment="EXIT SL @ "+ tostring(close))
    RSI_short              := false   
    RSI_long               := false
    bar_count_long          := 0
    bar_count_short         := 0   
    cci_buy := false
    cci_sell := false
    strategy.cancel("EXIT 1", true)
    strategy.cancel("EXIT 2", true)
    strategy.cancel("Exit Drawd",true)
    strategy.cancel("EXIT at TSL",true)

//>>>>>exit at target

if strategy.position_size > 0 and abs(strategy.position_size) == qty and not tsl_hit_flag
    strategy.order("EXIT 1", strategy.short, exit_1_qty, limit=exit_1_price, comment="EXIT TG1 @ "+ tostring(exit_1_price))
    strategy.cancel("Exit Drawd",true)
    cci_sell := false
    cci_buy := false

if strategy.position_size > 0 and abs(strategy.position_size) < qty and abs(strategy.position_size) != qty and not tsl_hit_flag
    strategy.order("EXIT 2", strategy.short, exit_2_qty, limit=exit_2_price, comment="EXIT TG2 @ "+ tostring(exit_2_price))
    RSI_short := false   
    RSI_long  := false
    bar_count_long := 0
    bar_count_short := 0
    cci_buy := false
    cci_sell := false
    strategy.cancel("Exit Drawd",true)
    strategy.cancel("EXIT at SL", true)

if strategy.position_size < 0 and abs(strategy.position_size) == qty and not tsl_hit_flag
    strategy.order("EXIT 1", strategy.long, exit_1_qty, limit=exit_1_price, comment="EXIT TG1 @ "+ tostring(exit_1_price))
    strategy.cancel("Exit Drawd",true)
    cci_buy := false
    cci_sell := false

if strategy.position_size < 0 and abs(strategy.position_size) < qty and abs(strategy.position_size) != qty 
    strategy.order("EXIT 2", strategy.long, exit_2_qty, limit=exit_2_price, comment="EXIT TG2 @ "+ tostring(exit_2_price))
    RSI_short := false   
    RSI_long  := false
    bar_count_long := 0
    bar_count_short := 0  
    cci_buy := false
    cci_sell := false
    strategy.cancel("Exit Drawd",true)
    strategy.cancel("EXIT at SL", true)
    
//>>>>>>drawdown execution

if strategy.position_size < 0 and original_sl_type == "Close Price" and not tsl_hit_flag  
    strategy.cancel("Exit Drawd",true)
    strategy.order("Exit Drawd", strategy.long, abs(strategy.position_size), stop= (entry_price + Draw_down*atr_length)  ,comment="Drawdown exit S")
    RSI_short            := false   
    RSI_long             := false
    bar_count_long        := 0
    bar_count_short       := 0
    cci_buy := false
    cci_sell := false
   
    
if strategy.position_size > 0 and original_sl_type == "Close Price" and not tsl_hit_flag and not sl_hit_flag 
    strategy.cancel("Exit Drawd",true)
    strategy.order("Exit Drawd", strategy.short, abs(strategy.position_size), stop= (entry_price - Draw_down*atr_length)  ,comment="Drawdown exit B")
    RSI_short           := false   
    RSI_long            := false
    bar_count_long       := 0
    bar_count_short      := 0
    cci_buy := false
    cci_sell := false
    
//>>>>to add sl hit sign  

if strategy.position_size != 0 and sl_hit_flag //For symbols on chart
    sl_cross := true

//>>>>>cancel all pending orders if the trade is booked

strategy.cancel_all(strategy.position_size == 0 and not (long_entry or short_entry))

//>>>>plot indicators
p_mBB = plot(plotBB ? mBB0 : na, color=color.teal)
p_uBB = plot(plotBB ? uBB0 : na, color=color.teal, style=plot.style_stepline)
p_lBB = plot(plotBB ? lBB0 : na, color=color.teal, style=plot.style_stepline)


plot(sma(close,5), color=color.blue, title="MA")





//>>>>plot signals

plotshape(plotSignals and RSI_short, style=shape.triangledown, location=location.abovebar, color=color.red)
plotshape(plotSignals and RSI_long, style=shape.triangleup, location=location.belowbar, color=color.green)
plotshape(sl_cross, text= "Stoploss Hit",size= size.normal,style=shape.xcross , location=location.belowbar, color=color.red)

//>>>>plot signal high low
if strategy.position_size != 0
    candles_on_trade := candles_on_trade + 1

if strategy.position_size != 0 and candles_on_trade == 1
    line.new(x1=bar_index[1], y1=high[1], x2=bar_index[0], y2=high[1], color=color.black, width=2)
    line.new(x1=bar_index[1], y1=low[1],  x2=bar_index[0], y2=low[1],  color=color.black, width=2)



//>>>>end of program





더 많은