从零开始搭建链上dex自动化价差套利程序(13)

优化

优化触发条件:

之前的触发条件有问题,导致迟迟不能触发,优化后触发条件如下:

复制代码
  dydx_take = 0.0002
  apex_make = 0.0005
  ​
  float(b_first_price_apex)-float(s_first_price_dydx) > float(b_first_price_apex)*apex_make+float(s_first_price_dydx)*dydx_take

优化风险控制:

每次异常退出再重启杠杆都会从0开始计算,这导致杠杆越拉越高,故而采用全局文件的方式存储arbitrage_count

place_order_all.py

python 复制代码
# 其他导入和函数定义...
  ​
  # 读取存储 arbitrage_count 的文件,如果存在则读取值
  try:
      with open('arbitrage_count.txt', 'r') as file:
          arbitrage_count = int(file.read())
  except FileNotFoundError:
      arbitrage_count = 0
  ​
  async def arbitrage():
      global arbitrage_count
      # 其他代码...
      
      while True:
          # 计算价差和交易逻辑
          # ...
  ​
          # 在合适的地方,更新 arbitrage_count 的值
          # 比如:
          arbitrage_count += 1  # 或者根据你的逻辑修改 arbitrage_count
          
          # 在适当的时候将 arbitrage_count 的值写入文件,以便下次读取
          with open('arbitrage_count.txt', 'w') as file:
              file.write(str(arbitrage_count))
          
          # 等待 1 秒
          await asyncio.sleep(1)
  ​
  # 其他代码...
  ​
  # 运行异步函数
  asyncio.run(arbitrage())
复制代码

run.py

python 复制代码
  # 其他代码...
  ​
  if __name__ == "__main__":
      choice = input("请输入要运行的文件(1-btc,2-eth,3-link,4-ltc,5-avax,6-atom,7-doge,8-bch,9-matic,10-sol,11-all ):")
      with open('arbitrage_count.txt', 'w') as file:
              file.write(str(0))
      while True:
          program = run_program(choice)
          if program:
              while program.poll() is None:
                  time.sleep(5)
              print("程序已终止,重新启动中...")
              time.sleep(1)

apex买卖价设置

要尽可能大和尽可能小,但不能太大,不然会触发报错:

{'code': 3, 'msg': 'If order is filled, your account may be liquidated.', 'key': 'ORDER_POSSIBLE_LEAD_TO_ACCOUNT_LIQUIDATED'}

dydx参数设置

post-only一定要设置成false,改正后买单的price可设置成卖一价,卖单的price可设置成买一价,保证立刻成交!

否则极其容易订单发出去就被取消!

time 设置为currentTime+1000比较好,大约15分钟。

结果分析

时间:

大概10s达到杠杆上限

仓位对比

apex:

dydx:

收益为:0.05764U

初始资金为:

apex:100U

dydx:100U

按此频率,如果持续交易,则每日收益为498U

后续需要加上自动平仓的机制,以及风险控制模块需要优化,同时多币种套利可以算最优解,大体套利模块已经搭好,本系列至此也就完结了。

相关推荐
EnCi Zheng19 小时前
11a. 阿里云大模型API调用基础
人工智能·python·阿里云·云计算
庭前云落19 小时前
Solidity 智能合约进阶 1| 安全性和验证 Keccak256 哈希函数 (Keccak256 Hash Function)
区块链·智能合约·哈希算法
MoRanzhi120319 小时前
Pillow 图像算术运算与通道计算
图像处理·人工智能·python·计算机视觉·pillow·图像差异检测·图像算术运算
怪侠_岭南一只猿20 小时前
爬虫阶段三实战练习题二:使用 Selenium 模拟爬取拉勾网职位表
css·爬虫·python·selenium·html
电报号dapp11920 小时前
公链浏览器:区块链世界的“数据透视镜”与哈希查询的艺术
算法·区块链·智能合约·哈希算法
前端付豪20 小时前
自动学习建议解决薄弱知识点
前端·python·openai
deephub20 小时前
LangGraph vs Semantic Kernel:状态图与内核插件的两条技术路线对比
人工智能·python·深度学习·大语言模型·agent
与虾牵手20 小时前
多轮对话 API 怎么实现?从原理到代码,踩完坑我总结了这套方案
python·aigc·ai编程
geovindu20 小时前
python: Simple Factory Pattern
开发语言·python·设计模式·简单工厂模式
weixin1997010801620 小时前
开山网商品详情页前端性能优化实战
java·前端·python