从零开始搭建链上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

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

相关推荐
久绊A44 分钟前
Python 基本语法的详细解释
开发语言·windows·python
Hylan_J4 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶4 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
失败尽常态5237 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447747 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农7 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿7 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing8 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
xinxiyinhe9 小时前
如何设置Cursor中.cursorrules文件
人工智能·python
诸神缄默不语9 小时前
如何用Python 3自动打开exe程序
python·os·subprocess·python 3