從零開始搭建鏈上dex自動化價差套利程序(12)

其他品種

擴展到其他幣種的價差套利

1.eth

新建文件get_depth_data_eth.py

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 task1s_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))*100spread2 = ((float(b_first_price_dydx) - float(s_first_price_apex))/float(s_first_price_dydx))*100return 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,spread2if __name__ == '__main__':# 創建事件循環loop = asyncio.get_event_loop()# 運行異步函數loop.run_until_complete(calculate_spread())# 關閉事件循環loop.close()

新建文件place_order_eth.py

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 = 0while 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_sellorderResult2 = await task_dydx_buyarbitrage_count += 1if 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_buyorderResult2 = await task_dydx_sellarbitrage_count -= 1if 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即可。

所有品種同時運行

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 = 0async def execute_trade(client_apex, client_dydx, position_id, market, spread1, spread2, size, price1,price2, symbol,s_first_price,b_first_price):global arbitrage_countif 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 += 1orderResult1 = await task_apex_sellorderResult2 = await task_dydx_buyprint(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 -= 1orderResult1 = await task_apex_buyorderResult2 = await task_dydx_sellprint(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())

重寫運行文件:

import subprocess
import timedef 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 Nonereturn processif __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)

大體到此結束,之后還有一些小優化將于下期更新

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/212236.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/212236.shtml
英文地址,請注明出處:http://en.pswp.cn/news/212236.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

vue創建時長時間卡頓無結果

vue創建時長時間卡頓無結果 01 發生場景 當我在VS code中使用vue create myVue &#xff08;注&#xff1a;最后一個是我創建的vue項目的文件名&#xff09;指令時在終端內長時間的無反應 02 問題的產生及其原因 經過面向百度編程&#xff0c;得出的第一結論是vue/cil版本過…

【數據結構】——排序篇(下)

前言&#xff1a;前面我們的排序已經詳細的講解了一系列的方法&#xff0c;那么我們現在久之后一個歸并排序了&#xff0c;所以我們現在就來講解一下歸并排序。 歸并排序&#xff1a; 歸并排序&#xff08;MERGE-SORT&#xff09;是建立在歸并操作上的一種有效的排序算法,該算法…

代碼隨想錄二刷 |二叉樹 | 二叉樹的右視圖

代碼隨想錄二刷 &#xff5c;二叉樹 &#xff5c; 二叉樹的右視圖 題目描述解題思路代碼實現 題目描述 199.二叉樹的右視圖 給定一個二叉樹的 根節點 root&#xff0c;想象自己站在它的右側&#xff0c;按照從頂部到底部的順序&#xff0c;返回從右側所能看到的節點值。 示例…

?My學習Linux命令小記錄(15)?

目錄 ?My學習Linux命令小記錄&#xff08;15&#xff09;? 61.history指令 62.apt指令 ①apt-get ②apt-key&#xff1a; ③apt-sortpkgs&#xff1a; ④aptitude&#xff1a; 63.yum指令 64.cal指令 65.init指令 ?My學習Linux命令小記錄&#xff08;15&#xff0…

表格的介紹與實戰(詳細且有案例)

目錄?????????????? 表格的主要作用&#xff1a; 表格的基本語法&#xff1a; 表格相關的標簽 合并單元格&#xff1a; 實戰&#xff1a; 表格的主要作用&#xff1a; 表格主要是用來展示數據的&#xff0c;使用表格來展示數據&#xff0c;數據可讀性更好…

202301209將RK3399的挖掘機開發板在Android10下設置系統默認為24小時制

202301209將RK3399的挖掘機開發板在Android10下設置系統默認為24小時制 2023/12/9 22:07 應該也可以適用于RK3399的Android12系統 --- a/frameworks/base/packages/SettingsProvider/res/values/defaults.xml b/frameworks/base/packages/SettingsProvider/res/values/default…

一文搞懂Lombok Plugins使用與原理

目錄 一文搞懂Lombok使用與原理 1.前言2.什么是Lombok3. IntelliJ安裝Lombok3.1通過IntelliJ的插件中心安裝3.2在項目中使用Lombok Plugins 4.Lombok 注解大全說明4.1POJO類常用注解4.2其他注解 5.Lombok常見問題6.總結7.參考 文章所屬專區 超鏈接 1.前言 2.什么是Lombok Lo…

產品創新受贊譽,懌星榮獲2023未來汽車(電子和軟件)創新創業大賽一等獎

2023未來汽車&#xff08;電子和軟件&#xff09;創新創業大賽 11月29日&#xff0c;上海臨港&#xff0c;由中國汽車工程學會和中國&#xff08;上海&#xff09;自由貿易試驗區臨港新片區管理委員會聯合舉辦的“2023未來汽車&#xff08;電子和軟件&#xff09;創新創業大賽…

