avatar of 发明者量化-小小梦 发明者量化-小小梦
집중하다 사신
4
집중하다
1271
수행원

dYdX 전략 설계 사례 - 확률적 거래 전략

만든 날짜: 2021-11-03 15:40:56, 업데이트 날짜: 2023-09-15 21:02:48
comments   6
hits   2500

dYdX 전략 설계 사례 - 확률적 거래 전략

dYdX 전략 설계 사례

많은 사용자 요구에 부응하여 FMZ 플랫폼은 최근 분산형 거래소 dYdX를 지원했습니다. 전략이 있는 친구는 즐겁게 dYdX를 채굴할 수 있습니다. 그냥 우연히 오래전에 랜덤 트레이딩 전략을 쓰고 싶었을 뿐입니다. 돈을 벌든 잃든 상관없습니다. 목적은 전략 설계를 연습하고 동시에 가르치는 것입니다. 그러니 랜덤 교환 전략을 함께 설계해 봅시다. 전략의 성과에 대해서는 걱정하지 마세요. 전략 설계에 대해서만 알아봅시다.

먼저 채굴 방법을 보여드리겠습니다.

본 기사의 전략적 채굴에 대한 스크린샷입니다.

dYdX 전략 설계 사례 - 확률적 거래 전략

좋은 채굴 전략 아이디어를 가지고 있는 친구는 메시지를 남겨주시기 바랍니다!

확률론적 거래 전략 설계

“거칠게 생각해보세요”! 저는 지표나 가격을 보지 않고 무작위로 주문을 하는 전략을 설계할 계획입니다. 주문은 롱 또는 숏에 불과하며, 당신이 해야 할 일은 확률을 예측하는 것뿐입니다. 그런 다음 1에서 100까지의 난수를 사용하여 길고 짧은 것을 결정합니다.

긴 조건: 1~50의 난수. 공매도 조건 : 난수 51~100.

롱 포지션과 숏 포지션 모두 숫자는 50입니다. 다음으로 포지션을 어떻게 마감할지 생각해 보자. 도박이기 때문에 승패에 대한 기준이 있어야 한다. 그런 다음 거래에서 고정된 이익실현과 손절매를 수익과 손실의 기준으로 설정합니다. 이익을 멈추면 이기는 것이고, 손실을 멈추면 지는 것입니다. 적절한 이익실현과 손실정지 설정에 관해서는 실제로 손익비율에 영향을 미칩니다. 이는 승률에도 영향을 미칩니다! (이 디자인 전략이 효과적일까요? 긍정적인 수학적 기대를 보장할 수 있을까요? 먼저 해보자! 결국 학습과 연구를 위한 것이니까!)

거래는 무료가 아닙니다. 미끄러짐과 처리 수수료와 같은 요인만으로도 무작위 거래 승률을 50% 미만으로 끌어내리기에 충분합니다. 이것을 염두에 두고 어떻게 디자인을 계속해야 할까? 여러 포지션 증가를 설계하는 것이 더 좋습니다. 도박이기 때문에 10번의 무작위 거래 중 8번을 연속으로 잃을 확률은 그리 높지 않을 것입니다. 그래서 저는 첫 번째 거래를 가능한 한 아주 작은 주문 크기로 설계하고 싶습니다. 그런 다음 베팅에서 졌다면 주문 수량을 늘리고 계속해서 무작위 주문을 하세요.

네, 전략 설계는 이렇게 간단합니다.

디자인 소스 코드:

var openPrice = 0 
var ratio = 1
var totalEq = null 
var nowEq = null 

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)
    }
}

