수량화 된 점진적으로 가중화된 DCA 거래 전략

저자:차오장, 날짜: 2023-11-16 11:32:12
태그:

img

전반적인 설명

정량화된 점진적 가중화 DCA 거래 전략은 신호 발생을 위한 이동 평균 지표와 점진적 가중화 달러 비용 평균화 메커니즘을 결합한 양적 거래 전략이다. 이 전략은 트렌드 식별과 비용 평균화로 강하게 유행하는 시장에서 상대적으로 안정적인 수익을 달성하는 것을 목표로 한다.

원칙

이 전략은 세 가지 주요 구성 요소로 구성됩니다.

  1. 입력 신호 판단

    이 매개시스템은 빠른 매개시스템과 느린 매개시스템의 크로스오버를 입력 신호로 사용한다. 사용자는 빠른 매개시스템과 느린 매개시스템의 크로스오버를 선택할 수 있다. 빠른 매개시스템이 느린 매개시스템보다 높을 때 구매 신호가 생성된다. 빠른 매개시스템이 느린 매개시스템보다 낮을 넘을 때 판매 신호가 생성된다.

  2. 점진적으로 가중된 DCA

    매수 신호를 받은 후, 전략은 즉시 기본 포지션을 열게 된다. 가격이 계속 하락함에 따라, 전략은 추가적인 안전 포지션의 크기를 가중된 방식으로 점차적으로 증가시킬 것이다. 각 새로운 안전 포지션의 가격은 이전과 비교하여 고정된 비율로 낮아질 것이다. 또한, 각 새로운 안전 포지션에 할당된 자금은 요인으로 증폭될 것이다.

    포지션 크기의 이러한 점진적 증가는 비용 평균의 한 형태를 허용하여 위험을 통제하면서 더 나은 평균 비용을 얻을 수 있습니다.

  3. 이윤을 취하고 손실을 중지합니다.

    가격이 이윤 라인을 넘어서면 전략은 이윤을 위해 포지션을 닫습니다. 가격이 스톱 로스 라인을 넘어서면 전략은 손실을 통제하기 위해 포지션을 종료합니다.

    영업이익 라인은 기본 위치 평균 가격 * (1 + 고정 비율) 에 고정됩니다.

    스톱 로스 라인은 마지막 안전 포지션 가격에 따라 변동하며 그 아래의 고정 비율입니다.

장점

  1. 추세와 비용 평균을 결합하면 더 안정적입니다.

    트렌드를 이용하면 무의미한 문제들을 피할 수 있고, 평균적인 비용으로 더 좋은 입시 비용을 얻을 수 있습니다.

  2. 점진적인 위치 크기는 위험을 제어합니다.

    안전 위치 크기의 고정 증폭, 재입구 문턱은 위험을 통제합니다.

  3. 사용된 자금의 실시간 모니터링

    통합된 잔액 사용 지표는 과잉 제약과 강제 청산을 방지합니다.

  4. 각 포지션에 대해 별도의 TP/SL

    독립적인 출구는 이익을 확보하고 손실을 줄일 수 있습니다.

위험 과 개선

  1. 가격 위프사는 여러 안전 주문을 유발할 수 있습니다

    극심한 변동성에서는 여러 가지 불필요한 안전 주문이 추가되어 손실을 증가시킬 수 있습니다. 안전 주문 재입구 문턱을 최적화 할 수 있습니다.

  2. 이동 평균 매개 변수는 최적화 필요

    각기 다른 기기들은 다른 이동 평균 기간을 필요로 합니다.

  3. TP/SL 수준은 백테스트 최적화가 필요합니다.

    TP/SL 비율은 위험/이익 프로파일을 결정합니다. 최적 수준은 다양합니다.

  4. 최대 유출량 또는 유지 시간 기준 강제 출출출을 추가합니다.

    위험을 더 제한하기 위해 마감 또는 유지 시간을 기반으로 강제 출구를 통합하여 테스트 할 수 있습니다.

요약

정량화된 점진적 가중화 DCA 거래 전략은 트렌드 거래와 비용 평균화의 장점을 결합하여 강력한 트렌드에서 안정적인 수익을 창출합니다. 최적화된 매개 변수, 포지션 사이즈 및 재입구 문턱으로 제어된 위험에 안정적인 거래를 달성 할 수 있습니다. 헤지 펀드, CTA 및 시장 중립 전략에 적용됩니다.


