algo orchestrator

This commit is contained in:
2026-04-25 03:40:47 +00:00
parent afa2d1fd79
commit b0d031d452
11 changed files with 911 additions and 226 deletions

37
_On_Ice/apex_api.py Normal file
View File

@@ -0,0 +1,37 @@
from apexomni.http_private_v3 import HttpPrivate_v3
from apexomni.http_private_sign import HttpPrivateSign
from apexomni.constants import APEX_OMNI_HTTP_MAIN, NETWORKID_MAIN
from dotenv import load_dotenv
import os
def apex_create_client() -> HttpPrivateSign:
load_dotenv()
print("Authenticating...")
eth_private_key = os.getenv("RABBY_PRIVATE_KEY")
key = os.getenv("APEX_API_KEY")
secret = os.getenv("APEX_API_SECRET")
passphrase = os.getenv("APEX_API_PASSPHRASE")
client = HttpPrivate_v3(APEX_OMNI_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key=eth_private_key)
zkKeys = client.derive_zk_key(client.default_address)
seeds = zkKeys['seeds']
l2Key = zkKeys['l2Key']
client = HttpPrivateSign(
APEX_OMNI_HTTP_MAIN,
network_id=NETWORKID_MAIN,
zk_seeds=seeds,
zk_l2Key=l2Key,
api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})
try:
client.configs_v3()
client.get_account_v3()
except Exception as e:
raise ConnectionError(f'Failed to authenticate with APEX OMNI: {e}')
print("...Authenticated")
return client

306
_On_Ice/mexc.ipynb Normal file
View File

