Last active
August 13, 2024 06:44
-
-
Save daviddwlee84/4942f3c97f40d2460a84e3bcbeaf2be7 to your computer and use it in GitHub Desktop.
Subscribe DEPTH and TRADE from Pionex WebSocket with Socks5 Proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from urllib.parse import urlparse | |
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple PySocks websockets asyncio | |
import asyncio | |
import ssl | |
# https://github.com/Anorov/PySocks | |
import socks | |
# https://github.com/python-websockets/websockets | |
import websockets | |
import json | |
URL = "https://pionex.com" | |
# https://pionex-doc.gitbook.io/apidocs/websocket/general-info#subscribe | |
async def subscribe_to_topics(websocket, symbol): | |
# Subscribe to DEPTH | |
depth_subscription = {"op": "SUBSCRIBE", "topic": "DEPTH", "symbol": symbol} | |
await websocket.send(json.dumps(depth_subscription)) | |
print(f"Subscribed to DEPTH for {symbol}") | |
# Subscribe to TRADE | |
trade_subscription = {"op": "SUBSCRIBE", "topic": "TRADE", "symbol": symbol} | |
await websocket.send(json.dumps(trade_subscription)) | |
print(f"Subscribed to TRADE for {symbol}") | |
async def receive_messages(websocket): | |
async for message in websocket: | |
print(f"Received message: {message}") | |
# https://websockets.readthedocs.io/en/stable/reference/features.html#client | |
# https://github.com/python-websockets/websockets/issues/475 | |
async def main(): | |
netloc = urlparse(URL).netloc | |
ws_url = f"wss://ws.{netloc}/wsPub" | |
# Disable SSL verification (self-signed certificate) | |
ssl_context = ssl.SSLContext() | |
ssl_context.verify_mode = ssl.CERT_NONE | |
ssl_context.check_hostname = False | |
# Initialize the connection to the server through the proxy | |
tor_proxy = socks.socksocket() | |
tor_proxy.set_proxy(socks.SOCKS5, "localhost", 7890) | |
tor_proxy.connect((netloc, 443)) | |
# No ping and high timeout since tor is slow | |
async with websockets.connect( | |
ws_url, | |
ssl=ssl_context, | |
sock=tor_proxy, | |
server_hostname=netloc, | |
ping_interval=None, | |
ping_timeout=None, | |
open_timeout=60, | |
) as websocket: | |
# Subscribe to DEPTH and TRADE for the symbol BTC_USDT | |
await subscribe_to_topics(websocket, "BTC_USDT") | |
# Listen for incoming messages | |
await receive_messages(websocket) | |
asyncio.get_event_loop().run_until_complete(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment