후속 구매 전략

저자:차오장, 날짜: 2023-10-09 14:53:02
태그:

전반적인 설명

트레일링 구매 전략은 트렌드를 따르는 전략이다. 빠른 이동 평균이 느린 이동 평균을 넘을 때 오픈 포지션 신호를 유발한다. 오픈 포지션과 달리이 전략은 오픈 포지션 신호가 발동 된 즉시 시장에 진입하지 않고 가격이 특정 조건에 도달 할 때만 구매 명령을 실행한다. 이것은 전략의 수익을 어느 정도 증가시킬 수 있다.

원칙

이 전략은 두 개의 움직이는 평균을 가진 이동 평균 교차 시스템에 기반합니다. 빠른 이동 평균과 느린 이동 평균은 각각 계산됩니다. 빠른 이동 평균이 느린 이동 평균을 넘을 때 긴 신호가 생성됩니다.

실행 논리는 후속 구매 옵션이 활성화되면 다릅니다.

  1. 롱 신호가 발사되면 직접 구매하는 대신 그 순간 가장 낮은 가격을 기록하세요.

  2. 그 다음 구매 가격의 기준값을 최저 가격인 후속 구매 비율에 따라 계산합니다. * (1 + %)

  3. 다음 바에서 현재 바의 최저 가격을 구매 가격 임계치와 비교합니다.

  4. 가장 낮은 가격이 구매 가격의 문턱을 넘으면 구매 명령을 실행합니다.

  5. 이런 식으로 우리는 추세가 확인된 후에 더 좋은 가격으로 시장에 진출할 수 있습니다.

이점 분석

이 전략의 장점은 다음과 같습니다.

  1. 후속 구매를 사용하면 트렌드가 더 분명해지면 시장에 진입함으로써 잘못된 브레이크업의 위험을 피할 수 있습니다.

  2. 후속 구매를 통해 더 나은 가격을 얻을 수 있으며 어느 정도 수익을 향상시킬 수 있습니다.

  3. 이 전략은 간단하고 실행하기 쉽습니다.

  4. 후속 구매 단계 비율은 사용자 정의 가능하며 전략을 더 유연하게 만듭니다.

  5. 이동 평균 기간은 다른 시장 환경에 적응하도록 사용자 정의 할 수 있습니다.

위험 분석

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

  1. 후속 구매는 약간의 지연을 초래할 수 있고 출입 기회를 놓칠 수 있습니다.

  2. 후속 구매의 비율을 잘못 설정하면 구매가 불가능할 수 있습니다.

  3. 부적절한 이동 평균 기간은 더 많은 잘못된 신호를 생성할 수 있습니다.

  4. 이 전략은 다양한 시장에서 심각한 손실을 입을 수 있습니다.

  5. 이것은 매개 변수 최적화를 위한 공간이 있는 간단한 전략입니다.

이에 따른 조치는:

  1. 후속 구매의 비율을 줄여야 합니다.

  2. 다양한 비율 설정을 테스트하여 최적을 찾습니다.

  3. 시장 적응을 위해 이동 평균 기간을 최적화하십시오.

  4. 다른 필터를 추가해서 시장의 범위를 피합니다.

  5. 손실을 줄이기 위해 스톱 로스를 추가하는 것을 고려하십시오.

최적화 방향

이 전략은 다음과 같은 방향으로 최적화 될 수 있습니다.

  1. 가격과 부피의 불일치를 피하기 위해 클링거와 같은 가격과 부피 지표를 추가합니다.

  2. 부피 조건 판단을 추가하고, 부피가 증가할 때만 구매하세요.

  3. 다양한 상품에 대한 이동 평균 기간을 최적화합니다.

  4. 변동성 지표를 추가하여 범위 영역을 피합니다.

  5. ATR 스톱 손실을 추가합니다.

  6. 점진율을 동적으로 바꾸고, 추세가 더 명백할 때 더 빨리 점진하는 것을 고려하세요.

결론

