price_checker.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import requests
  2. import decimal # 导入 decimal 模块,用于更精确的货币运算
  3. import time # 导入 time 模块,用于实现轮询间隔
  4. # --- 配置部分 (与之前代码相同,此处省略以保持简洁) ---
  5. # proxies = None # 如果不使用代理
  6. GATEIO_SPOT_PAIR = 'MUBARAK_USDT'
  7. # BSC (币安智能链) 代币地址
  8. IN_TOKEN_ADDRESS_BSC = '0x55d398326f99059ff775485246999027b3197955' # BSC 上的 USDT 代币合约地址
  9. OUT_TOKEN_ADDRESS_BSC = '0x5C85D6C6825aB4032337F11Ee92a72DF936b46F6'
  10. AMOUNT_TO_QUERY_HUMAN = decimal.Decimal('1000') # 查询数量设置为1个单位的输入代币
  11. PROXY_HOST = '127.0.0.1'
  12. PROXY_PORT = '7890'
  13. proxies = {
  14. 'http': f'http://{PROXY_HOST}:{PROXY_PORT}',
  15. 'https': f'http://{PROXY_HOST}:{PROXY_PORT}',
  16. }
  17. # --- OpenOcean 和 Gate.io 的价格获取函数 (get_openocean_price_bsc, get_gateio_spot_price) ---
  18. # (这些函数与您上一版本代码中的基本一致,确保它们返回包含 'rate_out_per_in' 或 'price_base_in_quote' 的字典,
  19. # 或者在出错时返回包含 'error' 键的字典)
  20. # 为了完整性,我将它们包含进来,但假设它们是上一版本中我们确认过的:
  21. def get_openocean_price_bsc(in_token_addr, out_token_addr, human_amount_in_decimal, gas_price=3):
  22. chain = 'bsc'
  23. url = f'https://open-api.openocean.finance/v4/{chain}/quote'
  24. params = {
  25. 'inTokenAddress': in_token_addr,
  26. 'outTokenAddress': out_token_addr,
  27. 'amount': str(human_amount_in_decimal),
  28. 'gasPrice': gas_price,
  29. }
  30. try:
  31. response = requests.get(url, params=params, proxies=proxies, timeout=10)
  32. response.raise_for_status()
  33. data = response.json()
  34. print(data)
  35. if data.get('code') == 200 and data.get('data') and data['data'].get('outToken'):
  36. out_token_info = data['data']['outToken']
  37. human_out_amount_str = out_token_info.get('volume')
  38. if human_out_amount_str is not None:
  39. human_out_amount_decimal = decimal.Decimal(str(human_out_amount_str))
  40. if human_amount_in_decimal > 0:
  41. rate = human_amount_in_decimal / human_out_amount_decimal
  42. return {"rate_out_per_in": rate}
  43. else:
  44. return {"error": "输入金额为零"}
  45. else:
  46. return {"error": "未找到outToken.volume"}
  47. else:
  48. error_message = data.get('message', 'N/A') if data else '无响应数据'
  49. error_code = data.get('code', 'N/A') if data else 'N/A'
  50. return {"error": f"OO API Err Code: {error_code}, Msg: {error_message}"}
  51. except requests.exceptions.RequestException as e:
  52. return {"error": f"OO请求失败: {e}"}
  53. except Exception as e:
  54. return {"error": f"OO意外错误: {e}"}
  55. def get_gateio_spot_price(pair_symbol):
  56. url = f'https://api.gateio.ws/api/v4/spot/tickers'
  57. params = {'currency_pair': pair_symbol}
  58. try:
  59. response = requests.get(url, params=params, proxies=proxies, timeout=10)
  60. response.raise_for_status()
  61. data = response.json()
  62. if isinstance(data, list) and len(data) > 0:
  63. ticker_data = data[0]
  64. if ticker_data.get('currency_pair') == pair_symbol:
  65. last_price_str = ticker_data.get('last')
  66. if last_price_str:
  67. return {"price_base_in_quote": decimal.Decimal(last_price_str)}
  68. else:
  69. return {"error": "Gate未找到last price"}
  70. else:
  71. return {"error": f"Gate交易对不匹配"}
  72. else:
  73. return {"error": "Gate API数据格式错误"}
  74. except requests.exceptions.RequestException as e:
  75. return {"error": f"Gate请求失败: {e}"}
  76. except Exception as e:
  77. return {"error": f"Gate意外错误: {e}"}
  78. # --- 主逻辑 (已修改) ---
  79. def main():
  80. print(f"开始轮询价格 (每秒一次), BSC vs Gate.io {GATEIO_SPOT_PAIR}")
  81. print("按 Ctrl+C 停止。")
  82. # 打印表头,使用格式化字符串使其对齐
  83. header = f"{'OpenOcean ':<25} | {'Gate.io ':<25} | {'价差百分比':<15}"
  84. print(header)
  85. print("-" * (25 + 3 + 25 + 3 + 15)) # 打印与表头长度匹配的分隔线
  86. try:
  87. while True:
  88. # --- 初始化本轮迭代的变量 ---
  89. oo_rate_usdc_per_usdt = None # OpenOcean 的汇率 (1 USDT = X USDC)
  90. gate_rate_usdc_per_usdt_inverted = None # Gate.io 转换后的汇率 (1 USDT = X USDC)
  91. oo_display_str = "N/A" # OpenOcean 在最终输出行中显示的字符串
  92. gate_display_str = "N/A" # Gate.io 在最终输出行中显示的字符串
  93. diff_percentage_display_str = "N/A" # 价差百分比在最终输出行中显示的字符串
  94. oo_error_this_iteration = None # 存储本轮OpenOcean的错误信息
  95. gate_error_this_iteration = None # 存储本轮Gate.io的错误信息
  96. # --- 1. OpenOcean BSC 查询 ---
  97. oo_price_data = get_openocean_price_bsc(
  98. IN_TOKEN_ADDRESS_BSC,
  99. OUT_TOKEN_ADDRESS_BSC,
  100. AMOUNT_TO_QUERY_HUMAN
  101. )
  102. if "error" not in oo_price_data:
  103. oo_rate_usdc_per_usdt = oo_price_data['rate_out_per_in']
  104. oo_display_str = f"{oo_rate_usdc_per_usdt:.6f}" # 格式化价格
  105. else:
  106. oo_error_this_iteration = oo_price_data['error'] # 记录错误信息
  107. # --- 2. Gate.io 现货查询 ---
  108. gate_price_data = get_gateio_spot_price(GATEIO_SPOT_PAIR)
  109. if "error" not in gate_price_data:
  110. gate_rate_usdt_per_usdc = gate_price_data['price_base_in_quote']
  111. if gate_rate_usdt_per_usdc is not None and gate_rate_usdt_per_usdc > 0:
  112. # 转换 Gate.io 的汇率方向为 1 USDT = Y USDC (Y = 1 / X)
  113. gate_rate_usdc_per_usdt_inverted = gate_rate_usdt_per_usdc
  114. gate_display_str = f"{gate_rate_usdc_per_usdt_inverted:.6f}" # 格式化价格
  115. elif gate_rate_usdt_per_usdc is not None: # 价格为0或负数
  116. gate_error_this_iteration = f"Gate.io 无效汇率 ({gate_rate_usdt_per_usdc})"
  117. gate_display_str = "Invalid" # 在行内显示为无效
  118. # else: price_base_in_quote is None, error already handled by "error" key check
  119. else:
  120. gate_error_this_iteration = gate_price_data['error'] # 记录错误信息
  121. # --- 3. 计算价差百分比 (仅当两边价格都有效时) ---
  122. if oo_rate_usdc_per_usdt is not None and gate_rate_usdc_per_usdt_inverted is not None:
  123. if gate_rate_usdc_per_usdt_inverted != 0: # 避免除以零
  124. # 价差 = OpenOcean汇率 - Gate.io转换后汇率
  125. difference = oo_rate_usdc_per_usdt - gate_rate_usdc_per_usdt_inverted
  126. # 价差百分比 = (价差 / Gate.io转换后汇率) * 100
  127. # 您可以根据需要选择以哪个价格为基准计算百分比,这里以 Gate.io 为基准
  128. percentage_diff = (difference / gate_rate_usdc_per_usdt_inverted) * 100
  129. diff_percentage_display_str = f"{percentage_diff:+.4f}%" # 显示正负号和小数点后4位
  130. else:
  131. diff_percentage_display_str = "Gate.io汇率为0" # Gate.io 汇率为0,无法计算百分比
  132. # --- 4. 打印错误信息 (如果本轮有错误发生) ---
  133. # 这些错误会打印在数据行的上方,以便用户了解具体问题
  134. if oo_error_this_iteration:
  135. print(f"[错误] OpenOcean: {oo_error_this_iteration}")
  136. if gate_error_this_iteration:
  137. print(f"[错误] Gate.io: {gate_error_this_iteration}")
  138. # --- 5. 组合打印在一行 ---
  139. # 使用格式化字符串确保列对齐
  140. print(f"{oo_display_str:<25} | {gate_display_str:<25} | {diff_percentage_display_str:<15}")
  141. time.sleep(1) # 等待1秒
  142. except KeyboardInterrupt: # 允许用户通过 Ctrl+C 来停止脚本
  143. print("\n轮询停止。")
  144. if __name__ == "__main__":
  145. decimal.getcontext().prec = 36 # 设置 decimal 的计算精度
  146. main()