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

其他品种

扩展到其他币种的价差套利

1.eth

新建文件get_depth_data_eth.py

python 复制代码
import asyncio
from apexpro.http_public import HttpPublic
from dydx3 import Client
from dydx3.constants import MARKET_ETH_USD


# 定义交易对列表
symbol = 'ETHUSDC'
market = MARKET_ETH_USD

# 定义异步函数来获取 APEX 的价格
async def get_apex_price():
    # 初始化API客户端
    apexclient = HttpPublic("https://pro.apex.exchange")
    # 获取深度数据
    trades_data = apexclient.depth(symbol=symbol)['data']
    # 返回卖一价和买一价
    return trades_data['a'][0][0], trades_data['b'][0][0], trades_data['a'][0][1], trades_data['b'][0][1]

# 定义异步函数来获取 dydx 的价格
async def get_dydx_price():
    # 初始化API客户端
    dydxclient = Client(host='https://api.dydx.exchange')
    # 获取深度数据
    orderbook_response = dydxclient.public.get_orderbook(market=market)
    orderbook_data = orderbook_response.data
    # 返回卖一价和买一价
    return orderbook_data['asks'][0]['price'], orderbook_data['bids'][0]['price'], orderbook_data['asks'][0]['size'], orderbook_data['bids'][0]['size']

# 定义异步函数来计算价差
async def calculate_spread():
    # 创建两个任务,分别获取 APEX 和 dydx 的价格
    task1 = asyncio.create_task(get_apex_price())
    task2 = asyncio.create_task(get_dydx_price())
    # 等待两个任务完成,并获取结果
    s_first_price_apex, b_first_price_apex,s_first_size_apex,b_first_size_apex = await task1
    s_first_price_dydx, b_first_price_dydx,s_first_size_dydx,b_first_size_dydx   = await task2
    # 计算价差
    spread1 = ((float(b_first_price_apex) - float(s_first_price_dydx))/float(s_first_price_apex))*100
    spread2 = ((float(b_first_price_dydx) - float(s_first_price_apex))/float(s_first_price_dydx))*100
    return s_first_price_apex,b_first_price_apex,s_first_price_dydx,b_first_price_dydx,s_first_size_apex,b_first_size_apex,s_first_size_dydx,b_first_size_dydx,spread1,spread2


if __name__ == '__main__':
    # 创建事件循环
    loop = asyncio.get_event_loop()
    # 运行异步函数
    loop.run_until_complete(calculate_spread())
    # 关闭事件循环
    loop.close()

新建文件place_order_eth.py

python 复制代码
from init_apex_client import init_client
import asyncio
from send_order_apex import send_order_apex
from init_dydx_client import init_dydx_client
from send_order_dydx import send_order_dydx
from dydx3.constants import MARKET_ETH_USD
from dydx3.constants import ORDER_SIDE_BUY,ORDER_SIDE_SELL
from dydx3.constants import ORDER_TYPE_MARKET,ORDER_TYPE_LIMIT
from get_depth_data_eth import calculate_spread
import time

#价格设置需要更精确,不然发不出去!

# 初始化apex客户端
client_apex = init_client()
configs = client_apex.configs()
# 获取apex用户和账户信息
client_apex.get_user()
client_apex.get_account()


# 初始化dydx客户端
client_dydx = init_dydx_client()
# 获取我们的dydx仓位 ID
account_response = client_dydx.private.get_account()
position_id = account_response.data['account']['positionId']

