freqtrade_origin/scripts/ws_client.py

324 lines
9.4 KiB
Python
Raw Permalink Normal View History

2022-10-06 20:12:44 +00:00
#!/usr/bin/env python3
"""
Simple command line client for Testing/debugging
a Freqtrade bot's message websocket
Should not import anything from freqtrade,
so it can be used as a standalone script.
"""
2024-05-12 14:18:55 +00:00
2022-10-06 20:12:44 +00:00
import argparse
import asyncio
import logging
2022-10-06 20:33:04 +00:00
import socket
2022-10-06 20:12:44 +00:00
import sys
2022-10-06 20:33:04 +00:00
import time
2022-10-06 20:12:44 +00:00
from pathlib import Path
2022-10-06 20:33:04 +00:00
import orjson
import pandas
import rapidjson
import websockets
2022-10-06 20:12:44 +00:00
logger = logging.getLogger("WebSocketClient")
# ---------------------------------------------------------------------------
2024-05-12 14:18:55 +00:00
2022-10-06 20:12:44 +00:00
def setup_logging(filename: str):
logging.basicConfig(
level=logging.DEBUG,
2024-05-12 14:18:55 +00:00
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.FileHandler(filename), logging.StreamHandler()],
2022-10-06 20:12:44 +00:00
)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
2024-05-12 14:18:55 +00:00
"-c",
"--config",
help="Specify configuration file (default: %(default)s). ",
dest="config",
2022-10-06 20:12:44 +00:00
type=str,
2024-05-12 14:18:55 +00:00
metavar="PATH",
default="config.json",
2022-10-06 20:12:44 +00:00
)
parser.add_argument(
2024-05-12 14:18:55 +00:00
"-l",
"--logfile",
help="The filename to log to.",
dest="logfile",
2022-10-06 20:12:44 +00:00
type=str,
2024-05-12 14:18:55 +00:00
default="ws_client.log",
2022-10-06 20:12:44 +00:00
)
args = parser.parse_args()
return vars(args)
def load_config(configfile):
file = Path(configfile)
if file.is_file():
with file.open("r") as f:
2024-05-12 14:18:55 +00:00
config = rapidjson.load(
f, parse_mode=rapidjson.PM_COMMENTS | rapidjson.PM_TRAILING_COMMAS
)
2022-10-06 20:12:44 +00:00
return config
else:
logger.warning(f"Could not load config file {file}.")
sys.exit(1)
def readable_timedelta(delta):
"""
Convert a millisecond delta to a readable format
2022-10-06 20:12:44 +00:00
:param delta: A delta between two timestamps in milliseconds
2022-10-06 20:12:44 +00:00
:returns: The readable time difference string
"""
seconds, milliseconds = divmod(delta, 1000)
minutes, seconds = divmod(seconds, 60)
return f"{int(minutes)}:{int(seconds)}.{int(milliseconds)}"
2022-10-06 20:12:44 +00:00
2024-05-12 14:18:55 +00:00
2022-10-06 20:12:44 +00:00
# ----------------------------------------------------------------------------
def json_serialize(message):
"""
Serialize a message to JSON using orjson
:param message: The message to serialize
"""
return str(orjson.dumps(message), "utf-8")
def json_deserialize(message):
"""
Deserialize JSON to a dict
:param message: The message to deserialize
"""
2024-05-12 14:18:55 +00:00
2022-10-06 20:12:44 +00:00
def json_to_dataframe(data: str) -> pandas.DataFrame:
2024-05-12 14:18:55 +00:00
dataframe = pandas.read_json(data, orient="split")
if "date" in dataframe.columns:
dataframe["date"] = pandas.to_datetime(dataframe["date"], unit="ms", utc=True)
2022-10-06 20:12:44 +00:00
return dataframe
def _json_object_hook(z):
2024-05-12 14:18:55 +00:00
if z.get("__type__") == "dataframe":
return json_to_dataframe(z.get("__value__"))
2022-10-06 20:12:44 +00:00
return z
return rapidjson.loads(message, object_hook=_json_object_hook)
# ---------------------------------------------------------------------------
class ClientProtocol:
logger = logging.getLogger("WebSocketClient.Protocol")
_MESSAGE_COUNT = 0
_LAST_RECEIVED_AT = 0 # The epoch we received a message most recently
async def on_connect(self, websocket):
# On connection we have to send our initial requests
initial_requests = [
{
"type": "subscribe", # The subscribe request should always be first
2024-05-12 14:18:55 +00:00
"data": ["analyzed_df", "whitelist"], # The message types we want
2022-10-06 20:12:44 +00:00
},
{
"type": "whitelist",
"data": None,
},
2024-05-12 14:18:55 +00:00
{"type": "analyzed_df", "data": {"limit": 1500}},
2022-10-06 20:12:44 +00:00
]
for request in initial_requests:
await websocket.send(json_serialize(request))
async def on_message(self, websocket, name, message):
deserialized = json_deserialize(message)
message_size = sys.getsizeof(message)
2024-05-12 14:18:55 +00:00
message_type = deserialized.get("type")
message_data = deserialized.get("data")
2022-10-06 20:12:44 +00:00
self.logger.info(
f"Received message of type {message_type} [{message_size} bytes] @ [{name}]"
)
time_difference = self._calculate_time_difference()
if self._MESSAGE_COUNT > 0:
self.logger.info(f"Time since last message: {time_difference}")
message_handler = getattr(self, f"_handle_{message_type}", None) or self._handle_default
await message_handler(name, message_type, message_data)
self._MESSAGE_COUNT += 1
self.logger.info(f"[{self._MESSAGE_COUNT}] total messages..")
self.logger.info("-" * 80)
def _calculate_time_difference(self):
old_last_received_at = self._LAST_RECEIVED_AT
self._LAST_RECEIVED_AT = time.time() * 1e3
time_delta = self._LAST_RECEIVED_AT - old_last_received_at
2022-10-06 20:12:44 +00:00
return readable_timedelta(time_delta)
async def _handle_whitelist(self, name, msgtype, data):
2022-10-06 20:12:44 +00:00
self.logger.info(data)
async def _handle_analyzed_df(self, name, msgtype, data):
2024-05-12 14:18:55 +00:00
key, la, df = data["key"], data["la"], data["df"]
2022-10-06 20:12:44 +00:00
2022-10-07 03:00:28 +00:00
if not df.empty:
columns = ", ".join([str(column) for column in df.columns])
2022-10-06 20:12:44 +00:00
2022-10-07 03:00:28 +00:00
self.logger.info(key)
self.logger.info(f"Last analyzed datetime: {la}")
self.logger.info(f"Latest candle datetime: {df.iloc[-1]['date']}")
self.logger.info(f"DataFrame length: {len(df)}")
self.logger.info(f"DataFrame columns: {columns}")
2022-10-07 16:41:06 +00:00
else:
self.logger.info("Empty DataFrame")
async def _handle_default(self, name, msgtype, data):
self.logger.info("Unknown message of type {msgtype} received...")
2022-10-07 16:41:06 +00:00
self.logger.info(data)
2022-10-06 20:12:44 +00:00
async def create_client(
2024-05-12 14:18:55 +00:00
host,
port,
token,
scheme="ws",
name="default",
protocol=None,
sleep_time=10,
ping_timeout=10,
wait_timeout=30,
**kwargs,
2022-10-06 20:12:44 +00:00
):
"""
Create a websocket client and listen for messages
:param host: The host
:param port: The port
:param token: The websocket auth token
2022-11-16 05:44:02 +00:00
:param scheme: `ws` for most connections, `wss` for ssl
2022-10-06 20:12:44 +00:00
:param name: The name of the producer
:param **kwargs: Any extra kwargs passed to websockets.connect
"""
2024-04-20 07:51:11 +00:00
if not protocol:
protocol = ClientProtocol()
2022-10-06 20:12:44 +00:00
while 1:
try:
2022-11-16 05:44:02 +00:00
websocket_url = f"{scheme}://{host}:{port}/api/v1/message/ws?token={token}"
2022-10-06 20:12:44 +00:00
logger.info(f"Attempting to connect to {name} @ {host}:{port}")
async with websockets.connect(websocket_url, **kwargs) as ws:
logger.info("Connection successful...")
await protocol.on_connect(ws)
# Now listen for messages
while 1:
try:
2024-05-12 14:18:55 +00:00
message = await asyncio.wait_for(ws.recv(), timeout=wait_timeout)
2022-10-06 20:12:44 +00:00
await protocol.on_message(ws, name, message)
2024-05-12 14:18:55 +00:00
except (asyncio.TimeoutError, websockets.exceptions.WebSocketException):
2022-10-06 20:12:44 +00:00
# Try pinging
try:
pong = await ws.ping()
2024-05-12 14:18:55 +00:00
latency = await asyncio.wait_for(pong, timeout=ping_timeout) * 1000
logger.info(f"Connection still alive, latency: {latency}ms")
2022-10-06 20:12:44 +00:00
continue
except asyncio.TimeoutError:
logger.error(f"Ping timed out, retrying in {sleep_time}s")
await asyncio.sleep(sleep_time)
break
except (
socket.gaierror,
ConnectionRefusedError,
websockets.exceptions.InvalidStatusCode,
2024-05-12 14:18:55 +00:00
websockets.exceptions.InvalidMessage,
2022-10-06 20:12:44 +00:00
) as e:
logger.error(f"Connection Refused - {e} retrying in {sleep_time}s")
await asyncio.sleep(sleep_time)
continue
except (
websockets.exceptions.ConnectionClosedError,
2024-05-12 14:18:55 +00:00
websockets.exceptions.ConnectionClosedOK,
2022-10-06 20:12:44 +00:00
):
logger.info("Connection was closed")
2022-10-06 20:12:44 +00:00
# Just keep trying to connect again indefinitely
await asyncio.sleep(sleep_time)
continue
except Exception as e:
2024-04-18 20:51:25 +00:00
# An unforeseen error has occurred, log and try reconnecting again
2022-10-06 20:12:44 +00:00
logger.error("Unexpected error has occurred:")
logger.exception(e)
2022-10-07 03:00:28 +00:00
await asyncio.sleep(sleep_time)
2022-10-06 20:12:44 +00:00
continue
# ---------------------------------------------------------------------------
async def _main(args):
2024-05-12 14:18:55 +00:00
setup_logging(args["logfile"])
config = load_config(args["config"])
2022-10-06 20:12:44 +00:00
2024-05-12 14:18:55 +00:00
emc_config = config.get("external_message_consumer", {})
2022-10-06 20:12:44 +00:00
2024-05-12 14:18:55 +00:00
producers = emc_config.get("producers", [])
2022-10-06 20:12:44 +00:00
producer = producers[0]
2024-05-12 14:18:55 +00:00
wait_timeout = emc_config.get("wait_timeout", 30)
ping_timeout = emc_config.get("ping_timeout", 10)
sleep_time = emc_config.get("sleep_time", 10)
message_size_limit = emc_config.get("message_size_limit", 8) << 20
2022-10-06 20:12:44 +00:00
await create_client(
2024-05-12 14:18:55 +00:00
producer["host"],
producer["port"],
producer["ws_token"],
"wss" if producer.get("secure", False) else "ws",
producer["name"],
2022-10-06 20:12:44 +00:00
sleep_time=sleep_time,
ping_timeout=ping_timeout,
wait_timeout=wait_timeout,
max_size=message_size_limit,
2024-05-12 14:18:55 +00:00
ping_interval=None,
2022-10-06 20:12:44 +00:00
)
def main():
args = parse_args()
try:
asyncio.run(_main(args))
except KeyboardInterrupt:
logger.info("Exiting...")
if __name__ == "__main__":
main()