浏览代码

一些交易规则的封装。

skyfffire 5 月之前
父节点
当前提交
bb165041a8
共有 3 个文件被更改,包括 79 次插入57 次删除
  1. 12 11
      arbitrage_process.py
  2. 63 45
      mexc_client.py
  3. 4 1
      ok_chain_client.py

+ 12 - 11
arbitrage_process.py

@@ -21,7 +21,7 @@ def truncate_float_string(number, digits):
 
 
 class ArbitrageProcess:
-    def __init__(self, tx, gas_limit_multiplier, gas_price_multiplier, from_token, to_token, from_token_amount_human):
+    def __init__(self, tx, gas_limit_multiplier, gas_price_multiplier, from_token, to_token, from_token_amount_human, user_exchange_wallet):
         """
         初始化套利流程
 
@@ -42,6 +42,7 @@ class ArbitrageProcess:
         self.gas_price_multiplier = gas_price_multiplier
         self.from_token_addr = from_token
         self.to_token_addr = to_token
+        self.user_exchange_wallet = user_exchange_wallet
 
         # 存储当前套利交易的细节信息,例如买入数量、价格等
         chain_usdt_use = decimal.Decimal(from_token_amount_human)
@@ -50,7 +51,7 @@ class ArbitrageProcess:
             "chain_usdt_use": chain_usdt_use,           # 链上usdt减少量(使用量), todo, 暂用固定值代替
             "chain_buy_amount": None,                   # 链上币增加量(购入量), todo, 暂用即时余额代替
             "chain_buy_price": None,                    # 链上购入价, todo
-            "chain_withdrawal_tx_hash": None,           # 链上转入交易所的id
+            "chain_withdrawal_tx_hash": None,           # 链上转入交易所的tx
             "exchange_sell_order_id": None,             # 交易所卖出id
             "exchange_withdraw_id": None,               # 交易所提现id
             "exchange_withdraw_amount": None,           # 交易所提现数量
@@ -183,7 +184,7 @@ class ArbitrageProcess:
             if receipt.status == 1:
                 logging.info("链上交易已确认。")
                 # 在这里根据实际链上交易结果更新实际买入数量,用于后续流程
-                actual_buy_amount = web3.get_erc20_balance(self.to_token_addr)
+                actual_buy_amount = web3.get_erc20_balance(self.to_token_addr, self.user_exchange_wallet)
                 self.arbitrage_details["chain_buy_amount"] = actual_buy_amount # 存储实际买入数量
 
                 buy_amount_human = actual_buy_amount.quantize(decimal.Decimal('1e-2'), rounding=ROUND_DOWN)
@@ -270,10 +271,8 @@ class ArbitrageProcess:
         logging.info("执行:链上资产转账到交易所...")
         try:
             # 在将资产发送到交易所之前,需要先获取交易所的充值地址
-            # deposit_address = self.exchange_client.get_deposit_address(self.token_address)
-
-            # pseudo_amount_to_transfer = self.arbitrage_details.get("actual_buy_amount", self.arbitrage_details["amount"]) # 使用实际买入数量或预估数量
-            pseudo_amount_to_transfer = self.arbitrage_details["amount"] # 简化处理,使用预估数量
+            deposit_address = self.exchange_client.get_deposit_address(self.token_address)
+            pseudo_amount_to_transfer = self.arbitrage_details.get("actual_buy_amount")
 
             # 伪代码:从链上地址向交易所充值地址发送资产
             # chain_transfer_tx_hash = self.blockchain_client.transfer(
@@ -527,18 +526,20 @@ if __name__ == "__main__":
 
     CHAIN_ID = 1
     FROM_TOKEN = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
-    FROM_TOKEN_AMOUNT_HUMAM = decimal.Decimal('1')
+    FROM_TOKEN_AMOUNT_HUMAM = decimal.Decimal('10')
     FROM_TOKEN_DECIMAL = 6
     TO_TOKEN = '0xf816507E690f5Aa4E29d164885EB5fa7a5627860'
     USER_WALLET = '0xb1f33026Db86a86372493a3B124d7123e9045Bb4'
+    USER_EXCHANGE_WALLET = '0xc71835a042F4d870B0F4296cc89cAeb921a9f3DA'
 
-    # 询价
+    # 询价,注意!!!这里直接把交易所地址当收款方,省去transfer的流程
     data = ok_chain_client.swap(CHAIN_ID, 
                                 FROM_TOKEN_AMOUNT_HUMAM * (10 ** FROM_TOKEN_DECIMAL), 
                                 FROM_TOKEN, 
                                 TO_TOKEN, 
                                 1, 
-                                USER_WALLET
+                                USER_WALLET,
+                                USER_EXCHANGE_WALLET,  # 这里直接把交易所地址当收款方,省去transfer的流程!!!
                                 )
     if data.get('code') != '0' or not data.get('data'):
             pprint.pprint(data)
@@ -551,7 +552,7 @@ if __name__ == "__main__":
     pprint.pprint(tx)
 
     # 套利流程模拟
-    arbitrage_system = ArbitrageProcess(tx, 1, 1.2, FROM_TOKEN, TO_TOKEN, FROM_TOKEN_AMOUNT_HUMAM)
+    arbitrage_system = ArbitrageProcess(tx, 2, 1.2, FROM_TOKEN, TO_TOKEN, FROM_TOKEN_AMOUNT_HUMAM, USER_EXCHANGE_WALLET)
 
     # 一般都是从这个流程开始,测试时可以稍作修改、测试后续流程
     arbitrage_system._set_state(arbitrage_system.STATE_BUYING_ON_CHAIN)

+ 63 - 45
mexc_client.py

@@ -422,27 +422,27 @@ if __name__ == '__main__':
         print(f"初始化过程中发生意外错误: {e}")
         exit()
 
-    print("\n--- 测试公共接口 ---")
-    try:
-        print("Ping 服务器...")
-        ping_response = client.market.get_ping()
-        print(f"Ping 响应: {ping_response}")
-
-        print("\n获取服务器时间...")
-        time_response = client.market.get_timestamp()
-        print(f"服务器时间响应: {time_response}")
-        if isinstance(time_response, dict) and 'serverTime' in time_response:
-             print(f"服务器时间: {time_response['serverTime']}")
+    # print("\n--- 测试公共接口 ---")
+    # try:
+    #     print("Ping 服务器...")
+    #     ping_response = client.market.get_ping()
+    #     print(f"Ping 响应: {ping_response}")
+
+    #     print("\n获取服务器时间...")
+    #     time_response = client.market.get_timestamp()
+    #     print(f"服务器时间响应: {time_response}")
+    #     if isinstance(time_response, dict) and 'serverTime' in time_response:
+    #          print(f"服务器时间: {time_response['serverTime']}")
         
-        print("\n获取 BTCUSDT Ticker 价格...") # get_price 示例
-        price_response = client.market.get_price(params={"symbol": "BTCUSDT"})
-        print(f"BTCUSDT 价格响应: {price_response}")
+    #     print("\n获取 BTCUSDT Ticker 价格...") # get_price 示例
+    #     price_response = client.market.get_price(params={"symbol": "BTCUSDT"})
+    #     print(f"BTCUSDT 价格响应: {price_response}")
 
 
-    except requests.exceptions.RequestException as e:
-        print(f"  公共 API 请求期间出错: {e}")
-    except Exception as e:
-        print(f"  发生意外错误: {e}")
+    # except requests.exceptions.RequestException as e:
+    #     print(f"  公共 API 请求期间出错: {e}")
+    # except Exception as e:
+    #     print(f"  发生意外错误: {e}")
 
 
     print("\n--- 测试私有接口 (需要 API Key 和 Secret) ---")
@@ -450,18 +450,38 @@ if __name__ == '__main__':
         print("  在环境变量中未找到 API Key 或 Secret。跳过私有接口测试。")
     else:
         try:
-            print("获取账户信息...")
+            # print("获取账户信息...")
             account_info = client.trade.get_account_info()
-            print("账户信息:")
-            # 打印敏感数据时请小心。测试时,显示有限信息或结构。
-            if isinstance(account_info, dict):
-                print(f"  是否可以交易: {account_info.get('canTrade')}")
-                print(f"  是否可以提现: {account_info.get('canWithdraw')}")
-                print(f"  账户类型: {account_info.get('accountType')}")
-                # print(json.dumps(account_info, indent=2, ensure_ascii=False)) # 取消注释以查看完整响应
-            else:
-                print(f"  意外的响应格式: {account_info}")
-            print(account_info)
+            # # print("账户信息:")
+            # # # 打印敏感数据时请小心。测试时,显示有限信息或结构。
+            # # if isinstance(account_info, dict):
+            # #     print(f"  是否可以交易: {account_info.get('canTrade')}")
+            # #     print(f"  是否可以提现: {account_info.get('canWithdraw')}")
+            # #     print(f"  账户类型: {account_info.get('accountType')}")
+            # #     # print(json.dumps(account_info, indent=2, ensure_ascii=False)) # 取消注释以查看完整响应
+            # # else:
+            # #     print(f"  意外的响应格式: {account_info}")
+            import time
+            import logging
+            # 配置日志
+            logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
+
+            while True:
+                logging.info(account_info['balances'][0])
+                logging.info(client.wallet.get_deposit_list()[0])
+                logging.info('')
+
+                time.sleep(1)
+
+
+            # params = {
+            #     'coin': 'RATO',
+            #     'netWork': 'ETH',
+            # }
+            # # print(client.wallet.post_deposit_address(params))
+            # for deposit in client.wallet.get_deposit_address(params):
+            #     if deposit['netWork'] == 'ETH':
+            #         print(deposit)
 
 
             # print("\n测试下单 (POST /order/test)...")
@@ -517,12 +537,10 @@ if __name__ == '__main__':
             # else:
             #     print(f"  挂单响应: {open_orders}")
 
-            coin_list = client.wallet.get_coinlist()
-
+            # coin_list = client.wallet.get_coinlist()
             # for coin in coin_list:
             #     if 'USDT' in coin['coin']:
             #         networklist = coin['networkList']
-                    
             #         for network in networklist:
             #             print(network)
             '''
@@ -546,21 +564,21 @@ if __name__ == '__main__':
             }
             '''
 
-            print("\n提币测试...")
-            withdraw_params = {
-                'coin': 'USDT',
-                'netWork': 'ETH',
-                'address': '0xb1f33026db86a86372493a3b124d7123e9045bb4',
-                'amount': 10
-            }
-            withdraw_rst = client.wallet.post_withdraw(withdraw_params)
-            print(f"  提笔响应:{withdraw_rst}")
+            # print("\n提币测试...")
+            # withdraw_params = {
+            #     'coin': 'USDT',
+            #     'netWork': 'ETH',
+            #     'address': '0xb1f33026db86a86372493a3b124d7123e9045bb4',
+            #     'amount': 10
+            # }
+            # withdraw_rst = client.wallet.post_withdraw(withdraw_params)
+            # print(f"  提笔响应:{withdraw_rst}")
 
 
-            print("\n获取提币历史信息...")
-            withdraw_list = client.wallet.get_withdraw_list()
-            print("历史信息:")
-            print(f"  {withdraw_list}")
+            # print("\n获取提币历史信息...")
+            # withdraw_list = client.wallet.get_withdraw_list()
+            # print("历史信息:")
+            # print(f"  {withdraw_list}")
         except requests.exceptions.RequestException as e:
             print(f"  私有 API 请求期间出错: {e}")
             if e.response is not None:

+ 4 - 1
ok_chain_client.py

@@ -118,7 +118,7 @@ def send_post_request(request_path, body_params_dict=None):
         print(f"Failed to decode JSON. Response content: {response.text}")
     return None
 
-def swap(chain_id, amount, from_token_address, to_token_address, slippage, user_wallet_address):
+def swap(chain_id, amount, from_token_address, to_token_address, slippage, user_wallet_address, receiver_address=None):
     get_request_path = '/api/v5/dex/aggregator/swap'
     get_params = {
         'chainIndex': chain_id,
@@ -129,6 +129,9 @@ def swap(chain_id, amount, from_token_address, to_token_address, slippage, user_
         'userWalletAddress': user_wallet_address
     }
 
+    if receiver_address is not None:
+        get_params['swapReceiverAddress'] = receiver_address
+
     return send_get_request(get_request_path, get_params)
 
 def approve(chain_id, token_contract_address, approve_amount):