在跨境贸易结算、离岸资产分析、汇率套利以及多币种量化场景中,在岸人民币、离岸人民币汇率是核心监测标的。想要搭建稳定的汇率监控系统,一套易用、数据精准的行情接口尤为关键。
本文基于 PulseData 脉动行情 API,完整讲解美元在岸人民币、美元离岸人民币两种主流品种的接入方式,包含即时查询接口与长连接实时推送两种方案,所有代码均可直接运行。
一、基础接口信息
使用前请联系客服完成服务器 IP 授权。
- 实时行情查询地址:
http://39.107.99.235:1008/getQuote.php - 实时推送 WebSocket 地址:
ws://39.107.99.235/ws - 标准请求头:
Accept-Encoding: gzip,优化数据传输体验
二、对应品种代码
- 美元在岸人民币:
usdcny - 美元离岸人民币:
usdcnh
三、GET 接口实时行情查询
通过 HTTP 接口可以快速获取汇率最新价格、开盘价、高低点、涨跌幅度等全维度数据。
示例访问地址
plaintext
http://39.107.99.235:1008/getQuote.php?code=usdcny,usdcnh
Python 调用代码
python
运行
import requests
# 接口地址
api_url = "http: //39.107.99.235:1008/getQuote.php"
headers = {
"Accept-Encoding": "gzip"
}
# 传入在岸、离岸人民币代码
params = {
"code": "usdcny,usdcnh"
}
response = requests.get(api_url, headers=headers, params=params, timeout=10)
result = response.json()
# 解析并打印行情数据
if result.get("code") == 200:
for item in result["data"]["body"]:
print(f"品种代码:{item['StockCode']}")
print(f"最新价格:{item['Price']}")
print(f"今日开盘:{item['Open']} 昨日收盘:{item['LastClose']}")
print(f"日内最高:{item['High']} 日内最低:{item['Low']}")
print(f"涨跌额:{item['Diff']} 涨跌幅:{item['DiffRate']}%")
print("----------------------------------------")
四、WebSocket 实时行情推送
对于需要 7×24 不间断监控的场景,推荐使用 WebSocket 长连接。服务端行情变动即刻推送,搭配标准心跳机制,保障连接持久稳定。客户端规则:每 10 秒发送一次心跳包,心跳格式 {"ping": 十位时间戳};连接成功后发送订阅指令 {"Key": 品种代码}。
Python 长连接完整代码
python
运行
import websocket
import json
import time
import threading
ws_address = "ws://39.107.99.235/ws"
# 订阅在岸+离岸人民币
sub_code = "usdcny,usdcnh"
# 定时发送心跳
def heartbeat(ws):
while True:
ts = int(time.time())
ws.send(json.dumps({"ping": ts}))
time.sleep(10)
def on_open(ws):
print("连接建立成功,开始订阅汇率行情")
ws.send(json.dumps({"Key": sub_code}))
threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()
def on_message(ws, msg):
data = json.loads(msg)
if "body" in data:
body = data["body"]
print(f"【实时行情】{body['StockCode']} 现价:{body['Price']}")
def on_error(ws, err):
print("连接出现异常")
def on_close(ws, code, msg):
print("连接断开,自动重启连接...")
time.sleep(3)
run_ws()
def run_ws():
ws_app = websocket.WebSocketApp(
ws_address,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws_app.run_forever()
if __name__ == "__main__":
run_ws()
五、K 线数据获取
如需调取历史分时、日线数据,可使用 K 线接口,支持多种时间周期。接口地址:http://39.107.99.235:1008/redis.php示例(离岸人民币 1 分钟 K 线):
plaintext
http://39.107.99.235:1008/redis.php?code=usdcnh&time=1m&rows=100
整套接口数据格式统一,解析逻辑通用,可快速集成到行情终端、量化策略、数据分析平台当中。