동적 가격 오실레이터 추세 전략


생성 날짜: 2023-11-23 10:45:02 마지막으로 수정됨: 2023-11-23 10:45:02
복사: 1 클릭수: 588
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

동적 가격 오실레이터 추세 전략

개요

동적 가격 스윙 (Dynamic Price Swing) 은 가격 트렌드를 식별하기 위한 전략이다. 그것은 이동 평균, 가격 통로 및 피보나치 회전을 결합하여 동적 입출력을 구현한다. 이 전략의 장점은 가격 트렌드의 변화를 식별하고, 유연한 동작을 가능하게 하는 데 있다.

전략 원칙

이 전략은 다음과 같은 몇 가지 원칙에 기초하고 있습니다.

  1. 반전 거래를 방지하기 위해 빠른 EMA와 느린 EMA를 사용하여 가격 추세 방향을 판단하십시오.

  2. 가격 상부 하위 채널을 사용하여 브레이크 신호를 판단합니다. 가격이 상부 하위 채널을 뚫을 때 공백을 만들고, 하부 하위 채널을 뚫을 때 더 많이합니다.

  3. 이동 평균의 교차를 사용하여 판단 신호, 골드 포크가 더 많은 것을하고, 죽은 포크가 빈 것을합니다.

  4. 피포나치 회귀선을 판단 신호로 사용하며, 가격이 피포나치 상한선을 돌파할 때 공백을 하고, 피포나치 하한선을 돌파할 때 더 많이 한다.

이 지표에 따라 판단 후 경기장에 들어가서, 스톱 손실, 스톱 탈퇴 메커니즘을 설정한다.

우위 분석

이 전략은 여러 지표 판단을 결합하여 가격 경향의 변화를 식별할 수 있습니다. 이것이 그것의 가장 큰 장점입니다. 주요 장점은 다음과 같습니다:

  1. 빠른 EMA를 사용하여 큰 트렌드를 판단하고 역대 거래를 방지하여 손실을 줄일 수 있습니다.
  2. 가격 통로 판단은 가격 돌파 기회를 얻을 수 있으며 수익 잠재력이 높습니다.
  3. 이동 평균의 크로스 판단은 간단하고 실용적이며 쉽게 실행할 수 있습니다.
  4. 피보나치 후퇴는 전략의 세 가지 측면을 더하는 판단 방식을 추가했습니다.

위험 분석

이 전략에는 몇 가지 위험도 있습니다.

  1. 빠른 EMA와 느린 EMA 파라미터를 잘못 설정하면 판단 오류가 발생할 수 있습니다.
  2. 가격 상하계통을 뚫는 시점을 잘못 선택하면 손해배상 청구서를 받을 수 있습니다.
  3. 이동 평균의 교차는 신중해야 합니다.
  4. Fibonacci Reversal Bandwidth 설정이 잘못되면 판단에 영향을 미칠 수 있습니다.

이러한 위험은 변수 최적화를 통해 감소시킬 수 있습니다.

최적화 방향

이 전략에는 몇 가지 개선이 있습니다.

  1. EMA 주기, 채널 폭, 이동 평균 주기 등의 파라미터를 테스트 및 최적화
  2. RSI, 브린 띠와 같은 다른 기술 지표 판단 규칙을 추가합니다.
  3. OBV와 같은 거래량 에너지 지표와 함께 돌파구를 판단하는 신뢰성
  4. 기계 학습과 같은 기술을 사용하여 최적의 변수를 자동으로 찾아내는 방법

요약하다

다이내믹 가격 오징어는 매우 유연하고 다변적인 전략이다. 가격 변화에 동적으로 적응할 수 있고, 여러 지표를 통해 돌파구를 판단하고 거래한다. 위험도 있지만, 지속적인 최적화를 통해 위험을 줄이고, 전략의 안정성과 수익성을 높일 수 있다. 이 전략은 깊이 있는 연구를 할 가치가 있다.