async def arbitrage():
  arbitrage_count = 0
  while True:
    # 计算价差
    s_first_price_apex,b_first_price_apex,s_first_price_dydx,b_first_price_dydx,s_first_size_apex,b_first_size_apex,s_first_size_dydx,b_first_size_dydx,spread1,spread2 = await calculate_spread()
    # 根据价差判断是否发送交易
    if spread1 > 0.7:
          if arbitrage_count <8:
            currentTime = time.time()
            limitFeeRate = client_apex.account['takerFeeRate']
            task_apex_sell = asyncio.create_task(
                send_order_apex(client_apex, symbol="ETH-USDC", side="SELL",
                                type="MARKET", size="0.001", expirationEpochSeconds=currentTime+100,
                                price=b_first_price_apex, limitFeeRate=limitFeeRate)
            )
            task_dydx_buy = asyncio.create_task(
                send_order_dydx(client_dydx, position_id, MARKET_ETH_USD, ORDER_SIDE_BUY, ORDER_TYPE_LIMIT,
                                True, '0.001', b_first_price_dydx, '0.0015', currentTime+100)
            )

            orderResult1 = await task_apex_sell
            orderResult2 = await task_dydx_buy
            arbitrage_count += 1
            if arbitrage_count >=8:
               print('above leverage ,stop')
            print(orderResult1,orderResult2)
    if spread2 > 0.7: 
      if arbitrage_count >-8:
        currentTime = time.time()
        # 异步地发送一个apex市价买单和一个dydx市价卖单
        limitFeeRate = client_apex.account['takerFeeRate']
        task_apex_buy = asyncio.create_task(
                send_order_apex(client_apex, symbol="ETH-USDC", side="BUY",
                                type="MARKET", size="0.001", expirationEpochSeconds=currentTime+100,
                                price=s_first_price_apex, limitFeeRate=limitFeeRate)
            )
        task_dydx_sell = asyncio.create_task(
            send_order_dydx(client_dydx, position_id, MARKET_ETH_USD, ORDER_SIDE_SELL, ORDER_TYPE_LIMIT,
                            True, '0.001', s_first_price_dydx, '0.0015', currentTime+100)
        )

        orderResult1 = await task_apex_buy
        orderResult2 = await task_dydx_sell
        arbitrage_count -= 1
        if arbitrage_count <=-8:
          print('above leverage ,stop')
        print(orderResult1,orderResult2)
    # 延时一秒,避免过于频繁
    await asyncio.sleep(5)

# 运行异步函数
asyncio.run(arbitrage())

其他文件不变,文件结构如下:

初始化api端口

init_apex.client.py

init_dydx.client.py

发送交易

send_order_apex.py

send_order_dydx.py

测试发送交易

place_order_dydx.py

place_order_apex.py

其他品种同理。修改对应部分以及注意发送交易的size即可。

所有品种同时运行

python 复制代码
from init_apex_client import init_client
import asyncio
from send_order_apex import send_order_apex
from init_dydx_client import init_dydx_client
from send_order_dydx import send_order_dydx
from dydx3.constants import MARKET_BTC_USD,MARKET_ETH_USD,MARKET_LINK_USD,MARKET_LTC_USD,MARKET_AVAX_USD,MARKET_ATOM_USD,MARKET_DOGE_USD,MARKET_BCH_USD,MARKET_MATIC_USD,MARKET_SOL_USD
from dydx3.constants import ORDER_SIDE_BUY,ORDER_SIDE_SELL
from dydx3.constants import ORDER_TYPE_MARKET,ORDER_TYPE_LIMIT
from get_depth_data_btc import calculate_spread as calculate_spread_btc
from get_depth_data_eth import calculate_spread as calculate_spread_eth
from get_depth_data_link import calculate_spread as calculate_spread_link
from get_depth_data_ltc import calculate_spread as calculate_spread_ltc
from get_depth_data_avax import calculate_spread as calculate_spread_avax
from get_depth_data_atom import calculate_spread as calculate_spread_atom
from get_depth_data_doge import calculate_spread as calculate_spread_doge
from get_depth_data_bch import calculate_spread as calculate_spread_bch
from get_depth_data_matic import calculate_spread as calculate_spread_matic
from get_depth_data_sol import calculate_spread as calculate_spread_sol
import time

#价格设置需要更精确,不然发不出去!

# 初始化apex客户端
client_apex = init_client()
configs = client_apex.configs()
# 获取apex用户和账户信息
client_apex.get_user()
client_apex.get_account()


# 初始化dydx客户端
client_dydx = init_dydx_client()
# 获取我们的dydx仓位 ID
account_response = client_dydx.private.get_account()
position_id = account_response.data['account']['positionId']

arbitrage_count = 0