@@ -0,0 +1,306 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 15,
"id": "7a3f41bd",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import requests\n",
"from datetime import datetime"
]
},
{
"cell_type": "code",
"execution_count": 44,
"id": "3b48e1ce",
"metadata": {},
"outputs": [],
"source": [
"mexc_all_tickers = 'https://api.mexc.com/api/v1/contract/ticker'\n",
"edgex_all_tickers = 'https://pro.edgex.exchange/api/v1/public/quote/getTicker/?contractId=10000001'"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "ab38d984",
"metadata": {},
"outputs": [],
"source": [
"r = requests.get(mexc_all_tickers)\n",
"data = r.json()['data']"
]
},
{
"cell_type": "code",
"execution_count": 49,
"id": "2976b377",
"metadata": {},
"outputs": [],
"source": [
"r = requests.get(edgex_all_tickers)\n",
"data = r.json()['data']"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "1139b1a3",
"metadata": {},
"outputs": [],
"source": [
"df = pd.DataFrame(data)\n",
"df['fundingRate_pct'] = df['fundingRate']*100"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b00512dc",
"metadata": {},
"outputs": [],
"source": [
"df_trim = df[['symbol','fundingRate_pct','volume24']].copy()\n",
"df_trim = df_trim.loc[df_trim['volume24'] > 10_000]"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "f7b44068",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>symbol</th>\n",
" <th>fundingRate_pct</th>\n",
" <th>volume24</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>55</th>\n",
" <td>DRIFT_USDT</td>\n",
" <td>-1.1360</td>\n",
" <td>3308466</td>\n",
" </tr>\n",
" <tr>\n",
" <th>10</th>\n",
" <td>RED_USDT</td>\n",
" <td>-1.1138</td>\n",
" <td>105826673</td>\n",
" </tr>\n",
" <tr>\n",
" <th>157</th>\n",
" <td>PIXEL_USDT</td>\n",
" <td>-0.4059</td>\n",
" <td>12415472</td>\n",
" </tr>\n",
" <tr>\n",
" <th>105</th>\n",
" <td>NIL_USDT</td>\n",
" <td>-0.3846</td>\n",
" <td>31438005</td>\n",
" </tr>\n",
" <tr>\n",
" <th>33</th>\n",
" <td>SUPER_USDT</td>\n",
" <td>-0.3718</td>\n",
" <td>2469502</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>12</th>\n",
" <td>PLAY_USDT</td>\n",
" <td>0.0838</td>\n",
" <td>22168649</td>\n",
" </tr>\n",
" <tr>\n",
" <th>414</th>\n",
" <td>PUMPBTC_USDT</td>\n",
" <td>0.0913</td>\n",
" <td>745129</td>\n",
" </tr>\n",
" <tr>\n",
" <th>398</th>\n",
" <td>QQQSTOCK_USDT</td>\n",
" <td>0.0969</td>\n",
" <td>59485</td>\n",
" </tr>\n",
" <tr>\n",
" <th>222</th>\n",
" <td>GUA_USDT</td>\n",
" <td>0.0996</td>\n",
" <td>45623</td>\n",
" </tr>\n",
" <tr>\n",
" <th>265</th>\n",
" <td>BROCCOLIF3B_USDT</td>\n",
" <td>0.1647</td>\n",
" <td>3936939</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>837 rows × 3 columns</p>\n",
"</div>"
],
"text/plain": [
" symbol fundingRate_pct volume24\n",
"55 DRIFT_USDT -1.1360 3308466\n",
"10 RED_USDT -1.1138 105826673\n",
"157 PIXEL_USDT -0.4059 12415472\n",
"105 NIL_USDT -0.3846 31438005\n",
"33 SUPER_USDT -0.3718 2469502\n",
".. ... ... ...\n",
"12 PLAY_USDT 0.0838 22168649\n",
"414 PUMPBTC_USDT 0.0913 745129\n",
"398 QQQSTOCK_USDT 0.0969 59485\n",
"222 GUA_USDT 0.0996 45623\n",
"265 BROCCOLIF3B_USDT 0.1647 3936939\n",
"\n",
"[837 rows x 3 columns]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_trim.sort_values('fundingRate_pct', ascending=True)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "6775a03f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1775583908"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"round(datetime.now().timestamp())"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "edca3b9f",
"metadata": {},
"outputs": [],
"source": [
"### PRIVATE API ###\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "51e50e0d",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "21aabf30",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "f91b1c04",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "71e551f4",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "py_313",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

248
_On_Ice/ws_apex.py Normal file
View File

@@ -0,0 +1,248 @@
import asyncio
import json
import logging
import socket
import traceback
from datetime import datetime
from typing import AsyncContextManager
import numpy as np
import pandas as pd
import requests.packages.urllib3.util.connection as urllib3_cn # type: ignore
from sqlalchemy import text
import websockets
from sqlalchemy.ext.asyncio import create_async_engine
import valkey
import os
from dotenv import load_dotenv
### Allow only ipv4 ###
def allowed_gai_family():
return socket.AF_INET
urllib3_cn.allowed_gai_family = allowed_gai_family
### Database ###
USE_DB: bool = False
USE_VK: bool = True
# VK_FUND_RATE = 'fund_rate_apex'
VK_TICKER = 'fut_ticker_apex'
CON: AsyncContextManager | None = None
VAL_KEY = None
### Logging ###
load_dotenv()
LOG_FILEPATH: str = os.getenv("LOGS_PATH") + '/Fund_Rate_Apex.log'
### CONSTANTS ###
PING_INTERVAL_SEC = 15
### Globals ###
WSS_URL = "wss://quote.omni.apex.exchange/realtime_public?v=2&timestamp="
TICKER_SNAPSHOT_DATA_LAST: dict = {}
# HIST_TRADES = np.empty((0, 3))
# HIST_TRADES_LOOKBACK_SEC = 6
# ### 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':
# logging.info('Creating Table if Does Not Exist: binance_btcusd_trades')
# await CON.execute(text("""
# CREATE TABLE IF NOT EXISTS binance_btcusd_trades (
# timestamp_arrival BIGINT,
# timestamp_msg BIGINT,
# timestamp_value BIGINT,
# value DOUBLE,
# qty DOUBLE
# );
# """))
# await CON.commit()
# else:
# raise ValueError('Only MySQL engine is implemented')
# async def insert_rtds_btcusd_table(
# timestamp_arrival: int,
# timestamp_msg: int,
# timestamp_value: int,
# value: float,
# qty: float,
# CON: AsyncContextManager,
# engine: str = 'mysql', # mysql | duckdb
# ) -> None:
# params={
# 'timestamp_arrival': timestamp_arrival,
# 'timestamp_msg': timestamp_msg,
# 'timestamp_value': timestamp_value,
# 'value': value,
# 'qty': qty,
# }
# if CON is None:
# logging.info("NO DB CONNECTION, SKIPPING Insert Statements")
# else:
# if engine == 'mysql':
# await CON.execute(text("""
# INSERT INTO binance_btcusd_trades
# (
# timestamp_arrival,
# timestamp_msg,
# timestamp_value,
# value,
# qty
# )
# VALUES
# (
# :timestamp_arrival,
# :timestamp_msg,
# :timestamp_value,
# :value,
# :qty
# )
# """),
# parameters=params
# )
# await CON.commit()
# else:
# raise ValueError('Only MySQL engine is implemented')
### Websocket ###
async def heartbeat(ws):
while True:
await asyncio.sleep(PING_INTERVAL_SEC)
logging.info("SENDING PING...")
ping_msg = {"op":"ping","args":[ str(round(datetime.now().timestamp()*1000)) ]}
await ws.send(json.dumps(ping_msg))
async def ws_stream():
global TICKER_SNAPSHOT_DATA_LAST
async for websocket in websockets.connect(f'{WSS_URL}{round(datetime.now().timestamp())}'):
logging.info(f"Connected to {WSS_URL}")
asyncio.create_task(heartbeat(ws=websocket))
subscribe_msg = {
"op": "subscribe",
"args": ["instrumentInfo.H.ETHUSDT"]
}
await websocket.send(json.dumps(subscribe_msg))
try:
async for message in websocket:
ts_arrival = round(datetime.now().timestamp()*1000)
if isinstance(message, str):
try:
data = json.loads(message)
if data.get('op', None) == 'ping':
pong_msg = {"op":"pong","args":[ str(round(datetime.now().timestamp()*1000)) ]}
logging.info(f'RECEIVED PING: {data}; SENDING PONG: {pong_msg}')
await websocket.send(json.dumps(pong_msg))
continue
elif data.get('success', None):
# logging.info('CONNECTION SUCCESFUL RESP MSG')
continue
msg_type = data.get('type', None)
if msg_type is not None:
match msg_type:
case 'snapshot':
TICKER_SNAPSHOT_DATA_LAST = data['data']
nextFundingTime_ts = round(datetime.strptime(TICKER_SNAPSHOT_DATA_LAST['nextFundingTime'], "%Y-%m-%dT%H:%M:%SZ").timestamp()*1000)
VAL_KEY_OBJ = json.dumps({
'timestamp_arrival': ts_arrival,
'timestamp_msg': data['ts'],
'symbol': TICKER_SNAPSHOT_DATA_LAST['symbol'],
'lastPrice': float(TICKER_SNAPSHOT_DATA_LAST['lastPrice']),
'markPrice': float(TICKER_SNAPSHOT_DATA_LAST['markPrice']),
'indexPrice': float(TICKER_SNAPSHOT_DATA_LAST['indexPrice']),
'volume24h': float(TICKER_SNAPSHOT_DATA_LAST['volume24h']),
'fundingRate': float(TICKER_SNAPSHOT_DATA_LAST['fundingRate']),
'predictedFundingRate': float(TICKER_SNAPSHOT_DATA_LAST['predictedFundingRate']),
'nextFundingTime_ts_ms': nextFundingTime_ts,
})
VAL_KEY.set(VK_TICKER, VAL_KEY_OBJ)
continue
case 'delta':
TICKER_SNAPSHOT_DATA_LAST.update(data['data'])
nextFundingTime_ts = round(datetime.strptime(TICKER_SNAPSHOT_DATA_LAST['nextFundingTime'], "%Y-%m-%dT%H:%M:%SZ").timestamp()*1000)
VAL_KEY_OBJ = json.dumps({
'timestamp_arrival': ts_arrival,
'timestamp_msg': data['ts'],
'symbol': TICKER_SNAPSHOT_DATA_LAST['symbol'],
'lastPrice': float(TICKER_SNAPSHOT_DATA_LAST['lastPrice']),
'markPrice': float(TICKER_SNAPSHOT_DATA_LAST['markPrice']),
'indexPrice': float(TICKER_SNAPSHOT_DATA_LAST['indexPrice']),
'volume24h': float(TICKER_SNAPSHOT_DATA_LAST['volume24h']),
'fundingRate': float(TICKER_SNAPSHOT_DATA_LAST['fundingRate']),
'predictedFundingRate': float(TICKER_SNAPSHOT_DATA_LAST['predictedFundingRate']),
'nextFundingTime_ts_ms': nextFundingTime_ts,
})
VAL_KEY.set(VK_TICKER, VAL_KEY_OBJ)
continue
case _:
logging.warning(f'UNMATCHED OTHER MSG: {data}')
else:
logging.info(f'Initial or unexpected data struct, skipping: {data}')
continue
except (json.JSONDecodeError, ValueError):
logging.warning(f'Message not in JSON format, skipping: {message}')
continue
else:
raise ValueError(f'Type: {type(data)} not expected: {message}')
except websockets.ConnectionClosed as e:
logging.error(f'Connection closed: {e}')
logging.error(traceback.format_exc())
continue
except Exception as e:
logging.error(f'Connection closed: {e}')
logging.error(traceback.format_exc())
async def main():
global VAL_KEY
global CON
if USE_VK:
VAL_KEY = valkey.Valkey(host='localhost', port=6379, db=0)
else:
VAL_KEY = None
logging.warning("VALKEY NOT BEING USED, NO DATA WILL BE PUBLISHED")
if USE_DB:
engine = create_async_engine('mysql+asyncmy://root:pwd@localhost/fund_rate')
async with engine.connect() as CON:
# await create_rtds_btcusd_table(CON=CON)
await ws_stream()
else:
CON = None
logging.warning("DATABASE NOT BEING USED, NO DATA WILL BE RECORDED")
await ws_stream()
if __name__ == '__main__':
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}")
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info("Stream stopped")

244
_On_Ice/ws_mexc.py Normal file
View File

@@ -0,0 +1,244 @@
import asyncio
import json
import logging
import socket
import traceback
from datetime import datetime
from typing import AsyncContextManager
import numpy as np
import pandas as pd
import requests.packages.urllib3.util.connection as urllib3_cn # type: ignore
from sqlalchemy import text
import websockets
from sqlalchemy.ext.asyncio import create_async_engine
import valkey
import os
from dotenv import load_dotenv
### Allow only ipv4 ###
def allowed_gai_family():
return socket.AF_INET
urllib3_cn.allowed_gai_family = allowed_gai_family
### Database ###
USE_DB: bool = False
USE_VK: bool = True
VK_FUND_RATE = 'fund_rate_mexc'
VK_TICKER = 'fut_ticker_mexc'
CON: AsyncContextManager | None = None
VAL_KEY = None
### Logging ###
load_dotenv()
LOG_FILEPATH: str = os.getenv("LOGS_PATH") + '/Fund_Rate_MEXC.log'
### CONSTANTS ###
PING_INTERVAL_SEC = 20
### Globals ###
WSS_URL = "wss://contract.mexc.com/edge"
# HIST_TRADES = np.empty((0, 3))
# HIST_TRADES_LOOKBACK_SEC = 6
# ### 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':
# logging.info('Creating Table if Does Not Exist: binance_btcusd_trades')
# await CON.execute(text("""
# CREATE TABLE IF NOT EXISTS binance_btcusd_trades (
# timestamp_arrival BIGINT,
# timestamp_msg BIGINT,
# timestamp_value BIGINT,
# value DOUBLE,
# qty DOUBLE
# );
# """))
# await CON.commit()
# else:
# raise ValueError('Only MySQL engine is implemented')
# async def insert_rtds_btcusd_table(
# timestamp_arrival: int,
# timestamp_msg: int,
# timestamp_value: int,
# value: float,
# qty: float,
# CON: AsyncContextManager,
# engine: str = 'mysql', # mysql | duckdb
# ) -> None:
# params={
# 'timestamp_arrival': timestamp_arrival,
# 'timestamp_msg': timestamp_msg,
# 'timestamp_value': timestamp_value,
# 'value': value,
# 'qty': qty,
# }
# if CON is None:
# logging.info("NO DB CONNECTION, SKIPPING Insert Statements")
# else:
# if engine == 'mysql':
# await CON.execute(text("""
# INSERT INTO binance_btcusd_trades
# (
# timestamp_arrival,
# timestamp_msg,
# timestamp_value,
# value,
# qty
# )
# VALUES
# (
# :timestamp_arrival,
# :timestamp_msg,
# :timestamp_value,
# :value,
# :qty
# )
# """),
# parameters=params
# )
# await CON.commit()
# else:
# raise ValueError('Only MySQL engine is implemented')
### Websocket ###
async def heartbeat(ws):
while True:
await asyncio.sleep(PING_INTERVAL_SEC)
logging.info("SENDING PING...")
ping_msg = {
"method": "ping"
}
await ws.send(json.dumps(ping_msg))
async def ws_stream():
# global HIST_TRADES
async for websocket in websockets.connect(WSS_URL):
logging.info(f"Connected to {WSS_URL}")
asyncio.create_task(heartbeat(ws=websocket))
subscribe_msg = {
"method": "sub.ticker",
"param": {
"symbol": "ETH_USDT"
},
# "gzip": false
}
await websocket.send(json.dumps(subscribe_msg))
subscribe_msg = {
"method": "sub.funding.rate",
"param": {
"symbol": "ETH_USDT"
},
# "gzip": false
}
await websocket.send(json.dumps(subscribe_msg))
try:
async for message in websocket:
ts_arrival = round(datetime.now().timestamp()*1000)
if isinstance(message, str):
try:
data = json.loads(message)
channel = data.get('channel', None)
if channel is not None:
match channel:
case 'push.ticker':
# logging.info(f'TICKER: {data}')
VAL_KEY_OBJ = json.dumps({
'timestamp_arrival': ts_arrival,
'timestamp_msg': data['ts'],
'timestamp_data': data['data']['timestamp'],
'symbol': data['data']['symbol'],
'lastPrice': float(data['data']['lastPrice']),
'fairPrice': float(data['data']['fairPrice']),
'indexPrice': float(data['data']['indexPrice']),
'volume24': float(data['data']['volume24']),
'bid1': float(data['data']['bid1']),
'ask1': float(data['data']['ask1']),
'fundingRate': float(data['data']['fundingRate']),
})
VAL_KEY.set(VK_TICKER, VAL_KEY_OBJ)
case 'push.funding.rate':
# logging.info(f'FUNDING RATE: {data}')
VAL_KEY_OBJ = json.dumps({
'timestamp_arrival': ts_arrival,
'timestamp_msg': data['ts'],
'symbol': data['data']['symbol'],
'rate': float(data['data']['rate']),
'nextSettleTime_ts_ms': data['data']['nextSettleTime'],
})
VAL_KEY.set(VK_FUND_RATE, VAL_KEY_OBJ)
case 'pong':
logging.info(f'PING RESPONSE: {data}')
case _:
logging.info(f'OTHER: {data}')
else:
logging.info(f'Initial or unexpected data struct, skipping: {data}')
continue
except (json.JSONDecodeError, ValueError):
logging.warning(f'Message not in JSON format, skipping: {message}')
continue
else:
raise ValueError(f'Type: {type(data)} not expected: {message}')
except websockets.ConnectionClosed as e:
logging.error(f'Connection closed: {e}')
logging.error(traceback.format_exc())
continue
except Exception as e:
logging.error(f'Connection closed: {e}')
logging.error(traceback.format_exc())
async def main():
global VAL_KEY
global CON
if USE_VK:
VAL_KEY = valkey.Valkey(host='localhost', port=6379, db=0)
else:
VAL_KEY = None
logging.warning("VALKEY NOT BEING USED, NO DATA WILL BE PUBLISHED")
if USE_DB:
engine = create_async_engine('mysql+asyncmy://root:pwd@localhost/polymarket')
async with engine.connect() as CON:
# await create_rtds_btcusd_table(CON=CON)
await ws_stream()
else:
CON = None
logging.warning("DATABASE NOT BEING USED, NO DATA WILL BE RECORDED")
await ws_stream()
if __name__ == '__main__':
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}")
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info("Stream stopped")