동적 그리드 거래 전략 기반


생성 날짜: 2024-01-23 10:53:05 마지막으로 수정됨: 2024-01-23 10:53:05
복사: 0 클릭수: 832
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

동적 그리드 거래 전략 기반

개요

이 전략은 가격 범위 내에서 여러 개의 병렬 구매/판매 주문을 설정하여 시장의 변동에 따라 격자 영역과 라인을 조정하여 수익을 창출하는 것을 구현합니다.

전략 원칙

  1. 그리드 상하계를 설정할 수 있고, 수동으로 설정할 수도 있고, 최근 기간의 가격 상승과 하락에 따라 자동으로 계산할 수도 있다.
  2. 설정된 격자 수에 따라 격자 간격의 폭을 계산한다.
  3. 그릴 라인 값의 배열을 생성한다.
  4. 가격이 어떤 격자선보다 낮으면 그 선 아래에서 다중을 열고, 가격이 어떤 격자선보다 높으면 그 선 위에 공평한 상표를 열는다.
  5. 동적으로 격자 상단 경계, 간격 너비 및 격자 라인 가격을 조정하여 시장 변화에 적응하십시오.

우위 분석

  1. 수평과 변동 시장에서 안정적인 수익을 창출할 수 있으며, 일방적인 상황에 영향을 받지 않습니다.
  2. 수동 설정을 지원하는 것은 자동으로 격자 구간을 계산하는 것을 지원하며, 적응력이 강하다.
  3. 그리드 수, 그리드 너비 및 주문량을 조정하여 수익을 최적화 할 수 있습니다.
  4. 내장된 포지션 제어, 위험을 제어한다.
  5. 동적으로 격자 범위를 조정하여 정책의 적응성을 강화합니다.

위험 분석

  1. 큰 트렌드가 나타나면 큰 손실이 발생할 수 있습니다.
  2. 그리드 수와 포지션 설정이 잘못되면 위험이 커질 수 있습니다.
  3. 자동으로 계산된 격자 간격은 극단적인 경우에도 작동하지 않을 수 있습니다.

위험 해결 방법:

  1. 그리드 매개 변수를 최적화하고, 총 포지션을 엄격하게 제어한다.
  2. 큰 사태가 일어나기 전에 전략을 종료하라.
  3. 트렌드 지표와 결합하여 상황을 판단하고, 필요한 경우 전략을 종료한다.

최적화 방향

  1. 시장의 특성과 자본의 규모에 따라 최적의 격자 수를 선택하십시오.
  2. 다양한 시간 주기 최적화 그리드 자동 계산 파라미터를 테스트한다.
  3. 더 안정적인 수익을 얻기 위해 위탁량 계산 방법을 최적화하십시오.
  4. 다른 지표와 함께 대폭적인 상황을 판단하고, 전략 폐쇄 조건을 설정한다.

요약하다

이 동적 격자 거래 전략은 격자 간 변수를 동적으로 조정하여 시장 변화에 적응하여横盘 및 변동판에서 수익을 창출합니다. 적절한 포지션 컨트롤을 설정하는 동시에 위험을 제어 할 수 있습니다. 격자 변수를 최적화하여 추세 판단 지표와 결합하여 전략의 안정성을 더욱 향상시킬 수 있습니다.

