dYdX策略设计范例--随机交易策略

Author: 小小梦, Created: 2021-11-03 15:40:56, Updated: 2023-09-15 21:02:48

img

dYdX策略设计范例

应不少用户需求,最近FMZ平台支持了dYdX这个去中心化交易所。有策略的小伙伴们可以愉快的挖矿dYdX了。正好很久以前就想写一个随机交易策略,赚钱亏钱无所谓目的是练练手顺便教学一下策略设计。所以接下来我们一起来设计一个随机交易所策略,策略绩效好坏不用在意,我们权且来学习策略设计。

先来晒一波挖矿

本篇的策略挖矿截图。

img

有好的挖矿策略思路的小伙伴也欢迎留言哇!

随机交易策略设计

我们来“胡思乱想”一通!计划设计一个不看指标、不看价格随机下单的策略,下单无非就是做多、做空而已,堵的都是概率。那我们就用随机数1~100来确定多空。

做多条件:随机数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

哦对!策略需要起个名字,就叫“猜大小 (dYdX版)”吧。

回测

回测仅供参考就好,>_<! 主要检查策略是不是有什么BUG,用币安期货回测。

img

img

img

img

回测完了,没什么BUG。不过感觉我是不是拟合回测系统了…T_T,实盘跑着玩一下。

实盘跑跑

img

img

img

本策略仅供学习、参考,千万~千万不要实盘使用!!


Related

More

xionglonghui 问一下, dydx去中心化交易所现在是否支持现货交易? 还是只能永续合约? 从来没用过 去中心化交易所, 如果dydx支持现货交易, 可以考虑做个现货网格交易策略. 还有就是去中心化交易所, 确认买卖是否成功还需要等待时间, 不像中心化交易所那么闪电般快, 需要旷工确认. 要是速度这些克服了, 又支持写网格等量化策略, 那是非常好.

hyc1743 小白一个,请问怎么跑不起来

小小梦 dYdX我公开的有实盘,永续合约。

小小梦 策略源码只是策略代码,还要配置上参数。参数在文章里有截图。