二叉搜索樹中第K小的元素[中等]

優質博文&#xff1a;IT-BLOG-CN 一、題目 給定一個二叉搜索樹的根節點root&#xff0c;和一個整數k&#xff0c;請你設計一個算法查找其中第k個最小元素&#xff08;從1開始計數&#xff09;。 示例 1&#xff1a; 輸入&#xff1a;root [3,1,4,null,2], k 1 輸出&#x…

RHEL8_Linux硬盤管理

主要介紹Linux磁盤管理 了解分區的概念對硬盤進行分區常見的分區swap分區的管理 1.了解分區的概念 1&#xff09;新的硬盤首先需要對其進行分區和格式化&#xff0c;下面來了解以下硬盤的結構&#xff0c;如圖。 2&#xff09;硬盤的磁盤上有一個個圈&#xff0c;每兩個圈組…

JVM虛擬機系統性學習-類加載子系統

類加載子系統 類加載的時機 類加載的時機主要有 4 個&#xff1a; 遇到 new、getstatic、putstatic、invokestatic 這四條字節碼指令時&#xff0c;如果對應的類沒有初始化&#xff0c;則要先進行初始化 new 關鍵字創建對象時讀取或設置一個類型的靜態字段時&#xff08;被 …

javaSwing酒店管理系統

一、 使用方法&#xff1a; 在使用前&#xff0c;需要到druid.properties 配置文件中&#xff0c;修改自己對應于自己數據庫的屬性&#xff1b;如用戶名&#xff0c;密碼等 driverClassNamecom.mysql.cj.jdbc.Driver urljdbc:mysql:///hotel?useUnicodetrue&characterEn…

midwayjs從零開始創建項目,連接mikro-orm框架(必須有java的springboot基礎)

前言&#xff1a; 我一直都是用java的springboot開發項目&#xff0c;然后進來新公司之后&#xff0c;公司的后端是用node.js&#xff0c;然后框架用的是 midwayjs &#xff0c;然后網上的資料比較少&#xff0c;在此特地記錄一波 文檔&#xff1a; 1.官方文檔&#xff1a;介紹…

vue 前端crypto-js 如何實現加密解密

npm 安裝 crypto-js 引用 import CryptoJS from "crypto-js"; 或者 import CryptoJS from "crypto-js"; //秘鑰 var aesKey "s10dfc3321ba59abbe123057f20f883e"; //將秘鑰轉換成Utf8字節數組 var key CryptoJS.enc.Utf8.parse(aesKey); /…

Spring Boot 3.0 : 集成flyway數據庫版本控制工具

目錄 Spring Boot 3.0 : 集成flyway數據庫版本控制工具flyway是什么為什么使用flyway主要特性支持的數據庫&#xff1a; flyway如何使用spring boot 集成實現引入依賴配置sql版本控制約定3種版本類型 運行SpringFlyway 8.2.1及以后版本不再支持MySQL&#xff1f; 個人主頁: 【?…

常見web漏洞的流量分析

常見web漏洞的流量分析 文章目錄 常見web漏洞的流量分析工具sql注入的流量分析XSS注入的流量分析文件上傳漏洞流量分析文件包含漏洞流量分析文件讀取漏洞流量分析ssrf流量分析shiro反序列化流量分析jwt流量分析暴力破解流量分析命令執行流量分析反彈shell 工具 攻擊機受害機wi…

Unity DOTS中的baking(一) Baker簡介

Unity DOTS中的baking&#xff08;一&#xff09; Baker簡介 baking是DOTS ECS工作流的一環&#xff0c;大概的意思就是將原先Editor下的GameObject數據&#xff0c;全部轉換為Entity數據的過程。baking是一個不可逆的過程&#xff0c;原先的GameObject在運行時不復存在&#x…

leetcode 股票DP系列 總結篇

121. 買賣股票的最佳時機 你只能選擇 某一天 買入這只股票&#xff0c;并選擇在 未來的某一個不同的日子 賣出該股票。 只能進行一次交易 很簡單&#xff0c;只需邊遍歷邊記錄最小值即可。 class Solution { public:int maxProfit(vector<int>& prices) {int res …

Vue-安裝及安裝vscode相應插件

安裝Vue 安裝nodejs&#xff0c; 地址&#xff1a;https://nodejs.org/en 下載后直接安裝。 安裝后重新打開命令行工具&#xff0c;輸入 node -v PS C:\Users\zcl36> node -v v20.10.0 2. 安裝vue包npm install -g vue/cli安裝之后&#xff0c;你就可以在命令行中訪問 vue…