function main() {
    if (isReset) {
        _G(null)
        LogReset(1)
        LogProfitReset()
        LogVacuum()
        Log("重置所有数据", "#FF0000")
    }

    exchange.SetContractType(ct)

    var initPos = _C(exchange.GetPosition)
    if (initPos.length != 0) {
        throw "策略启动时有持仓!"
    }
    
    exchange.SetPrecision(pricePrecision, amountPrecision)
    Log("设置精度", pricePrecision, amountPrecision)
    
    if (!IsVirtual()) {
        var recoverTotalEq = _G("totalEq")
        if (!recoverTotalEq) {
            var currTotalEq = _C(exchange.GetAccount).Balance   // equity
            if (currTotalEq) {
                totalEq = currTotalEq
                _G("totalEq", currTotalEq)
            } else {
                throw "获取初始权益失败"
            }
        } else {
            totalEq = recoverTotalEq
        }
    } else {
        totalEq = _C(exchange.GetAccount).Balance
    }
    
    while (1) {
        if (openPrice == 0) {
            // 更新账户信息,计算收益
            var nowAcc = _C(exchange.GetAccount)
            nowEq = IsVirtual() ? nowAcc.Balance : nowAcc.Balance  // equity
            LogProfit(nowEq - totalEq, nowAcc)
            
            var direction = Math.floor((Math.random()*100)+1)   // 1~50 , 51~100
            var depth = _C(exchange.GetDepth)
            if (depth.Asks.length <= 2 || depth.Bids.length <= 2) {
                Sleep(1000)
                continue 
            }
            if (direction > 50) {
                // long
                openPrice = depth.Bids[1].Price
                exchange.SetDirection("buy")
                exchange.Buy(Math.abs(openPrice) + slidePrice, amount * ratio)
            } else {
                // short
                openPrice = -depth.Asks[1].Price
                exchange.SetDirection("sell")
                exchange.Sell(Math.abs(openPrice) - slidePrice, amount * ratio)
            }       
            Log("下", direction > 50 ? "买单" : "卖单", ",价格:", Math.abs(openPrice))
            continue
        }

        var orders = _C(exchange.GetOrders)
        if (orders.length == 0) {
            var pos = _C(exchange.GetPosition)
            if (pos.length == 0) {
                openPrice = 0
                continue
            }
            
            // 平仓检测
            while (1) {
                var depth = _C(exchange.GetDepth)
                if (depth.Asks.length <= 2 || depth.Bids.length <= 2) {
                    Sleep(1000)
                    continue 
                }
                var stopLossPrice = openPrice > 0 ? Math.abs(openPrice) - stopLoss : Math.abs(openPrice) + stopLoss 
                var stopProfitPrice = openPrice > 0 ? Math.abs(openPrice) + stopProfit : Math.abs(openPrice) - stopProfit
                var winOrLoss = 0 // 1 win , -1 loss 
                
                // 画线
                $.PlotLine("bid", depth.Bids[0].Price)
                $.PlotLine("ask", depth.Asks[0].Price)
                
                // 止损
                if (openPrice > 0 && depth.Bids[0].Price < stopLossPrice) {
                    exchange.SetDirection("closebuy")
                    exchange.Sell(depth.Bids[0].Price - slidePrice, pos[0].Amount)
                    winOrLoss = -1
                } else if (openPrice < 0 && depth.Asks[0].Price > stopLossPrice) {
                    exchange.SetDirection("closesell")
                    exchange.Buy(depth.Asks[0].Price + slidePrice, pos[0].Amount)
                    winOrLoss = -1
                }
                
                // 止盈
                if (openPrice > 0 && depth.Bids[0].Price > stopProfitPrice) {
                    exchange.SetDirection("closebuy")
                    exchange.Sell(depth.Bids[0].Price - slidePrice, pos[0].Amount)  
                    winOrLoss = 1
                } else if (openPrice < 0 && depth.Asks[0].Price < stopProfitPrice) {
                    exchange.SetDirection("closesell")
                    exchange.Buy(depth.Asks[0].Price + slidePrice, pos[0].Amount)
                    winOrLoss = 1
                }
                
                // 检测挂单
                Sleep(2000)
                var orders = _C(exchange.GetOrders)                
                if (orders.length == 0) {
                    pos = _C(exchange.GetPosition)
                    if (pos.length == 0) {
                        if (winOrLoss == -1) {
                            ratio++
                        } else if (winOrLoss == 1) {
                            ratio = 1
                        }
                        break
                    }                    
                } else {
                    // 撤销挂单
                    cancelAll()
                    Sleep(2000)
                    pos = _C(exchange.GetPosition)
                    // 撤销后更新持仓,需要再次检查
                    if (pos.length == 0) {
                        if (winOrLoss == -1) {
                            ratio++
                        } else if (winOrLoss == 1) {
                            ratio = 1
                        }
                        break
                    }    
                }
                
                var tbl = {
                    "type" : "table", 
                    "title" : "info", 
                    "cols" : ["totalEq", "nowEq", "openPrice", "bid1Price", "ask1Price", "ratio", "pos.length"], 
                    "rows" : [], 
                }
                tbl.rows.push([totalEq, nowEq, Math.abs(openPrice), depth.Bids[0].Price, depth.Asks[0].Price, ratio, pos.length])
                tbl.rows.push(["pos", "type", "amount", "price", "--", "--", "--"])
                for (var j = 0 ; j < pos.length ; j++) {
                    tbl.rows.push([j, pos[j].Type, pos[j].Amount, pos[j].Price, "--", "--", "--"])
                }
                LogStatus(_D(), "\n", "`" + JSON.stringify(tbl) + "`")
            }
        } else {
            // 撤销挂单
            // 重置openPrice
            cancelAll()
            openPrice = 0
        }
        Sleep(1000)
    }
}

전략 매개변수:

dYdX 전략 설계 사례 - 확률적 거래 전략

오, 맞아요! 이 전략에는 이름이 필요합니다. “크기 추측(dYdX 버전)“이라고 부르겠습니다.

백테스팅

백테스팅은 단지 참고용입니다._<! 주된 목적은 전략에 버그가 있는지 확인하고 바이낸스 선물 백테스팅을 활용하는 것입니다.

dYdX 전략 설계 사례 - 확률적 거래 전략

dYdX 전략 설계 사례 - 확률적 거래 전략

dYdX 전략 설계 사례 - 확률적 거래 전략

dYdX 전략 설계 사례 - 확률적 거래 전략

백테스팅이 완료되었고 버그가 없습니다. 하지만 백테스트 시스템을 과대적합시킨 것 같아요…T_T, 실시간으로 시도해 볼게요.

실제 거래

dYdX 전략 설계 사례 - 확률적 거래 전략

dYdX 전략 설계 사례 - 확률적 거래 전략

dYdX 전략 설계 사례 - 확률적 거래 전략

이 전략은 학습 및 참고용일 뿐입니다.1000만~1000만실제로 사용하지 마세요! !