async def execute_trade(client_apex, client_dydx, position_id, market, spread1, spread2, size, price1,price2, symbol,s_first_price,b_first_price):
    global arbitrage_count
    if spread1 > 0.7:
        if arbitrage_count<8:
            currentTime = time.time()
            limitFeeRate = client_apex.account['takerFeeRate']
            task_apex_sell = asyncio.create_task(
                send_order_apex(client_apex, symbol=symbol, side="SELL",
                                type="MARKET", size=size, expirationEpochSeconds=currentTime+100,
                                price=price1, limitFeeRate=limitFeeRate)
            )
            task_dydx_buy = asyncio.create_task(
                send_order_dydx(client_dydx, position_id, market, ORDER_SIDE_BUY, ORDER_TYPE_LIMIT,
                                True, size, b_first_price, '0.0015', currentTime+100)
            )
            arbitrage_count += 1
            orderResult1 = await task_apex_sell
            orderResult2 = await task_dydx_buy
            print(orderResult1, orderResult2)

    if spread2 > 0.7:
        if arbitrage_count >-8:
            currentTime = time.time()
            limitFeeRate = client_apex.account['takerFeeRate']
            task_apex_buy = asyncio.create_task(
                send_order_apex(client_apex, symbol=symbol, side="BUY",
                                type="MARKET", size=size, expirationEpochSeconds=currentTime+100,
                                price=price2, limitFeeRate=limitFeeRate)
            )
            task_dydx_sell = asyncio.create_task(
                send_order_dydx(client_dydx, position_id, market, ORDER_SIDE_SELL, ORDER_TYPE_LIMIT,
                                True, size, s_first_price, '0.0015', currentTime+100)
            )
            arbitrage_count -= 1
            orderResult1 = await task_apex_buy
            orderResult2 = await task_dydx_sell
            print(orderResult1, orderResult2)


async def arbitrage():
    while True:
        # 计算价差
        _, _, s_first_price_dydx_btc, b_first_price_dydx_btc, _, _, _, _, spread1_btc, spread2_btc = await calculate_spread_btc()
        _, _, s_first_price_dydx_eth, b_first_price_dydx_eth, _, _, _, _, spread1_eth, spread2_eth = await calculate_spread_eth()
        _, _, s_first_price_dydx_link, b_first_price_dydx_link, _, _, _, _, spread1_link, spread2_link = await calculate_spread_link()
        _, _, s_first_price_dydx_ltc, b_first_price_dydx_ltc, _, _, _, _, spread1_ltc, spread2_ltc = await calculate_spread_ltc()
        _, _, s_first_price_dydx_avax, b_first_price_dydx_avax, _, _, _, _, spread1_avax, spread2_avax = await calculate_spread_avax()
        _, _, s_first_price_dydx_atom, b_first_price_dydx_atom, _, _, _, _, spread1_atom, spread2_atom = await calculate_spread_atom()
        _, _, s_first_price_dydx_doge, b_first_price_dydx_doge, _, _, _, _, spread1_doge, spread2_doge = await calculate_spread_doge()
        _, _, s_first_price_dydx_bch, b_first_price_dydx_bch, _, _, _, _, spread1_bch, spread2_bch = await calculate_spread_bch()
        _, _, s_first_price_dydx_matic, b_first_price_dydx_matic, _, _, _, _, spread1_matic, spread2_matic = await calculate_spread_matic()
        _, _, s_first_price_dydx_sol, b_first_price_dydx_sol, _, _, _, _, spread1_sol, spread2_sol = await calculate_spread_sol()
        # 根据价差判断是否发送交易

        await execute_trade(client_apex, client_dydx, position_id, MARKET_BTC_USD, spread1_btc, spread2_btc, '0.001', '18888','58888', 'BTC-USDC',s_first_price_dydx_btc,b_first_price_dydx_btc)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_ETH_USD, spread1_eth, spread2_eth, '0.01', '888','5888', 'ETH-USDC',s_first_price_dydx_eth,b_first_price_dydx_eth)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_LINK_USD, spread1_link, spread2_link, '1', '8','58', 'LINK-USDC',s_first_price_dydx_link,b_first_price_dydx_link)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_LTC_USD, spread1_ltc, spread2_ltc, '0.5', '48', '488','LTC-USDC',s_first_price_dydx_ltc,b_first_price_dydx_ltc)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_AVAX_USD, spread1_avax, spread2_avax, '1', '8', '188','AVAX-USDC',s_first_price_dydx_avax,b_first_price_dydx_avax)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_ATOM_USD, spread1_atom, spread2_atom, '3', '4', '88','ATOM-USDC',s_first_price_dydx_atom,b_first_price_dydx_atom)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_DOGE_USD, spread1_doge, spread2_doge, '300', '0.04', '2','DOGE-USDC',s_first_price_dydx_doge,b_first_price_dydx_doge)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_BCH_USD, spread1_bch, spread2_bch, '0.1', '88', '588','BCH-USDC',s_first_price_dydx_bch,b_first_price_dydx_bch)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_MATIC_USD, spread1_matic, spread2_matic, '30', '0.1', '4','MATIC-USDC',s_first_price_dydx_matic,b_first_price_dydx_matic)
        await execute_trade(client_apex, client_dydx, position_id, MARKET_SOL_USD, spread1_sol, spread2_sol, '0.5', '48', '488','SOL-USDC',s_first_price_dydx_sol,b_first_price_dydx_sol)
        # 调用 execute_trade 处理其他币种的交易逻辑

        await asyncio.sleep(1)