전략 소스 코드
/*backtest
start: 2023-11-15 00:00:00
end: 2023-11-22 00:00:00
period: 1m
basePeriod: 1m
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/
//@version=4

// ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗██████╗     ██████╗ ██╗   ██╗    
//██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗    ██╔══██╗╚██╗ ██╔╝                       
//██║     ██████╔╝█████╗  ███████║   ██║   █████╗  ██║  ██║    ██████╔╝ ╚████╔╝                        
//██║     ██╔══██╗██╔══╝  ██╔══██║   ██║   ██╔══╝  ██║  ██║    ██╔══██╗  ╚██╔╝                         
//╚██████╗██║  ██║███████╗██║  ██║   ██║   ███████╗██████╔╝    ██████╔╝   ██║                          
// ╚═════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═════╝     ╚═════╝    ╚═╝                          
                                                                                                     
//███████╗ ██████╗ ██╗     ██╗   ██╗████████╗██╗ ██████╗ ███╗   ██╗███████╗ ██╗ █████╗ ███████╗ █████╗ 
//██╔════╝██╔═══██╗██║     ██║   ██║╚══██╔══╝██║██╔═══██╗████╗  ██║██╔════╝███║██╔══██╗╚════██║██╔══██╗
//███████╗██║   ██║██║     ██║   ██║   ██║   ██║██║   ██║██╔██╗ ██║███████╗╚██║╚██████║    ██╔╝╚█████╔╝
//╚════██║██║   ██║██║     ██║   ██║   ██║   ██║██║   ██║██║╚██╗██║╚════██║ ██║ ╚═══██║   ██╔╝ ██╔══██╗
//███████║╚██████╔╝███████╗╚██████╔╝   ██║   ██║╚██████╔╝██║ ╚████║███████║ ██║ █████╔╝   ██║  ╚█████╔╝
//╚══════╝ ╚═════╝ ╚══════╝ ╚═════╝    ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝╚══════╝ ╚═╝ ╚════╝    ╚═╝   ╚════╝ 
                                                                                                     

strategy(shorttitle='DPS',title='Dynamic Price Swing', overlay=true, scale=scale.left, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.18, calc_on_every_tick=true)


// -----------------  Strategy Inputs -------------------------------------------------------------
//Backtest dates with auto finish date of today
start = input(defval = timestamp("22 June 2021 00:00 -0500"), title = "Start Time")
finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time")
window()  => true       // create function "within window of time"

// Strategy Selection - Long, Short, or Both
stratinfo = input(true, "Long/Short for Mixed Market, Long for Bull, Short for Bear")
strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"])
strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1

// Risk Management Inputs
sl= input(10.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01)
stoploss = sl/100
tp = input(20.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01)
TargetProfit = tp/100
ld = input(2, "Stop Trading After This Many Losing Days", type=input.integer, minval=0, maxval=100, step=1)
// strategy.risk.max_cons_loss_days(count=ld)
ml = input(10, "Maximum % of Equity Lost to Halt Trading", type=input.integer, minval=1, maxval=100, step=1)
// strategy.risk.max_drawdown(value=ml, type=strategy.percent_of_equity)

// Price Movement Inputs
PriceInfo = input(true, "Number of bars to look back on to calculate price swings.")
lkbk = input(5,"Max Lookback Period")
high_source = input(high,"High Source")
low_source= input(low,"Low Source")

// Trend Inputs
TrendInfo = input(true, "Trend uses Fast and Slow EMA to prevent going the wrong direction")
length = input(14, "RSI Length", minval=1)
fastLength = input(12, minval=1, title="EMA Fast Length")
slowLength = input(26, minval=1, title="EMA Slow Length")

// Trigger Selection
usePrice = input(true, "Use Average Price Channel Only")
useMA = input(false, "Use Price Moving Average Only")
useFib = input(false, "Use Price Fibonacci Average Only")


// Trend Direction Calculation
rsi_ema = ema(rsi(close, length), length)
emaA = ema(rsi_ema, fastLength)                                     
emaFast = 2 * emaA - ema(emaA, fastLength)
emaB = ema(rsi_ema, slowLength)                                     
emaSlow = 2 * emaB - ema(emaB, slowLength) 


bullishRule =emaFast > emaSlow and rsi_ema >=rsi_ema[1]
bearishRule =emaFast < emaSlow and rsi_ema <= rsi_ema[1]


// Price Channel

lasthigh = highest(high_source, lkbk)
lastlow = lowest(low_source, lkbk)


// Fibonacci and Moving Average
MA1 = sma(close,5),HA1 = sma(high,5),LA1 = sma(low,5),
MA2 = sma(close,8),HA2 = sma(high,8),LA2 = sma(low,8),
MA3 = sma(close,13),HA3 = sma(high,13),LA3 = sma(low,13),
MA4 = sma(close,21),HA4 = sma(high,21),LA4 = sma(low,21),
MA5 = sma(close,34),HA5 = sma(high,34),LA5 = sma(low,34),
MA6 = sma(close,55),HA6 = sma(high,55),LA6 = sma(low,55),
MA7 = sma(close,89),HA7 = sma(high,89),LA7 = sma(low,89),

CMA = (MA1+MA2+MA3+MA4+MA5+MA6+MA7)/7,
HMA = (HA1+HA2+HA3+HA4+HA5+HA6+HA7)/7,
HMA2 = CMA + (atr(lkbk)*1.618)

LMA = (LA1+LA2+LA3+LA4+LA5+LA6+LA7)/7,
LMA2 = CMA - (atr(lkbk)*1.618)


plot(CMA, title="CMA", color=color.new(#00ffaa, 70), linewidth=2)
plot(HMA, title="HMA", color=color.maroon, linewidth=2)
plot(HMA2, title="HMA Fib", color=color.red, linewidth=3)
plot(LMA, title="LMA", color=color.green, linewidth=2)
plot(LMA2, title="LMA Fib", color=color.teal, linewidth=3)

    

// -------------------------------- Entry and Exit Logic ------------------------------------

// Entry Logic

Channel_Sell = close >= lasthigh[1] and bearishRule and window()
Channel_Buy =  close <= lastlow[1] and bullishRule and window()

MA_Sell = high>HMA and window()
MA_Buy = low<LMA and window()

Fib_Sell = high>HMA2 and window()
Fib_Buy = low<LMA2 and window()

qty = strategy.equity/close


// Strategy Entry and Exit with built in Risk Management
if(strategy.opentrades==0 and strat_val>-1)
    GoLong = usePrice ? Channel_Buy : useMA ? MA_Buy : useFib ? Fib_Buy : false
    if (GoLong)
        strategy.entry("LONG", strategy.long, qty)

if(strategy.opentrades==0 and strat_val<1)
    GoShort = usePrice ? Channel_Sell : useMA ? MA_Sell : useFib ? Fib_Sell : false
    if (GoShort) 
        strategy.entry("SHORT", strategy.short, qty)


longStopPrice  = strategy.position_avg_price * (1 - stoploss)
longTakePrice  = strategy.position_avg_price * (1 + TargetProfit)
shortStopPrice = strategy.position_avg_price * (1 + stoploss)
shortTakePrice = strategy.position_avg_price * (1 - TargetProfit)

if (strategy.position_size > 0)
    strategy.exit(id="Exit Long", from_entry = "LONG", stop = longStopPrice, limit = longTakePrice)
    
if (strategy.position_size < 0)
    strategy.exit(id="Exit Short", from_entry = "SHORT", stop = shortStopPrice, limit = shortTakePrice)

CloseShort= usePrice ? Channel_Buy : useMA ? MA_Buy : useFib ? Fib_Buy : false
CloseLong = usePrice ? Channel_Sell : useMA ? MA_Sell : useFib ? Fib_Sell : false

if(CloseLong and strategy.position_size > 0)
    strategy.close("LONG")
        

if(CloseShort and strategy.position_size < 0)
    strategy.close("SHORT")