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

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

相关推荐
TechubNews2 小时前
东方之珠·数链未来:香港回归28周年RWA革命赋能全球金融
区块链·稳定币
郭庆汝4 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变8 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络8 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find9 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
yoona102010 小时前
在 Sepolia 上使用 Zama fhEVM 构建隐私代币与流动性池:全流程实战指南
区块链·隐私币·zama
选择不变10 小时前
日线周线MACD指标使用图文教程,通达信指标
大数据·区块链·通达信指标公式·炒股技巧·短线指标·炒股指标
博观而约取10 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
链上Sniper11 小时前
智能合约状态快照技术:实现 EVM 状态的快速同步与回滚
java·大数据·linux·运维·web3·区块链·智能合约
精灵vector12 小时前
构建专家级SQL Agent交互
python·aigc·ai编程