# 运行异步函数
asyncio.run(arbitrage())

重写运行文件:

python 复制代码
import subprocess
import time

def run_program(file_choice):
    if file_choice == "1":
        process = subprocess.Popen(["python", "place_order_btc.py"])
    elif file_choice == "2":
        process = subprocess.Popen(["python", "place_order_eth.py"])
    elif file_choice == "3":
        process = subprocess.Popen(["python", "place_order_link.py"])
    elif file_choice == "4":
        process = subprocess.Popen(["python", "place_order_ltc.py"])
    elif file_choice == "5":
        process = subprocess.Popen(["python", "place_order_avax.py"])
    elif file_choice == "6":
        process = subprocess.Popen(["python", "place_order_atom.py"])
    elif file_choice == "7":
        process = subprocess.Popen(["python", "place_order_doge.py"])
    elif file_choice == "8":
        process = subprocess.Popen(["python", "place_order_bch.py"])
    elif file_choice == "9":
        process = subprocess.Popen(["python", "place_order_matic.py"])
    elif file_choice == "10":
        process = subprocess.Popen(["python", "place_order_sol.py"])
    elif file_choice == "11":
        process = subprocess.Popen(["python","place_order_all.py"])
    else:
        print("无效的选择")
        return None
    return process

if __name__ == "__main__":
    while True:
        choice = input("请输入要运行的文件(1-btc,2-eth,3-link,4-ltc,5-avax,6-atom,7-doge,8-bch,9-matic,10-sol,11-all ):")
        program = run_program(choice)
        if program:
            while program.poll() is None:
                time.sleep(5)
            print("程序已终止,重新启动中...")
            time.sleep(3)

大体到此结束,之后还有一些小优化将于下期更新

相关推荐
大模型铲屎官1 小时前
【Python-Day 14】玩转Python字典(上篇):从零开始学习创建、访问与操作
开发语言·人工智能·pytorch·python·深度学习·大模型·字典
yunvwugua__1 小时前
Python训练营打卡 Day27
开发语言·python
Stara05112 小时前
基于多头自注意力机制(MHSA)增强的YOLOv11主干网络—面向高精度目标检测的结构创新与性能优化
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·yolov11
那雨倾城3 小时前
使用 OpenCV 将图像中标记特定颜色区域
人工智能·python·opencv·计算机视觉·视觉检测
LuckyTHP5 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
mahuifa7 小时前
(7)python开发经验
python·qt·pyside6·开发经验
CertiK8 小时前
CertiK荣获以太坊基金会两项资助,领跑zkEVM形式化验证
web3·区块链·以太坊
学地理的小胖砸8 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
安迪小宝8 小时前
6 任务路由与负载均衡
运维·python·celery
Blossom.1188 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算