요약하자면, 후속 구매 전략은 가격을 더 나은 입점으로 추월하여 전략을 개선하면서 간단하게 유지합니다. 그러나이 전략에는 더 많은 시장 상황에 적응하기 위해 추가 최적화가 필요한 일부 위험이 있습니다. 전반적으로이 전략은 양적 거래에 대한 참조 가치가있는 아이디어를 제공합니다.


/*backtest
start: 2023-10-01 00:00:00
end: 2023-10-08 00:00:00
period: 5m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ 
//  -----------------------------------------------------------------------------
//  Copyright 2022 Iason Nikolas | jason5480
//  Trailing Buy script may be freely distributed under the MIT license.
//
//  Permission is hereby granted, free of charge, 
//  to any person obtaining a copy of this software and associated documentation files (the "Software"), 
//  to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, 
//  publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
//  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//  -----------------------------------------------------------------------------
//
//  Authors:  @jason5480
//  Revision: v1.0.0
//  Date:     15-Feb-2022
//
//  Description
//  =============================================================================
//  This strategy will go long if fast MA crosses over slow MA.
//  If the trailing buy is checked then the strategy instead of entering into the position
//  directly it will follow the price downwards (percentagewise) with small steps
//  If the price raise by this percentage then the entry order will be executed
//
//  The strategy has the following parameters:
//
//  Fast SMA Length - How many candles back to calculte the fast SMA.
//  Slow SMA Length - How many candles back to calculte the slow SMA.
//  Enable Trailing - Enable or disable the trailing
//  Training Buy Deviation % - The step to follow the price when the open position condition is met.
//  Source Buy - The price to compare the current buyPrice in order to trigger the buy order when trailing
//  
//  -----------------------------------------------------------------------------
//  Disclaimer:
//    1. I am not licensed financial advisors or broker dealer. I do not tell you 
//       when or what to buy or sell. I developed this software which enables you 
//       execute manual or automated using TradingView. The 
//       software allows you to set the criteria you want for entering and exiting 
//       trades.
//    2. Do not trade with money you cannot afford to lose.
//    3. I do not guarantee consistent profits or that anyone can make money with no 
//       effort. And I am not selling the holy grail.
//    4. Every system can have winning and losing streaks.
//    5. Money management plays a large role in the results of your trading. For 
//       example: lot size, account size, broker leverage, and broker margin call 
//       rules all have an effect on results. Also, your Take Profit and Stop Loss 
//       settings for individual pair trades and for overall account equity have a 
//       major impact on results. If you are new to trading and do not understand 
//       these items, then I recommend you seek education materials to further your
//       knowledge.
//
//    YOU NEED TO FIND AND USE THE TRADING SYSTEM THAT WORKS BEST FOR YOU AND YOUR 
//    TRADING TOLERANCE.
//
//    I HAVE PROVIDED NOTHING MORE THAN A TOOL WITH OPTIONS FOR YOU TO TRADE WITH THIS PROGRAM ON TRADINGVIEW.
//    
//    I accept suggestions to improve the script.
//    If you encounter any problems I will be happy to share with me.
//  -----------------------------------------------------------------------------
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// SETUP ============================================================================================================

strategy(title = 'Trailing Buy',
         shorttitle = 'TB',
         overlay = true,
         pyramiding = 0,
         default_qty_type = strategy.percent_of_equity,
         default_qty_value = 100,
         initial_capital = 100000)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// FILTERS ==========================================================================================================

// INPUT ============================================================================================================
usefromDate = input.bool(defval = true, title = 'From', inline = "From Date", group = "Filters")
fromDate = input(defval = timestamp('01 Jan 2021 00:00 UTC'), title = '', inline = "From Date", group = 'Filters')
usetoDate = input.bool(defval = false, title = 'To ', inline = "To Date", group = "Filters")
toDate = input(defval = timestamp('31 Dec 2121 23:59 UTC'), title = '', inline = "To Date", group = 'Filters')

// LOGIC ============================================================================================================
isWithinPeriod() => true

// PLOT =============================================================================================================
bgcolor(color = isWithinPeriod() ? color.new(color.gray, 90) : na, title = 'Period')

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// STRATEGY =========================================================================================================

// INPUT ============================================================================================================
fastMALen = input.int(defval = 21, title = 'Fast/Slow SMA Length', inline = 'MA Length', group = 'Strategy')
slowMALen = input.int(defval = 49, title = '', tooltip = 'How many candles back to calculte the fast/slow SMA.', inline = 'MA Length', group = 'Strategy')

// LOGIC ============================================================================================================
fastMA = ta.sma(close, fastMALen)
slowMA = ta.sma(close, slowMALen)

bool openLongPosition = isWithinPeriod() and ta.crossover(fastMA, slowMA)
bool closeLongPosition = ta.crossunder(fastMA, slowMA)

bool longIsActive = openLongPosition or strategy.position_size > 0

// PLOT =============================================================================================================
var fastColor = color.new(#0056BD, 0)
plot(series = fastMA, title = 'Fast SMA', color = fastColor, linewidth = 1, style = plot.style_line)
var slowColor = color.new(#FF6A00, 0)
plot(series = slowMA, title = 'Slow SMA', color = slowColor, linewidth = 1, style = plot.style_line)

plotshape(series = openLongPosition and strategy.position_size <= 0 ? fastMA : na, title = 'Buy', text = 'Buy', style = shape.labelup, location = location.absolute, color = color.new(color.green, 0), textcolor = color.new(color.white, 0), size = size.tiny)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// BUY ==============================================================================================================

// INPUT ============================================================================================================
enableTrailing = input.bool(defval = true, title = 'Enable Trailing', tooltip = 'Enable or disable the trailing for buy.', group = 'Buy')
trailingBuyDeviationPerc = input.float(defval = 4.0, title = 'Trailing Buy Deviation %', minval = 0.01, maxval = 100, step = 0.05, tooltip = 'The step to follow the price when the open position condition is met.', group = 'Buy') / 100
srcBuy = input.source(defval = high, title = 'Source Buy', tooltip = 'The price to check to trigger the buy order', group = 'Buy')

// LOGIC ============================================================================================================
int barsSinceOpenLong = nz(ta.barssince(openLongPosition), 999999)
int barsSinceCloseLong = nz(ta.barssince(closeLongPosition), 999999)
bool tryOpenLongPosition = isWithinPeriod() and barsSinceCloseLong >= barsSinceOpenLong and not (strategy.position_size > 0)

float longBuyPrice = na
longBuyPrice := if openLongPosition and not (strategy.position_size > 0)
    low * (1 + trailingBuyDeviationPerc)
else if tryOpenLongPosition
    math.min(low * (1 + trailingBuyDeviationPerc), nz(longBuyPrice[1], 999999))
else
    na

bool executeLongPosition = enableTrailing ? isWithinPeriod() and srcBuy > longBuyPrice : openLongPosition

// PLOT =============================================================================================================
var buyColor = color.new(#419388, 0)
plot(series = enableTrailing ? longBuyPrice : na, title = 'Long Buy Price', color = buyColor, linewidth = 1, style = plot.style_linebr, offset = 1)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// POSITION ORDERS ==================================================================================================

// LOGIC ============================================================================================================
// getting into LONG position
strategy.entry(id = 'Long Entry', direction = strategy.long, when = executeLongPosition, alert_message = 'Long(' + syminfo.ticker + '): Started')
// submit close order on trend reversal
strategy.close(id = 'Long Entry', when = closeLongPosition, comment = 'Close Long', alert_message = 'Long(' + syminfo.ticker + '): Closed at market price')

// PLOT =============================================================================================================
var posColor = color.new(color.white, 0)
plot(series = strategy.position_avg_price, title = 'Position', color = posColor, linewidth = 1, style = plot.style_linebr)

// ==================================================================================================================

더 많은