Files
Polymarket/ws_rtds.py

201 lines
6.7 KiB
Python
Raw Normal View History

2026-03-27 12:40:49 -04:00
import asyncio
import json
2026-03-27 17:57:12 +00:00
import logging
import socket
import traceback
from datetime import datetime
from typing import AsyncContextManager
import numpy as np
2026-03-27 12:40:49 -04:00
import pandas as pd
2026-03-27 17:57:12 +00:00
import requests.packages.urllib3.util.connection as urllib3_cn # type: ignore
from sqlalchemy import text
2026-03-27 12:40:49 -04:00
import websockets
2026-03-27 17:57:12 +00:00
from sqlalchemy.ext.asyncio import create_async_engine
2026-03-29 16:27:58 +00:00
import valkey
2026-03-27 17:57:12 +00:00
### Allow only ipv4 ###
def allowed_gai_family():
return socket.AF_INET
urllib3_cn.allowed_gai_family = allowed_gai_family
### Database ###
USE_DB: bool = True
2026-03-29 16:27:58 +00:00
USE_VK: bool = True
VK_CHANNEL = 'poly_rtds_cl_btcusd'
2026-03-27 17:57:12 +00:00
CON: AsyncContextManager | None = None
2026-03-29 16:27:58 +00:00
VAL_KEY = None
2026-03-27 12:40:49 -04:00
2026-03-27 17:57:12 +00:00
### Logging ###
LOG_FILEPATH: str = '/root/logs/Polymarket_RTDS.log'
### Globals ###
2026-03-27 12:40:49 -04:00
WSS_URL = "wss://ws-live-data.polymarket.com"
2026-03-27 17:57:12 +00:00
# HIST_TRADES = np.empty((0, 2))
### Database Funcs ###
async def create_rtds_btcusd_table(
CON: AsyncContextManager,
engine: str = 'mysql', # mysql | duckdb
) -> None:
if CON is None:
logging.info("NO DB CONNECTION, SKIPPING Create Statements")
else:
if engine == 'mysql':
2026-03-29 16:27:58 +00:00
logging.info('Creating Table if Does Not Exist: poly_rtds_cl_btcusd')
2026-03-27 17:57:12 +00:00
await CON.execute(text("""
2026-03-29 16:27:58 +00:00
CREATE TABLE IF NOT EXISTS poly_rtds_cl_btcusd (
timestamp_arrival BIGINT,
2026-03-27 17:57:12 +00:00
timestamp_msg BIGINT,
timestamp_value BIGINT,
2026-03-29 16:27:58 +00:00
value DOUBLE
2026-03-27 17:57:12 +00:00
);
"""))
await CON.commit()
else:
raise ValueError('Only MySQL engine is implemented')
2026-03-27 12:40:49 -04:00
2026-03-27 17:57:12 +00:00
async def insert_rtds_btcusd_table(
2026-03-29 16:27:58 +00:00
timestamp_arrival: int,
2026-03-27 17:57:12 +00:00
timestamp_msg: int,
timestamp_value: int,
value: int,
CON: AsyncContextManager,
engine: str = 'mysql', # mysql | duckdb
) -> None:
params={
2026-03-29 16:27:58 +00:00
'timestamp_arrival': timestamp_arrival,
2026-03-27 17:57:12 +00:00
'timestamp_msg': timestamp_msg,
'timestamp_value': timestamp_value,
'value': value,
}
if CON is None:
logging.info("NO DB CONNECTION, SKIPPING Insert Statements")
else:
if engine == 'mysql':
await CON.execute(text("""
2026-03-29 16:27:58 +00:00
INSERT INTO poly_rtds_cl_btcusd
2026-03-27 17:57:12 +00:00
(
2026-03-29 16:27:58 +00:00
timestamp_arrival,
2026-03-27 17:57:12 +00:00
timestamp_msg,
timestamp_value,
value
)
VALUES
(
2026-03-29 16:27:58 +00:00
:timestamp_arrival,
2026-03-27 17:57:12 +00:00
:timestamp_msg,
:timestamp_value,
:value
)
"""),
parameters=params
)
await CON.commit()
else:
raise ValueError('Only MySQL engine is implemented')
2026-03-27 12:40:49 -04:00
2026-03-27 17:57:12 +00:00
### Websocket ###
2026-03-27 12:40:49 -04:00
async def rtds_stream():
global HIST_TRADES
2026-03-29 16:27:58 +00:00
async for websocket in websockets.connect(WSS_URL):
2026-03-27 17:57:12 +00:00
logging.info(f"Connected to {WSS_URL}")
2026-03-27 12:40:49 -04:00
subscribe_msg = {
"action": "subscribe",
"subscriptions": [
{
"topic": "crypto_prices_chainlink",
"type": "*",
"filters": "{\"symbol\":\"btc/usd\"}"
}
]
}
await websocket.send(json.dumps(subscribe_msg))
try:
async for message in websocket:
if isinstance(message, str):
try:
data = json.loads(message)
if data['payload'].get('value', None) is not None:
2026-03-29 16:27:58 +00:00
ts_arrival = round(datetime.now().timestamp()*1000)
print(f'🤑 BTC Chainlink Last Px: {data['payload']['value']:_.4f}; TS: {pd.to_datetime(data['payload']['timestamp'], unit='ms')}')
VAL_KEY_OBJ = json.dumps({
'timestamp_arrival': ts_arrival,
'timestamp_msg': data['timestamp'],
'timestamp_value': data['payload']['timestamp'],
'value': data['payload']['value'],
})
VAL_KEY.publish(VK_CHANNEL, VAL_KEY_OBJ)
VAL_KEY.set(VK_CHANNEL, VAL_KEY_OBJ)
await insert_rtds_btcusd_table(
CON=CON,
timestamp_arrival=ts_arrival,
timestamp_msg=data['timestamp'],
timestamp_value=data['payload']['timestamp'],
value=data['payload']['value'],
)
2026-03-27 12:40:49 -04:00
else:
2026-03-29 16:27:58 +00:00
# logging.info(f'Initial or unexpected data struct, skipping: {data}')
logging.info('Initial or unexpected data struct, skipping')
2026-03-27 12:40:49 -04:00
continue
except (json.JSONDecodeError, ValueError):
2026-03-27 17:57:12 +00:00
logging.warning(f'Message not in JSON format, skipping: {message}')
2026-03-27 12:40:49 -04:00
continue
else:
raise ValueError(f'Type: {type(data)} not expected: {message}')
2026-03-27 17:57:12 +00:00
except websockets.ConnectionClosed as e:
logging.error(f'Connection closed: {e}')
logging.error(traceback.format_exc())
2026-03-29 16:27:58 +00:00
continue
2026-03-27 17:57:12 +00:00
except Exception as e:
logging.error(f'Connection closed: {e}')
logging.error(traceback.format_exc())
2026-03-27 12:40:49 -04:00
2026-03-27 17:57:12 +00:00
async def main():
2026-03-29 16:27:58 +00:00
global VAL_KEY
2026-03-27 17:57:12 +00:00
global CON
2026-03-29 16:27:58 +00:00
if USE_VK:
VAL_KEY = valkey.Valkey(host='localhost', port=6379, db=0)
published_count = VAL_KEY.publish(VK_CHANNEL,f"Hola, starting to publish to valkey: {VK_CHANNEL} @ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
logging.info(f"Valkey message published to {published_count} subscribers of {VK_CHANNEL}")
else:
VAL_KEY = None
logging.warning("VALKEY NOT BEING USED, NO DATA WILL BE PUBLISHED")
2026-03-27 17:57:12 +00:00
if USE_DB:
2026-03-29 16:27:58 +00:00
engine = create_async_engine('mysql+asyncmy://root:pwd@localhost/polymarket')
2026-03-27 17:57:12 +00:00
async with engine.connect() as CON:
2026-03-29 16:27:58 +00:00
await create_rtds_btcusd_table(CON=CON)
2026-03-27 17:57:12 +00:00
await rtds_stream()
else:
CON = None
logging.warning("DATABASE NOT BEING USED, NO DATA WILL BE RECORDED")
await rtds_stream()
2026-03-27 12:40:49 -04:00
if __name__ == '__main__':
2026-03-27 17:57:12 +00:00
START_TIME = round(datetime.now().timestamp()*1000)
logging.info(f'Log FilePath: {LOG_FILEPATH}')
logging.basicConfig(
force=True,
filename=LOG_FILEPATH,
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filemode='w'
)
logging.info(f"STARTED: {START_TIME}")
2026-03-27 12:40:49 -04:00
try:
2026-03-27 17:57:12 +00:00
asyncio.run(main())
2026-03-27 12:40:49 -04:00
except KeyboardInterrupt:
2026-03-27 17:57:12 +00:00
logging.info("Stream stopped")