dYdX 전략 설계 예제 - 무작위 거래 전략

저자:작은 꿈, 2021-11-03 15:40:56, 업데이트: 2023-09-15 21:02:48

img

dYdX 전략 설계 사례

많은 사용자 요구에 따라 FMZ 플랫폼은 최근 dYdX라는 탈중앙화 거래소를 지원했습니다. 전략이있는 파트너는 dYdX를 즐겁게 채굴 할 수 있습니다. 아주 오래 전에 무작위 거래 전략을 쓰고 싶었습니다. 돈을 벌거나 돈을 버는 것은 무작위 전략 설계를 연습하고 가르치는 것입니다.

"이봐, 이봐, 이봐, 이봐.

이 글의 전략적 채굴 스크린 샷.

img

: : : : : : : : : : : : :

무작위 거래 전략 설계

우리는 한 번 생각해보자! 우리는 지표와 가격의 무작위 순서를 고려하지 않고, 더 많은 일을 하고, 공백을 하고, 확률을 기준으로 할 수 있는 무작위 순서를 설계할 계획이다.

여러 조건: 무작위 숫자 1 ~ 50. 공백 조건: 무작위 51 ~ 100 ▲

50개의 숫자입니다. 다음으로 우리가 어떻게 평형화 할 수 있는지 생각해 볼 때, 승자이기 때문에 승패 기준이 있어야합니다. 그렇다면 거래에서 우리는 승패 기준으로 고정된 스톱레이, 스톱레이를 설정합니다. 스톱레이는 승패, 스톱레이는 손실입니다. 이 스톱레이, 스톱레이, 스톱레이는 손실입니다. 이 스톱레이, 스톱레이, 스톱레이가 얼마나 적합합니까?

거래는 비용이 많이 들지 않고, 슬라이드 포인트, 처리 요금 등이 우리의 무작위 거래 승률을 50% 이하로 끌어올릴 만큼 충분합니다. 곱셈을 설계하는 것이 낫습니다. 왜냐하면 그것은 이기 때문에 연속 10번의 8번의 무작위 거래를 모두 잃는 확률이 크지 않아야합니다. 그래서 나는 첫 번째 거래를 단위로 작게 설계하고, 더 작을 수 있습니다. 그리고 만약 당신이 잃는다면 다음 단위를 늘리고 무작위 거래를 계속하십시오.

OK, 전략은 이렇게 간단하게 설계하면 됩니다.

디자인 소스:

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

전략 파라미터:

img

오, 맞아요! 전략은 이름을 가지고 있어야 합니다.

재검토

이 글은 한 번 더 읽어보겠습니다. 주요 검사 전략은 어떤 BUG가 있는지 확인하고, 아온 선물로 재검토하는 것입니다.

img

img

img

img

다시 테스트 완료, 아무 BUG. 하지만 나는 다시 테스트 시스템에 적합하지 않은 느낌... T_T, 실제 디스크가 실행하고 있습니다.

실재

img

img

img

이 전략은 학습, 참고, 정보 제공을 위한 것입니다.천만~천만실제 디스크는 사용하지 마세요!


관련

더 많은

롱후이자, Dydx 분산 거래소는 현재 현금 거래를 지원합니까? 아니면 영구 계약만 할 수 있습니까? 분산 거래소를 사용하지 않았습니다. Dydx가 현금 거래를 지원하는 경우, 현금 격자 거래 전략을 고려할 수 있습니다. 또는 분산 거래소는 거래가 성공했는지 확인하는 데 시간이 필요합니다.

hyc1743작은 흰색, 왜 뛰지 않는지 물어보세요.

작은 꿈dYdX는 제가 공개한 실제 음반과 영구 계약입니다.

작은 꿈전략 소스 코드는 전략 코드일 뿐이며, 파라미터도 설정해야 한다. 파라미터에는 문서에 스크린 샷이 있다.