전략 소스 코드
/*backtest
start: 2023-12-23 00:00:00
end: 2024-01-22 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4
strategy("sarasa srinivasa kumar", overlay=true, pyramiding=14, close_entries_rule="ANY", default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)
i_autoBounds    = input(group="Grid Bounds", title="Use Auto Bounds?", defval=true, type=input.bool)                             // calculate upper and lower bound of the grid automatically? This will theorhetically be less profitable, but will certainly require less attention
i_boundSrc      = input(group="Grid Bounds", title="(Auto) Bound Source", defval="Hi & Low", options=["Hi & Low", "Average"])     // should bounds of the auto grid be calculated from recent High & Low, or from a Simple Moving Average
i_boundLookback = input(group="Grid Bounds", title="(Auto) Bound Lookback", defval=250, type=input.integer, maxval=500, minval=0) // when calculating auto grid bounds, how far back should we look for a High & Low, or what should the length be of our sma
i_boundDev      = input(group="Grid Bounds", title="(Auto) Bound Deviation", defval=0.10, type=input.float, maxval=1, minval=-1)  // if sourcing auto bounds from High & Low, this percentage will (positive) widen or (negative) narrow the bound limits. If sourcing from Average, this is the deviation (up and down) from the sma, and CANNOT be negative.
i_upperBound    = input(group="Grid Bounds", title="(Auto) Upper Boundry", defval=0.285, type=input.float)                      // for manual grid bounds only. The upperbound price of your grid
i_lowerBound    = input(group="Grid Bounds", title="(Auto) Lower Boundry", defval=0.225, type=input.float)                      // for manual grid bounds only. The lowerbound price of your grid.
i_gridQty       = input(group="Grid Lines",  title="Grid Line Quantity", defval=8, maxval=15, minval=3, type=input.integer)       // how many grid lines are in your grid

f_getGridBounds(_bs, _bl, _bd, _up) =>
    if _bs == "Hi & Low"
        _up ? highest(close, _bl) * (1 + _bd) : lowest(close, _bl)  * (1 - _bd)
    else
        avg = sma(close, _bl)
        _up ? avg * (1 + _bd) : avg * (1 - _bd)

f_buildGrid(_lb, _gw, _gq) =>
    gridArr = array.new_float(0)
    for i=0 to _gq-1
        array.push(gridArr, _lb+(_gw*i))
    gridArr

f_getNearGridLines(_gridArr, _price) =>
    arr = array.new_int(3)
    for i = 0 to array.size(_gridArr)-1
        if array.get(_gridArr, i) > _price
            array.set(arr, 0, i == array.size(_gridArr)-1 ? i : i+1)
            array.set(arr, 1, i == 0 ? i : i-1)
            break
    arr

var upperBound      = i_autoBounds ? f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, true) : i_upperBound  // upperbound of our grid
var lowerBound      = i_autoBounds ? f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, false) : i_lowerBound // lowerbound of our grid
var gridWidth       = (upperBound - lowerBound)/(i_gridQty-1)                                                       // space between lines in our grid
var gridLineArr     = f_buildGrid(lowerBound, gridWidth, i_gridQty)                                                 // an array of prices that correspond to our grid lines
var orderArr        = array.new_bool(i_gridQty, false)                                                              // a boolean array that indicates if there is an open order corresponding to each grid line

var closeLineArr    = f_getNearGridLines(gridLineArr, close)                                                        // for plotting purposes - an array of 2 indices that correspond to grid lines near price
var nearTopGridLine = array.get(closeLineArr, 0)                                                                    // for plotting purposes - the index (in our grid line array) of the closest grid line above current price
var nearBotGridLine = array.get(closeLineArr, 1)                                                                    // for plotting purposes - the index (in our grid line array) of the closest grid line below current price
strategy.initial_capital = 50000
for i = 0 to (array.size(gridLineArr) - 1)
    if close < array.get(gridLineArr, i) and not array.get(orderArr, i) and i < (array.size(gridLineArr) - 1)
        buyId = i
        array.set(orderArr, buyId, true)
        strategy.entry(id=tostring(buyId), long=true, qty=(strategy.initial_capital/(i_gridQty-1))/close, comment="#"+tostring(buyId))
    if close > array.get(gridLineArr, i) and i != 0
        if array.get(orderArr, i-1)
            sellId = i-1
            array.set(orderArr, sellId, false)
            strategy.close(id=tostring(sellId), comment="#"+tostring(sellId))

if i_autoBounds
    upperBound  := f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, true)
    lowerBound  := f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, false)
    gridWidth   := (upperBound - lowerBound)/(i_gridQty-1)
    gridLineArr := f_buildGrid(lowerBound, gridWidth, i_gridQty)

closeLineArr    := f_getNearGridLines(gridLineArr, close)
nearTopGridLine := array.get(closeLineArr, 0)
nearBotGridLine := array.get(closeLineArr, 1)