/*backtest
start: 2022-11-09 00:00:00
end: 2023-11-15 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/
// © MGTG

//@version=5
Strategy = input.string('Long', options=['Long'], group='Strategy', inline='1',
 tooltip='Long bots profit when asset prices rise, Short bots profit when asset prices fall'
 + '\n\n' + 'Please note: to run a Short bot on a spot exchange account, you need to own the asset you want to trade. The bot will sell the asset at the current chart price and buy it back at a lower price - the profit made is actually trapped equity released from an asset you own that is declining in value.')

Profit_currency = input.string('Quote (USDT)', 'Profit currency', options=['Quote (USDT)', 'Quote (BTC)', 'Quote (BUSD)'], group='Strategy', inline='1')
Base_order_size = input.int(10, 'Base order Size', group='Strategy', inline='2', 
 tooltip='The Base Order is the first order the bot will create when starting a new deal.')
Safety_order_size = input.int(20, 'Safety order Size', group='Strategy', inline='2',
 tooltip="Enter the amount of funds your Safety Orders will use to Average the cost of the asset being traded, this can help your bot to close deals faster with more profit. Safety Orders are also known as Dollar Cost Averaging and help when prices moves in the opposite direction to your bot's take profit target.")

Triger_Type = input.string('Over', 'Entry at Cross Over / Under', options=['Over', 'Under'], group='Deal start condition > Trading View custom signal', inline='1',
 tooltip='Deal start condition decision')

Short_Moving_Average  = input.string('SMA', 'Short Moving Average', group='Deal start condition > Trading View custom signal', inline='2',
 options=["SMA", "EMA", "HMA"])
Short_Period         = input.int(5, 'Period', group='Deal start condition > Trading View custom signal', inline='2')
Long_Moving_Average  = input.string('HMA', 'Long Moving Average', group='Deal start condition > Trading View custom signal', inline='3',
 options=["SMA", "EMA", "HMA"])

Long_Period          = input.int(50, 'Period', group='Deal start condition > Trading View custom signal', inline='3')

Target_profit = input.float(1.5, 'Target profit (%)', step=0.05, group='Take profit / Stop Loss', inline='1') * 0.01
Stop_Loss = input.int(15, 'Stop Loss (%)', group='Take profit / Stop Loss', inline='1',
 tooltip='This is the percentage that price needs to move in the opposite direction to your take profit target, at which point the bot will execute a Market Order on the exchange account to close the deal for a smaller loss than keeping the deal open.'
 + '\n' + 'Please note, the Stop Loss is calculated from the price the Safety Order at on the exchange account and not the Dollar Cost Average price.') * 0.01

Max_safety_trades_count = input.int(10, 'Max safety trades count', maxval=10, group='Safety orders', inline='1')
Price_deviation = input.float(0.4, 'Price deviation to open safety orders (% from initial order)', step=0.01, group='Safety orders', inline='2') * 0.01
Safety_order_volume_scale = input.float(1.8, 'Safety order volume scale', step=0.01, group='Safety orders', inline='3')
Safety_order_step_scale = input.float(1.19, 'Safety order step scale', step=0.01, group='Safety orders', inline='3')

// daily_volume  = input.int(500, "Don't start deal(s) if the daily volume is less than", group='Advanced settings', inline='1')
// Minimum_price  = input.int(500, "Minimum price to open deal", group='Advanced settings', inline='1')
// Maximum_price  = input.int(500, "Maximum price to open deal", group='Advanced settings', inline='1')

// Close_deal_after_timeout  = input.int(5, "Close deal after timeout (Hrs)", group='Advanced settings', inline='1')

initial_capital = 8913

strategy(
 title='3Commas Visible DCA Strategy', 
 overlay=true, 
 initial_capital=initial_capital, 
 pyramiding=11, 
 process_orders_on_close=true, 
 commission_type=strategy.commission.percent, 
 commission_value=0.01, 
 max_bars_back=5000, 
 max_labels_count=50)


// Position
status_none  = strategy.position_size == 0
status_long  = strategy.position_size[1] == 0 and strategy.position_size > 0
status_long_offset  = strategy.position_size[2] == 0 and strategy.position_size[1] > 0
status_short = strategy.position_size[1] == 0 and strategy.position_size < 0
status_increase = strategy.opentrades[1] < strategy.opentrades

Short_Moving_Average_Line = 
 Short_Moving_Average == 'SMA' ? ta.sma(close, Short_Period) :
 Short_Moving_Average == 'EMA' ? ta.ema(close, Short_Period) :
 Short_Moving_Average == 'HMA' ? ta.sma(close, Short_Period) : na

Long_Moving_Average_Line = 
 Long_Moving_Average == 'SMA' ? ta.sma(close, Long_Period) :
 Long_Moving_Average == 'EMA' ? ta.ema(close, Long_Period) :
 Long_Moving_Average == 'HMA' ? ta.sma(close, Long_Period) : na
 
Base_order_Condition      = Triger_Type == "Over" ? ta.crossover(Short_Moving_Average_Line, Long_Moving_Average_Line) : ta.crossunder(Short_Moving_Average_Line, Long_Moving_Average_Line) // Buy when close crossing lower band

safety_order_deviation(index) => Price_deviation * math.pow(Safety_order_step_scale,  index - 1)

pd = Price_deviation
ss = Safety_order_step_scale

step(i) =>
 i == 1 ? pd :
 i == 2 ? pd + pd * ss :
 i == 3 ? pd + (pd + pd * ss) * ss :
 i == 4 ? pd + (pd + (pd + pd * ss) * ss) * ss : 
 i == 5 ? pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss : 
 i == 6 ? pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss : 
 i == 7 ? pd + (pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss) * ss : 
 i == 8 ? pd + (pd + (pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss) * ss) * ss : 
 i == 9 ? pd + (pd + (pd + (pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss) * ss) * ss) * ss : 
 i == 10 ? pd + (pd + (pd + (pd + (pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss) * ss) * ss) * ss) * ss : na

long_line(i) =>
 close[1] - close[1] * (step(i))


Safe_order_line(i) =>
 i == 0 ? ta.valuewhen(status_long, long_line(0), 0) :
 i == 1 ? ta.valuewhen(status_long, long_line(1), 0) :
 i == 2 ? ta.valuewhen(status_long, long_line(2), 0) :
 i == 3 ? ta.valuewhen(status_long, long_line(3), 0) :
 i == 4 ? ta.valuewhen(status_long, long_line(4), 0) :
 i == 5 ? ta.valuewhen(status_long, long_line(5), 0) :
 i == 6 ? ta.valuewhen(status_long, long_line(6), 0) :
 i == 7 ? ta.valuewhen(status_long, long_line(7), 0) :
 i == 8 ? ta.valuewhen(status_long, long_line(8), 0) : 
 i == 9 ? ta.valuewhen(status_long, long_line(9), 0) :
 i == 10 ? ta.valuewhen(status_long, long_line(10), 0) : na

TP_line = strategy.position_avg_price * (1 + Target_profit) 

SL_line = Safe_order_line(Max_safety_trades_count) * (1 - Stop_Loss)

safety_order_size(i) => Safety_order_size * math.pow(Safety_order_volume_scale, i - 1)


plot(Short_Moving_Average_Line, 'Short MA', color=color.new(color.white, 0), style=plot.style_line)
plot(Long_Moving_Average_Line, 'Long MA', color=color.new(color.green, 0), style=plot.style_line)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 1 ? Safe_order_line(1) : na, 'Safety order1', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 2 ? Safe_order_line(2) : na, 'Safety order2', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 3 ? Safe_order_line(3) : na, 'Safety order3', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 4 ? Safe_order_line(4) : na, 'Safety order4', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 5 ? Safe_order_line(5) : na, 'Safety order5', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 6 ? Safe_order_line(6) : na, 'Safety order6', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 7 ? Safe_order_line(7) : na, 'Safety order7', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 8 ? Safe_order_line(8) : na, 'Safety order8', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 9 ? Safe_order_line(9) : na, 'Safety order9', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 10 ? Safe_order_line(10) : na, 'Safety order10', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? TP_line : na, 'Take Profit', color=color.new(color.orange, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? SL_line : na, 'Safety', color=color.new(color.aqua, 0), style=plot.style_linebr)


currency = 
 Profit_currency == 'Quote (USDT)' ? ' USDT' :
 Profit_currency == 'Quote (BTC)'  ? ' BTC' :
 Profit_currency == 'Quote (BUSD)' ? ' BUSD' : na
 

if Base_order_Condition
    strategy.entry('Base order', strategy.long, qty=Base_order_size/close, when=Base_order_Condition and strategy.opentrades == 0,
     comment='BO' + ' - ' + str.tostring(Base_order_size) + str.tostring(currency))

for i = 1 to Max_safety_trades_count by 1
    i_s = str.tostring(i)
    strategy.entry('Safety order' + i_s, strategy.long, qty=safety_order_size(i)/close,
     limit=Safe_order_line(i), when=(strategy.opentrades <= i) and strategy.position_size > 0, 
     comment='SO' + i_s + ' - ' + str.tostring(safety_order_size(i))  + str.tostring(currency))


for i = 1 to Max_safety_trades_count by 1
    i_s = str.tostring(i)
    // strategy.close('Base order', when=shortCondition)
    // strategy.close('Safety order' + i_s, when=shortCondition)
    // strategy.cancel('Safety order' + i_s, when=shortCondition)
    strategy.cancel('SO' + i_s, when=ta.crossunder(low, SL_line) or ta.crossover(high, TP_line) or status_none)
    strategy.exit('TP/SL','Base order', limit=TP_line, stop=SL_line, comment = Safe_order_line(100) > close ? 'SL' + i_s + ' - ' +  str.tostring(Base_order_size) + str.tostring(currency) : 'TP' + i_s + ' - ' +  str.tostring(Base_order_size) + str.tostring(currency)) 
    strategy.exit('TP/SL','Safety order' + i_s, limit=TP_line, stop=SL_line, comment = Safe_order_line(100) > close ? 'SL' + i_s + ' - ' +  str.tostring(safety_order_size(i)) + str.tostring(currency) : 'TP' + i_s + ' - ' +  str.tostring(safety_order_size(i)) + str.tostring(currency)) 
    // strategy.cancel('TP/SP' + i_s, when=Base_order_Condition)
    // strategy.exit('Stop Loss','Base order', stop=SL_line)
    // strategy.exit('Stop Loss','Safety order' + i_s, stop=SL_line)
    
//----------------label A----------------//

bot_usage(i) =>
 i == 1 ? Base_order_size + safety_order_size(1) :
 i == 2 ? Base_order_size + safety_order_size(1) + safety_order_size(2) :
 i == 3 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) :
 i == 4 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) : 
 i == 5 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) :
 i == 6 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) : 
 i == 7 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) + safety_order_size(7) : 
 i == 8 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) + safety_order_size(7) + safety_order_size(8) : 
 i == 9 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) + safety_order_size(7) + safety_order_size(8) + safety_order_size(9) :
 i == 10 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) + safety_order_size(7) + safety_order_size(8) + safety_order_size(9) + safety_order_size(10) : na

equity = strategy.equity
bot_use = bot_usage(Max_safety_trades_count)
bot_dev = float(step(Max_safety_trades_count)) * 100
bot_ava = (bot_use / equity) * 100

string label_A = 
 'Balance                                      : ' + str.tostring(math.round(equity, 0), '###,###,###,###') + ' USDT' + '\n' + 
 'Max amount for bot usage           : ' + str.tostring(math.round(bot_use, 0), '###,###,###,###') + ' USDT' + '\n' + 
 'Max safety order price deviation : ' + str.tostring(math.round(bot_dev, 0), '##.##') + ' %' + '\n' + 
 '% of available balance                : ' + str.tostring(math.round(bot_ava, 0), '###,###,###,###') + ' %' 
 + (bot_ava > 100 ? '\n \n' +  '⚠ Warning! Bot will use amount greater than you have on exchange' : na) 


if status_long
    day_label = 
     label.new(
     x=time[1], 
     y=high * 1.03, 
     text=label_A, 
     xloc=xloc.bar_time, 
     yloc=yloc.price, 
     color=bot_ava > 100 ? color.new(color.yellow, 0) : color.new(color.black, 50), 
     style=label.style_label_lower_right, 
     textcolor=bot_ava > 100 ? color.new(color.red, 0) : color.new(color.silver, 0), 
     size=size.normal, 
     textalign=text.align_left)

더 많은