암호화폐 선물 마틴게일형 전략 설계

저자:니나바다스, 창작: 2022-04-12 17:50:07, 업데이트: 2022-04-12 18:06:07

암호화폐 선물 마틴게일형 전략 설계

최근에는 FMZ 공식 그룹에서 많은 마틴게일 유형의 전략이 논의되고 있으며, 우리 플랫폼에는 암호화폐 계약의 많은 마틴게일 전략이 없습니다. 따라서, 나는 간단한 암호화폐 선물 마틴게일 유형의 전략을 설계할 기회를 잡았습니다. 왜 마틴게일 유형의 전략이라고 불리나요? 마틴게일 전략의 잠재적 위험은 실제로 작지 않기 때문에 마틴게일 전략에 따라 설계할 필요가 없습니다. 그러나, 이러한 유형의 전략은 여전히 많은 위험을 가지고 있으며, 마틴게일 유형의 전략의 매개 변수 설정은 위험과 밀접하게 관련이 있으며, 위험은 무시해서는 안됩니다.

이 기사에서는 주로 마르틴게일 방식의 전략의 설계에 대해 설명하고 학습합니다. 전략 아이디어 자체는 이미 매우 명확하므로 FMZ 사용자로서 전략 설계에 대해 더 많은 것을 고려할 수 있습니다.

전체 주식

전체 자본은 종종 암호화폐 선물 전략을 설계할 때 사용됩니다. 특히 부동 수익을 계산해야 할 때 수익을 계산하고 싶습니다. 포지션을 보유하는 것이 마진을 차지하기 때문에 미뤄진 주문도합니다.exchange.GetAccount()FMZ 플랫폼의 사용 가능한 자산과 대기 주문 동결 자산을 얻기 위해 호출됩니다. 사실, 대부분의 암호화폐 선물 플랫폼은 총 자본의 데이터를 제공하지만이 재산은 FMZ에 균일하게 포장되지 않습니다.

따라서 우리는 서로 다른 플랫폼에 따라 데이터를 얻기 위해 기능을 별도로 설계합니다.

// OKEX V5 obtains the total equity 
function getTotalEquity_OKEX_V5() {
    var totalEquity = null 
    var ret = exchange.IO("api", "GET", "/api/v5/account/balance", "ccy=USDT")
    if (ret) {
        try {
            totalEquity = parseFloat(ret.data[0].details[0].eq)
        } catch(e) {
            Log("Fail to obtain the total equity of the account!")
            return null
        }
    }
    return totalEquity
}

// Binance Ftures 
function getTotalEquity_Binance() {
    var totalEquity = null 
    var ret = exchange.GetAccount()
    if (ret) {
        try {
            totalEquity = parseFloat(ret.Info.totalWalletBalance)
        } catch(e) {
            Log("Fail to obtain the total equity!")
            return null
        }
    }
    return totalEquity
}

totalEquity코드에서 필요한 총 주식입니다. 그러면 우리는 호출 항목으로 함수를 작성하고 해당 함수를 플랫폼 이름에 따라 호출합니다.

function getTotalEquity() {
    var exName = exchange.GetName()
    if (exName == "Futures_OKCoin") {
        return getTotalEquity_OKEX_V5()
    } else if (exName == "Futures_Binance") {
        return getTotalEquity_Binance()
    } else {
        throw "Do not support the platform"
    }
}

여러 보조 기능을 설계

