# 基于Dex深度差异的循环套利算法设计与实现 **Published by:** [shaneson.eth](https://paragraph.com/@shaneson-eth/) **Published on:** 2022-05-13 **URL:** https://paragraph.com/@shaneson-eth/dex ## Content 背景由于Dex的深度会有差异,两个token的直接汇率可能与市场上的交叉汇率不一致。而这种价格差异 通过不同的加密货币循环交易,开启了套利的可能性。由于实在对这个很感兴趣,利用了业余时间我熬夜了好几天以conflux swappi上的循环套利为例,开展这以类别的研究。(注意是业余时间,我没有耽误正事!!)(https://evm.confluxscan.net/tx/0x55fee13835c115f7936e9a1ced897fd7a8ff7a15e0e60e8ed570aa768b5683e4) 上面是套利者在swappi上进行的套利行为:他设计path为:USDT =》WBTC => WCFX => USDT,利用深度差的特点,AmountIn是710USDT,AmountOut是712USDT。完成了2USDT的套利利润。Model Definition我们不妨先定义套利行为涉及到n种token的转换的成立条件: Trade 1: Exchange 𝛿1 of 𝐴1 with 𝛿2 of 𝐴2. Trade 2: Exchange 𝛿2 of 𝐴2 with 𝛿3 of 𝐴3. . . . Trade 𝑛: Exchange 𝛿𝑛 of 𝐴𝑛 with 𝛿′1 of 𝐴1. 当且仅当 𝛿′1 - 𝛿1 > 0时,套利成立。**定理1: **给定一个循环套利的路径:A1 -> A2 -> A3 -> ... An -> A1。当满足下面条件时,套利条件满足。其中,Aij 代表Token I和Token J上的流动性。Algorithm and Code利用xy=k的公式算法,我们可以得到最佳的兑换数值为:代码实现如下: async function CycleArbitrage(Path, MappingReserve) { const A = new Array(); // A for (var i = 0; i < Path.length; i++ ) { A[i] = new Array(); for (var j = 0; j < Path.length; j++) { A[i][j] = MappingReserve.get(Path[i]+Path[j]); } } // console.log(A); // console.log( A[0][1], A[1][0]); var a = A ; // Compute the equivalent liquidity of the cycle for (var i = 0; i< Path.length; i++ ) { a[0][Path.length - 1] = A[0][1]; a[Path.length-1][0] = A[1][0]; for (var j = 1; j < Path.length - 1; j++ ) { a[0][Path.length - 1] = (a[0][Path.length - 1] * A[j-1][j]) / (a[j-1][j] + r1*r2*A[Path.length-1][0]) ; a[Path.length - 1][0] = ( r1 * r2 * a[Path.length- 1 ][0] * A[j][j-1]) / (A[j-1][j] + r1*r2*a[Path.length-1][0]) ; } } // 0.0007746540591768103 0.0007669365197266427 // 0.0007849891438126567 0.0007771686404362653 // console.log(a[0][Path.length - 1], a[Path.length-1][0]); BestAmount = 0; _a1 = (a[0][Path.length - 1] * A[Path.length-1][0]) / (A[Path.length-1][0] + r1 * r2 * a[Path.length-1][0]); _a2 = (A[0][Path.length - 1] * a[Path.length - 1][0]) /(A[Path.length-1][0] + r1 * r2 * a[Path.length-1][0]);; BestAmount = (Math.sqrt(r1*r2*_a1*_a2) - _a1) / r1 ; return BestAmount; } ## Publication Information - [shaneson.eth](https://paragraph.com/@shaneson-eth/): Publication homepage - [All Posts](https://paragraph.com/@shaneson-eth/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@shaneson-eth): Subscribe to updates