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

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

相关推荐
用户83562907805113 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng815 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi16 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee16 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay16 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤16 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean17 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽18 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户606487671889619 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听20 小时前
RAG深入学习之Chunk
前端·人工智能·python