adding aster
This commit is contained in:
0
aster.ipynb
Normal file
0
aster.ipynb
Normal file
141
ws_aster.py
141
ws_aster.py
@@ -25,21 +25,23 @@ urllib3_cn.allowed_gai_family = allowed_gai_family
|
|||||||
### Database ###
|
### Database ###
|
||||||
USE_DB: bool = False
|
USE_DB: bool = False
|
||||||
USE_VK: bool = True
|
USE_VK: bool = True
|
||||||
# VK_FUND_RATE = 'fund_rate_apex'
|
VK_FUND_RATE = 'fund_rate_aster'
|
||||||
VK_TICKER = 'fut_ticker_apex'
|
VK_TICKER = 'fut_ticker_aster'
|
||||||
CON: AsyncContextManager | None = None
|
CON: AsyncContextManager | None = None
|
||||||
VAL_KEY = None
|
VAL_KEY = None
|
||||||
|
|
||||||
### Logging ###
|
### Logging ###
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
LOG_FILEPATH: str = os.getenv("LOGS_PATH") + '/Fund_Rate_Apex.log'
|
LOG_FILEPATH: str = os.getenv("LOGS_PATH") + '/Fund_Rate_Aster.log'
|
||||||
|
|
||||||
### CONSTANTS ###
|
### CONSTANTS ###
|
||||||
PING_INTERVAL_SEC = 15
|
SYMBOL: str = 'ETHUSDT'
|
||||||
|
STREAM_MARKPRICE: str = f'{SYMBOL.lower()}@markPrice@1s'
|
||||||
|
STREAM_BOOKTICKER: str = f'{SYMBOL.lower()}@bookTicker'
|
||||||
|
|
||||||
### Globals ###
|
### Globals ###
|
||||||
WSS_URL = "wss://quote.omni.apex.exchange/realtime_public?v=2×tamp="
|
WSS_URL = f"wss://fstream.asterdex.com/stream?streams={STREAM_MARKPRICE}/{STREAM_BOOKTICKER}"
|
||||||
TICKER_SNAPSHOT_DATA_LAST: dict = {}
|
# WSS_URL = f"wss://fstream.asterdex.com/stream?streams={STREAM_MARKPRICE}"
|
||||||
|
|
||||||
# HIST_TRADES = np.empty((0, 3))
|
# HIST_TRADES = np.empty((0, 3))
|
||||||
# HIST_TRADES_LOOKBACK_SEC = 6
|
# HIST_TRADES_LOOKBACK_SEC = 6
|
||||||
@@ -112,93 +114,58 @@ TICKER_SNAPSHOT_DATA_LAST: dict = {}
|
|||||||
# raise ValueError('Only MySQL engine is implemented')
|
# raise ValueError('Only MySQL engine is implemented')
|
||||||
|
|
||||||
### Websocket ###
|
### 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():
|
async def ws_stream():
|
||||||
global TICKER_SNAPSHOT_DATA_LAST
|
async for websocket in websockets.connect(WSS_URL):
|
||||||
|
|
||||||
async for websocket in websockets.connect(f'{WSS_URL}{round(datetime.now().timestamp())}'):
|
|
||||||
logging.info(f"Connected to {WSS_URL}")
|
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:
|
try:
|
||||||
async for message in websocket:
|
async for message in websocket:
|
||||||
ts_arrival = round(datetime.now().timestamp()*1000)
|
ts_arrival = round(datetime.now().timestamp()*1000)
|
||||||
print(message)
|
if isinstance(message, str):
|
||||||
# if isinstance(message, str):
|
try:
|
||||||
# try:
|
data = json.loads(message)
|
||||||
# data = json.loads(message)
|
channel = data.get('stream', None)
|
||||||
# if data.get('op', None) == 'ping':
|
if channel is not None:
|
||||||
# pong_msg = {"op":"pong","args":[ str(round(datetime.now().timestamp()*1000)) ]}
|
match channel:
|
||||||
# logging.info(f'RECEIVED PING: {data}; SENDING PONG: {pong_msg}')
|
case c if c == STREAM_MARKPRICE:
|
||||||
# await websocket.send(json.dumps(pong_msg))
|
print(f'MP: {data}')
|
||||||
# continue
|
VAL_KEY_OBJ = json.dumps({
|
||||||
# elif data.get('success', None):
|
'timestamp_arrival': ts_arrival,
|
||||||
# # logging.info('CONNECTION SUCCESFUL RESP MSG')
|
'timestamp_msg': data['data']['E'],
|
||||||
# continue
|
'symbol': data['data']['s'],
|
||||||
|
'mark_price': data['data']['p'],
|
||||||
# msg_type = data.get('type', None)
|
'index_price': data['data']['i'],
|
||||||
# if msg_type is not None:
|
'estimated_settle_price': data['data']['P'],
|
||||||
# match msg_type:
|
'funding_rate': data['data']['r'],
|
||||||
# case 'snapshot':
|
'next_funding_time_ts_ms': data['data']['T'],
|
||||||
# TICKER_SNAPSHOT_DATA_LAST = data['data']
|
})
|
||||||
|
VAL_KEY.set(VK_FUND_RATE, VAL_KEY_OBJ)
|
||||||
# nextFundingTime_ts = round(datetime.strptime(TICKER_SNAPSHOT_DATA_LAST['nextFundingTime'], "%Y-%m-%dT%H:%M:%SZ").timestamp()*1000)
|
continue
|
||||||
# VAL_KEY_OBJ = json.dumps({
|
case c if c == STREAM_BOOKTICKER:
|
||||||
# 'timestamp_arrival': ts_arrival,
|
# print(f'BT: {data}')
|
||||||
# 'timestamp_msg': data['ts'],
|
VAL_KEY_OBJ = json.dumps({
|
||||||
# 'symbol': TICKER_SNAPSHOT_DATA_LAST['symbol'],
|
'timestamp_arrival': ts_arrival,
|
||||||
# 'lastPrice': float(TICKER_SNAPSHOT_DATA_LAST['lastPrice']),
|
'timestamp_msg': data['data']['E'],
|
||||||
# 'markPrice': float(TICKER_SNAPSHOT_DATA_LAST['markPrice']),
|
'timestamp_transaction': data['data']['T'],
|
||||||
# 'indexPrice': float(TICKER_SNAPSHOT_DATA_LAST['indexPrice']),
|
'orderbook_update_id': data['data']['u'],
|
||||||
# 'volume24h': float(TICKER_SNAPSHOT_DATA_LAST['volume24h']),
|
'symbol': data['data']['s'],
|
||||||
# 'fundingRate': float(TICKER_SNAPSHOT_DATA_LAST['fundingRate']),
|
'best_bid_px': data['data']['b'],
|
||||||
# 'predictedFundingRate': float(TICKER_SNAPSHOT_DATA_LAST['predictedFundingRate']),
|
'best_bid_qty': data['data']['B'],
|
||||||
# 'nextFundingTime_ts_ms': nextFundingTime_ts,
|
'best_ask_px': data['data']['a'],
|
||||||
# })
|
'best_ask_qty': data['data']['A'],
|
||||||
# VAL_KEY.set(VK_TICKER, VAL_KEY_OBJ)
|
})
|
||||||
# continue
|
VAL_KEY.set(VK_TICKER, VAL_KEY_OBJ)
|
||||||
# case 'delta':
|
continue
|
||||||
# TICKER_SNAPSHOT_DATA_LAST.update(data['data'])
|
case _:
|
||||||
|
logging.warning(f'UNMATCHED OTHER MSG: {data}')
|
||||||
# nextFundingTime_ts = round(datetime.strptime(TICKER_SNAPSHOT_DATA_LAST['nextFundingTime'], "%Y-%m-%dT%H:%M:%SZ").timestamp()*1000)
|
else:
|
||||||
# VAL_KEY_OBJ = json.dumps({
|
logging.info(f'Initial or unexpected data struct, skipping: {data}')
|
||||||
# 'timestamp_arrival': ts_arrival,
|
continue
|
||||||
# 'timestamp_msg': data['ts'],
|
except (json.JSONDecodeError, ValueError):
|
||||||
# 'symbol': TICKER_SNAPSHOT_DATA_LAST['symbol'],
|
logging.warning(f'Message not in JSON format, skipping: {message}')
|
||||||
# 'lastPrice': float(TICKER_SNAPSHOT_DATA_LAST['lastPrice']),
|
continue
|
||||||
# 'markPrice': float(TICKER_SNAPSHOT_DATA_LAST['markPrice']),
|
else:
|
||||||
# 'indexPrice': float(TICKER_SNAPSHOT_DATA_LAST['indexPrice']),
|
raise ValueError(f'Type: {type(data)} not expected: {message}')
|
||||||
# '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:
|
except websockets.ConnectionClosed as e:
|
||||||
logging.error(f'Connection closed: {e}')
|
logging.error(f'Connection closed: {e}')
|
||||||
logging.error(traceback.format_exc())
|
logging.error(traceback.format_exc())
|
||||||
|
|||||||
0
ws_extended.py
Normal file
0
ws_extended.py
Normal file
Reference in New Issue
Block a user