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

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

相关推荐
u01092727111 小时前
RESTful API设计最佳实践(Python版)
jvm·数据库·python
我材不敲代码15 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
0思必得017 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长17 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_1927798717 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u01092727118 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊18 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
Imm77718 小时前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew18 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd65219 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python