주요 기능과 주요 논리를 설계하기 전에, 우리는 또한 준비에 대한 몇 가지 보조 기능을 설계해야합니다.

  • 현재 대기 중인 모든 주문을 취소합니다.

    function cancelAll() {
        while (1) {
            var orders = _C(exchange.GetOrders)
            if (orders.length == 0) {
                break
            }
            for (var i = 0 ; i < orders.length ; i++) {
                exchange.CancelOrder(orders[i].Id, orders[i])
                Sleep(500)
            }
            Sleep(500)
        }
    }
    

    이 함수는 FMZ 전략 사각형의 전략 예제 코드를 자주 읽는 사람들에게 익숙하다고 여겨지며 많은 전략이 유사한 디자인을 사용했습니다. 기능은 현재 미뤄진 주문 목록을 얻고 주문을 하나씩 취소하는 것입니다.

  • 선물 주문을 하는 행위

    function trade(distance, price, amount) {
        var tradeFunc = null 
        if (distance == "buy") {
            tradeFunc = exchange.Buy
        } else if (distance == "sell") {
            tradeFunc = exchange.Sell
        } else if (distance == "closebuy") {
            tradeFunc = exchange.Sell
        } else {
            tradeFunc = exchange.Buy
        }
        exchange.SetDirection(distance)
        return tradeFunc(price, amount)
    }
    
    function openLong(price, amount) {
        return trade("buy", price, amount)
    }
    
    function openShort(price, amount) {
        return trade("sell", price, amount)
    }
    
    function coverLong(price, amount) {
        return trade("closebuy", price, amount)
    }
    
    function coverShort(price, amount) {
        return trade("closesell", price, amount)
    }
    

    선물 거래에는 네 가지 방향이 있습니다: 오픈 롱 포지션 (openLong), 오픈 쇼트 포지션 (openShort), 클로즈 롱 포지션 (coverLong), 클로즈 쇼트 포지션 (coverShort). 따라서 우리는 이러한 작업에 대응하도록 네 가지 오더 함수를 설계했습니다. 주문을 배치하는 것을만 고려하면 방향, 주문 가격 및 주문 금액 등 여러 가지 필요한 요소가 있습니다.

    우리는 또한 다음과 같은 함수를 설계했습니다.trade작업 처리 할 때direction (distance), order price (price)그리고order amount (amount)정해져 있습니다.

    개방된 긴 포지션 (openLong), 오픈 짧은 포지션 (openShort), 긴 포지션 (coverLong), 그리고 긴 포지션 (coverShort) 을 닫는 함수 호출은 최종적으로trade기능, 즉, 정해진 방향, 가격 및 금액에 따라, 선물 플랫폼에 주문을 배치.

주요 기능

