볼링거 밴드 자동 거래 전략

저자:차오장, 날짜: 2023-09-10 21:50:44
태그:

어떻게 작동 합니까?

이 전략은 짧은 기간과 긴 기간의 간단한 이동 평균 (SMA) 과 볼링거 밴드를 결합하여 거래 기회를 식별합니다. 가격이 하위 밴드 아래로 닫을 때 긴 포지션을 입력합니다.

초기 거래 규모는 고정되어 있지만 후속 안전 주문은 사용자가 정의한 비율에 따라 확장됩니다. 수익 취득 및 중지 손실 수준은 목표 비율을 사용하여 평균 입시 가격을 추적합니다.

이점

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

볼링거 밴드 (Bollinger Band) 브레이크에 기반한 자동 거래 최적화를 위한 유연한 입력 매개 변수 안전 명령어를 사용하여 위치 크기를 측정합니다. 3Commas 거래 로봇으로 구현 위험성

고려해야 할 잠재적 위험:

변동성이 증가할 때 지연된 파업 신호 피라미드 위치에서 노출 증가 스톱 로스는 빠르게 움직이는 시장에서 뒤쳐질 수 있습니다. 이 전략은 추세의 지속을 활용하는 것을 목표로 합니다. 하락세를 제한하기 위해 적절한 스톱 로스 및 리스크 관리가 필요합니다.


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

//@version=4
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tedwardd

// This strategy is intended to help users of the 3commas.io platform backtest bot performance based on a Bollinger Strategy.
// It can also be used to signal a bot to open a deal by providing the Bot ID, email token and trading pair in the strategy settings screen.
// As currently written, this strategy uses a basic Bollinger Band strategy, recommening a deal start when the closing price crosses under the lower band.
// The thick thick red line plotted on the chart shows the average entry price of the current deal.

// strategy("3Commas Bollinger Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=100, initial_capital=1000, currency="USD", commission_value=0.1)


// USER INPUTS
sma_short_val           = input(title="Short MA Window", defval=20)
sma_long_val            = input(title="Long MA Window", defval=100)
ubOffset                = input(title="Upper Band Offset", defval=2.5, step=0.5)
lbOffset                = input(title="Lower Band Offset", defval=2.5, step=0.5)
stoploss_input          = input(title="Long Stop Loss (%)", minval=0, step=1, defval=15) * 0.01
takeprofit_input        = input(title="Long Take Profit (%)", minval=0, step=1, defval=1.4) * 0.01
initial_deviation_input = input(title="Initial SO Deviation (%)", minval=0, step=0.01, defval=0.8) * 0.01
volume_scale            = input(title="Safety Order Vol Step (%)", minval=0.00, step=0.01, defval=1.55)
plotlines               = input(title="Enable/Disable visual lines", type=input.bool, defval=true)

// 3Commas Bot settinsg
bot_id      = input(title="3Commas Bot ID", defval="")
email_token = input(title="Bot Email Token", defval="")
bot_pair    = input(title="3Commas Bot Trading Pair", defval="")

// Backtesting Date Ranges
startDate  = input(title="Start Date", defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", defval=1, minval=1, maxval=12)
startYear  = input(title="Start Year", defval=2016, minval=1800, maxval=2100)
endDate    = input(title="End Date", defval=31, minval=1, maxval=31)
endMonth   = input(title="End Month", defval=12, minval=1, maxval=12)
endYear    = input(title="End Year", defval=2022, minval=1800, maxval=2100)

// VARS
short_sma        = sma(close, sma_short_val-5)
long_sma         = sma(close, sma_long_val)
stdDev           = stdev(close, sma_short_val)
upperBand        = short_sma + (stdDev * ubOffset)
lowerBand        = short_sma - (stdDev * lbOffset)
stoploss_value   = strategy.position_avg_price * (1 - stoploss_input)
takeprofit_value = strategy.position_avg_price * (1 + takeprofit_input)
initial_dev_val  = strategy.position_avg_price * (1 - initial_deviation_input)
inDateRange      = true


initial_deviation = close < initial_dev_val

// Market Conditions
goodBuy    = crossunder(close, lowerBand) // Buy when close crossing under lower band
safety     = initial_deviation and (1-(close/strategy.position_avg_price))/.01 > strategy.opentrades * 1.55 and strategy.opentrades <= 6 // SO when price deviates below SO threshold %
stoploss   = close <= stoploss_value // Stoploss condition - true if closing price for current bar drops below stoploss %
takeprofit = close >= takeprofit_value // Take profit condition - true if closing price for current bar is >= take profit percentage

// goodSell is currently unused for any practical purpose. If you wish to try it, switch these two values. 
// Doing so will make sell suggestions at high crossover upper bollinger but it does not trigger the bot to sell as written but may affect backtest results
//goodSell = crossover(high, upperBand)
goodSell   = false

// Plot some lines
plot(short_sma, color=color.green)
plot(upperBand)
plot(lowerBand, color=color.yellow)
plot(strategy.position_avg_price, color=color.red, linewidth=3)


// Webhook message. Defaults to string. To signal 3c bot, fill in bot_id and email_token in user settings
var enter_msg = "Enter Position"
var exit_msg = "Exit Position"
var close_all = "Exit Position"
if bot_id != "" and email_token != ""
    enter_msg := '{"message_type": "bot",  "bot_id": ' + bot_id + ',  "email_token": "' + email_token + '", "delay_seconds": 0, "pair": "' + bot_pair + '"}'
    exit_msg := '{  "message_type": "bot",  "bot_id": ' + bot_id + ',  "email_token": ' + email_token + ',  "delay_seconds": 0,  "action": "close_at_market_price"}'
    close_all := '{ "message_type": "bot", "bot_id": ' + bot_id + ', "email_token": ' + email_token + ', "delay_seconds": 0, "action": "close_at_market_price_all"}'

// Strategy Actions
if inDateRange and goodBuy
    strategy.entry("Good Buy", strategy.long, when = strategy.opentrades <= 0, alert_message=enter_msg)
if inDateRange and safety
    strategy.order("Good Buy", strategy.long, strategy.position_size*volume_scale, when = strategy.opentrades > 0, comment = "safety order")
if inDateRange and goodSell
    strategy.close_all(comment="Good sell point")
if inDateRange and stoploss
    strategy.close_all(comment="Stoploss")
if inDateRange and takeprofit
    strategy.close_all(comment="TP Target")


더 많은