전략 아이디어는 매우 간단합니다; 현재 가격을 기준으로 취하고, 기준선 위와 아래에서 특정 거리에서 판매 주문 (단거리) 및 구매 주문 (장거리) 을 배치합니다. 한쪽의 주문이 실행되면 나머지 모든 주문을 취소하고, 그 다음 새로운 클로즈 주문이 위치 가격에 따라 특정 거리에 배치되며 구매 주문은 업데이트 된 현재 가격에 배치되지만 구매 주문은 주문 금액을 두 배로 증가시키지 않습니다.

  • 초기 작업 주문을 대기하려면 두 개의 변수가 필요합니다.

    var buyOrderId = null
    var sellOrderId = null
    

    그런 다음, OKEX_V5 시뮬레이션 봇을 사용하는 옵션은 전략 인터페이스 매개 변수에서 설계되므로 코드에 약간의 처리 작업이 필요합니다.

    var exName = exchange.GetName()    
    // switch to OKEX V5 simulated bot 
    if (isSimulate && exName == "Futures_OKCoin") {
        exchange.IO("simulate", true)
    }
    

    모든 정보를 다시 설정하는 옵션은 전략 매개 변수에도 설계되어 있으므로 코드에서 약간의 처리 작업이 필요합니다.

    if (isReset) {
        _G(null)
        LogReset(1)
        LogProfitReset()
        LogVacuum()
        Log("Reset all data", "#FF0000")
    }
    

    우리는 영구계약만 실행합니다. 그래서 여기서는 무한 루프로 작성하고

    exchange.SetContractType("swap")
    

    또한, 우리는 주문 가격과 주문 금액의 정확성 문제를 고려해야합니다. 정확성이 올바르게 설정되지 않으면 전략 계산 과정에서 손실됩니다. 데이터가 많은 소수점을 가지고 있다면 플랫폼 인터페이스에 의해 주문이 거부되는 것이 쉽습니다.

    exchange.SetPrecision(pricePrecision, amountPrecision)
    Log("set percision", pricePrecision, amountPrecision)
    

    디자인에서 간단한 데이터 복구 기능

    if (totalEq == -1 && !IsVirtual()) {
        var recoverTotalEq = _G("totalEq")
        if (!recoverTotalEq) {
            var currTotalEq = getTotalEquity()
            if (currTotalEq) {
                totalEq = currTotalEq
                _G("totalEq", currTotalEq)
            } else {
                throw "Fail to obtain the initial equity"
            }
        } else {
            totalEq = recoverTotalEq
        }
    }
    

    전략을 실행 할 때 계좌의 초기 총 자산을 지정하려면 매개 변수를 설정할 수 있습니다totalEq이 매개 변수가 -1로 설정되면 전략은 저장된 총 주식 데이터를 읽을 것입니다. 저장된 총 주식 데이터가 없으면 현재 읽힌 총 주식은 진행 중인 전략의 초기 총 주식으로 사용됩니다. 나중에 총 주식이 증가하면 이익이 발생했으며 총 주식이 감소하면 손실이 발생한다는 것을 의미합니다. 총 주식 데이터가 읽히면 데이터를 사용하여 계속 실행하십시오.

  • 주요 논리 초기 작업이 완료된 후, 우리는 마침내 전략의 주요 논리적 부분에 도달했습니다. 설명의 편의를 위해, 나는 코드에 직접 언급을 썼다.

      while (1) {                                  // the main logic of the strategy is designed as an infinite loop
          var ticker = _C(exchange.GetTicker)      // read the current market information first, in which we mainly use the latest trading price
          var pos = _C(exchange.GetPosition)       // read the current position data 
          if (pos.length > 1) {                    // judge the position data; due to the strategy logic, it is unlikely to have long and short positions at the same time, so if there are long and short positions at the same time, an error will be thrown
              Log(pos)
              throw "concurrently with long and short positions"                  // raise an error, and stop the strategy 
          }
          // according to the status 
          if (pos.length == 0) {                    // according to the position status, make different operations; if pos.length == 0, it means currently no position
              // when there is no position yet, calculate the equity 
              if (!IsVirtual()) {
                  var currTotalEq = getTotalEquity()
                  if (currTotalEq) {
                      LogProfit(currTotalEq - totalEq, "Current total equity:", currTotalEq)
                  }
              }
    
              buyOrderId = openLong(ticker.Last - targetProfit, amount)       // pend buy order of open long position 
              sellOrderId = openShort(ticker.Last + targetProfit, amount)     // pend sell order of open short position
          } else if (pos[0].Type == PD_LONG) {   // there are long positions; pending position and amount are 
              var n = 1
              var price = ticker.Last
              buyOrderId = openLong(price - targetProfit * n, amount)
              sellOrderId = coverLong(pos[0].Price + targetProfit, pos[0].Amount)
          } else if (pos[0].Type == PD_SHORT) {   // there are short positions; pending position and amount are different 
              var n = 1
              var price = ticker.Last
              buyOrderId = coverShort(pos[0].Price - targetProfit, pos[0].Amount)
              sellOrderId = openShort(price + targetProfit * n, amount)
          }
    
          if (!sellOrderId || !buyOrderId) {   // if opending orders of one side fails, cancel all pending orders and try again 
              cancelAll()
              buyOrderId = null 
              sellOrderId = null
              continue
          } 
    
          while (1) {  // finish pending the order, and start to monitor the order
              var isFindBuyId = false 
              var isFindSellId = false
              var orders = _C(exchange.GetOrders)
              for (var i = 0 ; i < orders.length ; i++) {
                  if (buyOrderId == orders[i].Id) {
                      isFindBuyId = true 
                  }
                  if (sellOrderId == orders[i].Id) {
                      isFindSellId = true 
                  }               
              }
              if (!isFindSellId && !isFindBuyId) {    // both buy order and sell order are detected to be executed 
                  cancelAll()
                  break
              } else if (!isFindBuyId) {   // a buy order execution is detected 
                  Log("buy order executed")
                  cancelAll()
                  break
              } else if (!isFindSellId) {  // a sell order execution is detected 
                  Log("sell order executed")
                  cancelAll()
                  break
              }
              LogStatus(_D())
              Sleep(3000)
          }
          Sleep(500)
      }
    

이 모든 논리와 설계는 완전히 설명되어 있습니다.

백테스트

전략은 2021년 5월 19일 시장 코팅을 통과하도록 합니다.

img

img

우리가 볼 수 있듯이, 마틴게일 전략과 비슷한 전략은 여전히 특정 위험을 가지고 있습니다.

봇 테스트는 OKEX V5 시뮬레이션 봇을 실행할 수 있습니다.

img

전략 주소:https://www.fmz.com/strategy/294957

이 전략은 주로 연구용으로 사용되므로 실제 봇에서 전략을 조작하지 마세요!


더 많은