From 9f6bba40af1a407f190a89f5c0c8b4e3f528ba46 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 18 Aug 2022 10:39:20 -0600 Subject: [PATCH 001/115] initial concept for replicate, basic leader and follower logic --- .gitignore | 2 + freqtrade/__init__.py | 2 +- freqtrade/constants.py | 28 + freqtrade/enums/__init__.py | 1 + freqtrade/enums/replicate.py | 11 + freqtrade/enums/rpcmessagetype.py | 2 + freqtrade/rpc/api_server/webserver.py | 8 +- freqtrade/rpc/replicate/__init__.py | 385 ++++++++++++++ freqtrade/rpc/replicate/channel.py | 106 ++++ freqtrade/rpc/replicate/proxy.py | 60 +++ freqtrade/rpc/replicate/serializer.py | 42 ++ freqtrade/rpc/replicate/thread_queue.py | 650 ++++++++++++++++++++++++ freqtrade/rpc/replicate/types.py | 9 + freqtrade/rpc/replicate/utils.py | 10 + freqtrade/rpc/rpc_manager.py | 13 + requirements-replicate.txt | 5 + 16 files changed, 1330 insertions(+), 4 deletions(-) create mode 100644 freqtrade/enums/replicate.py create mode 100644 freqtrade/rpc/replicate/__init__.py create mode 100644 freqtrade/rpc/replicate/channel.py create mode 100644 freqtrade/rpc/replicate/proxy.py create mode 100644 freqtrade/rpc/replicate/serializer.py create mode 100644 freqtrade/rpc/replicate/thread_queue.py create mode 100644 freqtrade/rpc/replicate/types.py create mode 100644 freqtrade/rpc/replicate/utils.py create mode 100644 requirements-replicate.txt diff --git a/.gitignore b/.gitignore index e400c01f5..df2121990 100644 --- a/.gitignore +++ b/.gitignore @@ -113,3 +113,5 @@ target/ !config_examples/config_full.example.json !config_examples/config_kraken.example.json !config_examples/config_freqai.example.json + +*-config.json diff --git a/freqtrade/__init__.py b/freqtrade/__init__.py index 2572c03f1..9e022b2d9 100644 --- a/freqtrade/__init__.py +++ b/freqtrade/__init__.py @@ -1,5 +1,5 @@ """ Freqtrade bot """ -__version__ = '2022.8.dev' +__version__ = '2022.8.1+pubsub' # Metadata 1.2 mandates PEP 440 version, but 'develop' is not if 'dev' in __version__: try: diff --git a/freqtrade/constants.py b/freqtrade/constants.py index ddbc84fa9..416b4646f 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -60,6 +60,8 @@ USERPATH_FREQAIMODELS = 'freqaimodels' TELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent'] WEBHOOK_FORMAT_OPTIONS = ['form', 'json', 'raw'] +FOLLOWER_MODE_OPTIONS = ['follower', 'leader'] + ENV_VAR_PREFIX = 'FREQTRADE__' NON_OPEN_EXCHANGE_STATES = ('cancelled', 'canceled', 'closed', 'expired') @@ -242,6 +244,7 @@ CONF_SCHEMA = { 'exchange': {'$ref': '#/definitions/exchange'}, 'edge': {'$ref': '#/definitions/edge'}, 'freqai': {'$ref': '#/definitions/freqai'}, + 'replicate': {'$ref': '#/definitions/replicate'}, 'experimental': { 'type': 'object', 'properties': { @@ -483,6 +486,31 @@ CONF_SCHEMA = { }, 'required': ['process_throttle_secs', 'allowed_risk'] }, + 'replicate': { + 'type': 'object', + 'properties': { + 'enabled': {'type': 'boolean', 'default': False}, + 'mode': { + 'type': 'string', + 'enum': FOLLOWER_MODE_OPTIONS + }, + 'api_key': {'type': 'string', 'default': ''}, + 'leaders': { + 'type': 'array', + 'items': { + 'type': 'object', + 'properties': { + 'url': {'type': 'string', 'default': ''}, + 'token': {'type': 'string', 'default': ''}, + } + } + }, + 'follower_reply_timeout': {'type': 'integer'}, + 'follower_sleep_time': {'type': 'integer'}, + 'follower_ping_timeout': {'type': 'integer'}, + }, + 'required': ['mode'] + }, "freqai": { "type": "object", "properties": { diff --git a/freqtrade/enums/__init__.py b/freqtrade/enums/__init__.py index e50ebc4a4..e1057208a 100644 --- a/freqtrade/enums/__init__.py +++ b/freqtrade/enums/__init__.py @@ -5,6 +5,7 @@ from freqtrade.enums.exitchecktuple import ExitCheckTuple from freqtrade.enums.exittype import ExitType from freqtrade.enums.marginmode import MarginMode from freqtrade.enums.ordertypevalue import OrderTypeValues +from freqtrade.enums.replicate import LeaderMessageType, ReplicateModeType from freqtrade.enums.rpcmessagetype import RPCMessageType from freqtrade.enums.runmode import NON_UTIL_MODES, OPTIMIZE_MODES, TRADING_MODES, RunMode from freqtrade.enums.signaltype import SignalDirection, SignalTagType, SignalType diff --git a/freqtrade/enums/replicate.py b/freqtrade/enums/replicate.py new file mode 100644 index 000000000..d55d45b45 --- /dev/null +++ b/freqtrade/enums/replicate.py @@ -0,0 +1,11 @@ +from enum import Enum + + +class ReplicateModeType(str, Enum): + leader = "leader" + follower = "follower" + + +class LeaderMessageType(str, Enum): + Pairlist = "pairlist" + Dataframe = "dataframe" diff --git a/freqtrade/enums/rpcmessagetype.py b/freqtrade/enums/rpcmessagetype.py index 415d8f18c..d5b3ce89c 100644 --- a/freqtrade/enums/rpcmessagetype.py +++ b/freqtrade/enums/rpcmessagetype.py @@ -19,6 +19,8 @@ class RPCMessageType(Enum): STRATEGY_MSG = 'strategy_msg' + EMIT_DATA = 'emit_data' + def __repr__(self): return self.value diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 0da129583..c98fb9fd4 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -54,7 +54,11 @@ class ApiServer(RPCHandler): ApiServer.__initialized = False return ApiServer.__instance - def __init__(self, config: Dict[str, Any], standalone: bool = False) -> None: + def __init__( + self, + config: Dict[str, Any], + standalone: bool = False, + ) -> None: ApiServer._config = config if self.__initialized and (standalone or self._standalone): return @@ -71,8 +75,6 @@ class ApiServer(RPCHandler): ) self.configure_app(self.app, self._config) - self.start_api() - def add_rpc_handler(self, rpc: RPC): """ Attach rpc handler diff --git a/freqtrade/rpc/replicate/__init__.py b/freqtrade/rpc/replicate/__init__.py new file mode 100644 index 000000000..d725a4a90 --- /dev/null +++ b/freqtrade/rpc/replicate/__init__.py @@ -0,0 +1,385 @@ +""" +This module manages replicate mode communication +""" +import asyncio +import logging +import secrets +import socket +from threading import Thread +from typing import Any, Coroutine, Dict, Union + +import websockets +from fastapi import Depends +from fastapi import WebSocket as FastAPIWebSocket +from fastapi import WebSocketDisconnect, status + +from freqtrade.enums import LeaderMessageType, ReplicateModeType, RPCMessageType +from freqtrade.rpc import RPC, RPCHandler +from freqtrade.rpc.replicate.channel import ChannelManager +from freqtrade.rpc.replicate.thread_queue import Queue as ThreadedQueue +from freqtrade.rpc.replicate.utils import is_websocket_alive + + +logger = logging.getLogger(__name__) + + +class ReplicateController(RPCHandler): + """ This class handles all websocket communication """ + + def __init__( + self, + rpc: RPC, + config: Dict[str, Any], + api_server: Union[Any, None] = None + ) -> None: + """ + Init the ReplicateRPC class, and init the super class RPCHandler + :param rpc: instance of RPC Helper class + :param config: Configuration object + :return: None + """ + super().__init__(rpc, config) + + self.api_server = api_server + + if not self.api_server: + raise RuntimeError("The API server must be enabled for replicate to work") + + self._loop = None + self._running = False + self._thread = None + self._queue = None + + self.channel_manager = ChannelManager() + + self.replicate_config = config.get('replicate', {}) + + # What the config should look like + # "replicate": { + # "enabled": true, + # "mode": "follower", + # "leaders": [ + # { + # "url": "ws://localhost:8080/replicate/ws", + # "token": "test" + # } + # ] + # } + + # "replicate": { + # "enabled": true, + # "mode": "leader", + # "api_key": "test" + # } + + self.mode = ReplicateModeType[self.replicate_config.get('mode', 'leader').lower()] + + self.leaders_list = self.replicate_config.get('leaders', []) + self.push_throttle_secs = self.replicate_config.get('push_throttle_secs', 1) + + self.reply_timeout = self.replicate_config.get('follower_reply_timeout', 10) + self.ping_timeout = self.replicate_config.get('follower_ping_timeout', 2) + self.sleep_time = self.replicate_config.get('follower_sleep_time', 1) + + if self.mode == ReplicateModeType.follower and len(self.leaders_list) == 0: + raise ValueError("You must specify at least 1 leader in follower mode.") + + # This is only used by the leader, the followers use the tokens specified + # in each of the leaders + # If you do not specify an API key in the config, one will be randomly + # generated and logged on startup + default_api_key = secrets.token_urlsafe(16) + self.secret_api_key = self.replicate_config.get('api_key', default_api_key) + + self.start_threaded_loop() + + if self.mode == ReplicateModeType.follower: + self.start_follower_mode() + elif self.mode == ReplicateModeType.leader: + self.start_leader_mode() + + def start_threaded_loop(self): + """ + Start the main internal loop in another thread to run coroutines + """ + self._loop = asyncio.new_event_loop() + + if not self._thread: + self._thread = Thread(target=self._loop.run_forever) + self._thread.start() + self._running = True + else: + raise RuntimeError("A loop is already running") + + def submit_coroutine(self, coroutine: Coroutine): + """ + Submit a coroutine to the threaded loop + """ + if not self._running: + raise RuntimeError("Cannot schedule new futures after shutdown") + + if not self._loop or not self._loop.is_running(): + raise RuntimeError("Loop must be started before any function can" + " be submitted") + + logger.debug(f"Running coroutine {repr(coroutine)} in loop") + try: + return asyncio.run_coroutine_threadsafe(coroutine, self._loop) + except Exception as e: + logger.error(f"Error running coroutine - {str(e)}") + return None + + def cleanup(self) -> None: + """ + Cleanup pending module resources. + """ + if self._thread: + if self._loop.is_running(): + + self._running = False + + # Tell all coroutines submitted to the loop they're cancelled + pending = asyncio.all_tasks(loop=self._loop) + for task in pending: + task.cancel() + + self._loop.call_soon_threadsafe(self.channel_manager.disconnect_all) + # This must be called threadsafe, otherwise would not work + self._loop.call_soon_threadsafe(self._loop.stop) + + self._thread.join() + + def send_msg(self, msg: Dict[str, Any]) -> None: + """ Push message through """ + + if msg["type"] == RPCMessageType.EMIT_DATA: + self._send_message( + { + "type": msg["data_type"], + "content": msg["data"] + } + ) + + # ----------------------- LEADER LOGIC ------------------------------ + + def start_leader_mode(self): + """ + Register the endpoint and start the leader loop + """ + + logger.info("Running rpc.replicate in Leader mode") + logger.info("-" * 15) + logger.info(f"API_KEY: {self.secret_api_key}") + logger.info("-" * 15) + + self.register_leader_endpoint() + self.submit_coroutine(self.leader_loop()) + + async def leader_loop(self): + """ + Main leader coroutine + At the moment this just broadcasts data that's in the queue to the followers + """ + try: + await self._broadcast_queue_data() + except Exception as e: + logger.error("Exception occurred in leader loop: ") + logger.exception(e) + + def _send_message(self, data: Dict[Any, Any]): + """ + Add data to the internal queue to be broadcasted. This func will block + if the queue is full. This is meant to be called in the main thread. + """ + + if self._queue: + self._queue.put(data) + else: + logger.warning("Can not send data, leader loop has not started yet!") + + async def _broadcast_queue_data(self): + """ + Loop over queue data and broadcast it + """ + # Instantiate the queue in this coroutine so it's attached to our loop + self._queue = ThreadedQueue() + async_queue = self._queue.async_q + + try: + while self._running: + # Get data from queue + data = await async_queue.get() + + # Broadcast it to everyone + await self.channel_manager.broadcast(data) + + # Sleep + await asyncio.sleep(self.push_throttle_secs) + except asyncio.CancelledError: + # Silently stop + pass + + async def get_api_token( + self, + websocket: FastAPIWebSocket, + token: Union[str, None] = None + ): + """ + Extract the API key from query param. Must match the + set secret_api_key or the websocket connection will be closed. + """ + if token == self.secret_api_key: + return token + else: + logger.info("Denying websocket request...") + await websocket.close(code=status.WS_1008_POLICY_VIOLATION) + + def register_leader_endpoint(self, path: str = "/replicate/ws"): + """ + Attach and start the main leader loop to the ApiServer + + :param path: The endpoint path + """ + + if not self.api_server: + raise RuntimeError("The leader needs the ApiServer to be active") + + # The endpoint function for running the main leader loop + @self.api_server.app.websocket(path) + async def leader_endpoint( + websocket: FastAPIWebSocket, + api_key: str = Depends(self.get_api_token) + ): + await self.leader_endpoint_loop(websocket) + + async def leader_endpoint_loop(self, websocket: FastAPIWebSocket): + """ + The WebSocket endpoint served by the ApiServer. This handles connections, + and adding them to the channel manager. + """ + try: + if is_websocket_alive(websocket): + logger.info(f"Follower connected - {websocket.client}") + channel = await self.channel_manager.on_connect(websocket) + + # Send initial data here + + # Keep connection open until explicitly closed, and sleep + try: + while not channel.is_closed(): + await channel.recv() + + except WebSocketDisconnect: + # Handle client disconnects + logger.info(f"Follower disconnected - {websocket.client}") + await self.channel_manager.on_disconnect(websocket) + except Exception as e: + logger.info(f"Follower connection failed - {websocket.client}") + logger.exception(e) + # Handle cases like - + # RuntimeError('Cannot call "send" once a closed message has been sent') + await self.channel_manager.on_disconnect(websocket) + + except Exception: + logger.error(f"Failed to serve - {websocket.client}") + await self.channel_manager.on_disconnect(websocket) + + # -------------------------------FOLLOWER LOGIC---------------------------- + + def start_follower_mode(self): + """ + Start the ReplicateController in Follower mode + """ + logger.info("Starting rpc.replicate in Follower mode") + + self.submit_coroutine(self.follower_loop()) + + async def follower_loop(self): + """ + Main follower coroutine + + This starts all of the leader connection coros + """ + try: + await self._connect_to_leaders() + except Exception as e: + logger.error("Exception occurred in follower loop: ") + logger.exception(e) + + async def _connect_to_leaders(self): + rpc_lock = asyncio.Lock() + + logger.info("Starting connections to Leaders...") + await asyncio.wait( + [ + self._handle_leader_connection(leader, rpc_lock) + for leader in self.leaders_list + ] + ) + + async def _handle_leader_connection(self, leader, lock): + """ + Given a leader, connect and wait on data. If connection is lost, + it will attempt to reconnect. + """ + url, token = leader["url"], leader["token"] + + websocket_url = f"{url}?token={token}" + + logger.info(f"Attempting to connect to leader at: {url}") + # TODO: limit the amount of connection retries + while True: + try: + async with websockets.connect(websocket_url) as ws: + channel = await self.channel_manager.on_connect(ws) + while True: + try: + data = await asyncio.wait_for( + channel.recv(), + timeout=self.reply_timeout + ) + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): + # We haven't received data yet. Just check the connection and continue. + try: + # ping + ping = await channel.ping() + await asyncio.wait_for(ping, timeout=self.ping_timeout) + logger.info(f"Connection to {url} still alive...") + continue + except Exception: + logger.info(f"Ping error {url} - retrying in {self.sleep_time}s") + asyncio.sleep(self.sleep_time) + break + + with lock: + # Should we have a lock here? + await self._handle_leader_message(data) + + except socket.gaierror: + logger.info(f"Socket error - retrying connection in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + continue + except ConnectionRefusedError: + logger.info(f"Connection Refused - retrying connection in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + continue + + async def _handle_leader_message(self, message): + type = message.get("type") + + message_type_handlers = { + LeaderMessageType.Pairlist.value: self._handle_pairlist_message, + LeaderMessageType.Dataframe.value: self._handle_dataframe_message + } + + handler = message_type_handlers.get(type, self._handle_default_message) + return await handler(message) + + async def _handle_default_message(self, message): + logger.info(f"Default message handled: {message}") + + async def _handle_pairlist_message(self, message): + logger.info(f"Pairlist message handled: {message}") + + async def _handle_dataframe_message(self, message): + logger.info(f"Dataframe message handled: {message}") diff --git a/freqtrade/rpc/replicate/channel.py b/freqtrade/rpc/replicate/channel.py new file mode 100644 index 000000000..9950742da --- /dev/null +++ b/freqtrade/rpc/replicate/channel.py @@ -0,0 +1,106 @@ +from typing import Type + +from freqtrade.rpc.replicate.proxy import WebSocketProxy +from freqtrade.rpc.replicate.serializer import JSONWebSocketSerializer, WebSocketSerializer +from freqtrade.rpc.replicate.types import WebSocketType + + +class WebSocketChannel: + """ + Object to help facilitate managing a websocket connection + """ + + def __init__( + self, + websocket: WebSocketType, + serializer_cls: Type[WebSocketSerializer] = JSONWebSocketSerializer + ): + # The WebSocket object + self._websocket = WebSocketProxy(websocket) + # The Serializing class for the WebSocket object + self._serializer_cls = serializer_cls + + # Internal event to signify a closed websocket + self._closed = False + + # Wrap the WebSocket in the Serializing class + self._wrapped_ws = self._serializer_cls(self._websocket) + + async def send(self, data): + """ + Send data on the wrapped websocket + """ + await self._wrapped_ws.send(data) + + async def recv(self): + """ + Receive data on the wrapped websocket + """ + return await self._wrapped_ws.recv() + + async def ping(self): + """ + Ping the websocket + """ + return await self._websocket.ping() + + async def close(self): + """ + Close the WebSocketChannel + """ + + self._closed = True + + def is_closed(self): + return self._closed + + +class ChannelManager: + def __init__(self): + self.channels = dict() + + async def on_connect(self, websocket: WebSocketType): + """ + Wrap websocket connection into Channel and add to list + + :param websocket: The WebSocket object to attach to the Channel + """ + if hasattr(websocket, "accept"): + try: + await websocket.accept() + except RuntimeError: + # The connection was closed before we could accept it + return + + ws_channel = WebSocketChannel(websocket) + self.channels[websocket] = ws_channel + + return ws_channel + + async def on_disconnect(self, websocket: WebSocketType): + """ + Call close on the channel if it's not, and remove from channel list + + :param websocket: The WebSocket objet attached to the Channel + """ + if websocket in self.channels.keys(): + channel = self.channels[websocket] + if not channel.is_closed(): + await channel.close() + del channel + + async def disconnect_all(self): + """ + Disconnect all Channels + """ + for websocket in self.channels.keys(): + await self.on_disconnect(websocket) + + async def broadcast(self, data): + """ + Broadcast data on all Channels + + :param data: The data to send + """ + for channel in self.channels.values(): + await channel.send(data) diff --git a/freqtrade/rpc/replicate/proxy.py b/freqtrade/rpc/replicate/proxy.py new file mode 100644 index 000000000..b2173670b --- /dev/null +++ b/freqtrade/rpc/replicate/proxy.py @@ -0,0 +1,60 @@ +from typing import TYPE_CHECKING, Union + +from fastapi import WebSocket as FastAPIWebSocket +from websockets import WebSocketClientProtocol as WebSocket + + +if TYPE_CHECKING: + from freqtrade.rpc.replicate.types import WebSocketType + + +class WebSocketProxy: + """ + WebSocketProxy object to bring the FastAPIWebSocket and websockets.WebSocketClientProtocol + under the same API + """ + + def __init__(self, websocket: WebSocketType): + self._websocket: Union[FastAPIWebSocket, WebSocket] = websocket + + async def send(self, data): + """ + Send data on the wrapped websocket + """ + if hasattr(self._websocket, "send_bytes"): + await self._websocket.send_bytes(data) + else: + await self._websocket.send(data) + + async def recv(self): + """ + Receive data on the wrapped websocket + """ + if hasattr(self._websocket, "receive_bytes"): + return await self._websocket.receive_bytes() + else: + return await self._websocket.recv() + + async def ping(self): + """ + Ping the websocket, not supported by FastAPI WebSockets + """ + if hasattr(self._websocket, "ping"): + return await self._websocket.ping() + return False + + async def close(self, code: int = 1000): + """ + Close the websocket connection, only supported by FastAPI WebSockets + """ + if hasattr(self._websocket, "close"): + return await self._websocket.close(code) + pass + + async def accept(self): + """ + Accept the WebSocket connection, only support by FastAPI WebSockets + """ + if hasattr(self._websocket, "accept"): + return await self._websocket.accept() + pass diff --git a/freqtrade/rpc/replicate/serializer.py b/freqtrade/rpc/replicate/serializer.py new file mode 100644 index 000000000..ae5e57b95 --- /dev/null +++ b/freqtrade/rpc/replicate/serializer.py @@ -0,0 +1,42 @@ +import json +from abc import ABC, abstractmethod + +from freqtrade.rpc.replicate.proxy import WebSocketProxy + + +class WebSocketSerializer(ABC): + def __init__(self, websocket: WebSocketProxy): + self._websocket: WebSocketProxy = websocket + + @abstractmethod + def _serialize(self, data): + raise NotImplementedError() + + @abstractmethod + def _deserialize(self, data): + raise NotImplementedError() + + async def send(self, data: bytes): + await self._websocket.send(self._serialize(data)) + + async def recv(self) -> bytes: + data = await self._websocket.recv() + + return self._deserialize(data) + + async def close(self, code: int = 1000): + await self._websocket.close(code) + +# Going to explore using MsgPack as the serialization, +# as that might be the best method for sending pandas +# dataframes over the wire + + +class JSONWebSocketSerializer(WebSocketSerializer): + def _serialize(self, data: bytes) -> bytes: + # json expects string not bytes + return json.dumps(data.decode()).encode() + + def _deserialize(self, data: bytes) -> bytes: + # The WebSocketSerializer gives bytes not string + return json.loads(data).encode() diff --git a/freqtrade/rpc/replicate/thread_queue.py b/freqtrade/rpc/replicate/thread_queue.py new file mode 100644 index 000000000..88321321b --- /dev/null +++ b/freqtrade/rpc/replicate/thread_queue.py @@ -0,0 +1,650 @@ +import asyncio +import sys +import threading +from asyncio import QueueEmpty as AsyncQueueEmpty +from asyncio import QueueFull as AsyncQueueFull +from collections import deque +from heapq import heappop, heappush +from queue import Empty as SyncQueueEmpty +from queue import Full as SyncQueueFull +from typing import Any, Callable, Deque, Generic, List, Optional, Set, TypeVar + +from typing_extensions import Protocol + + +__version__ = "1.0.0" +__all__ = ( + "Queue", + "PriorityQueue", + "LifoQueue", + "SyncQueue", + "AsyncQueue", + "BaseQueue", +) + + +T = TypeVar("T") +OptFloat = Optional[float] + + +class BaseQueue(Protocol[T]): + @property + def maxsize(self) -> int: + ... + + @property + def closed(self) -> bool: + ... + + def task_done(self) -> None: + ... + + def qsize(self) -> int: + ... + + @property + def unfinished_tasks(self) -> int: + ... + + def empty(self) -> bool: + ... + + def full(self) -> bool: + ... + + def put_nowait(self, item: T) -> None: + ... + + def get_nowait(self) -> T: + ... + + +class SyncQueue(BaseQueue[T], Protocol[T]): + @property + def maxsize(self) -> int: + ... + + @property + def closed(self) -> bool: + ... + + def task_done(self) -> None: + ... + + def qsize(self) -> int: + ... + + @property + def unfinished_tasks(self) -> int: + ... + + def empty(self) -> bool: + ... + + def full(self) -> bool: + ... + + def put_nowait(self, item: T) -> None: + ... + + def get_nowait(self) -> T: + ... + + def put(self, item: T, block: bool = True, timeout: OptFloat = None) -> None: + ... + + def get(self, block: bool = True, timeout: OptFloat = None) -> T: + ... + + def join(self) -> None: + ... + + +class AsyncQueue(BaseQueue[T], Protocol[T]): + async def put(self, item: T) -> None: + ... + + async def get(self) -> T: + ... + + async def join(self) -> None: + ... + + +class Queue(Generic[T]): + def __init__(self, maxsize: int = 0) -> None: + self._loop = asyncio.get_running_loop() + self._maxsize = maxsize + + self._init(maxsize) + + self._unfinished_tasks = 0 + + self._sync_mutex = threading.Lock() + self._sync_not_empty = threading.Condition(self._sync_mutex) + self._sync_not_full = threading.Condition(self._sync_mutex) + self._all_tasks_done = threading.Condition(self._sync_mutex) + + self._async_mutex = asyncio.Lock() + if sys.version_info[:3] == (3, 10, 0): + # Workaround for Python 3.10 bug, see #358: + getattr(self._async_mutex, "_get_loop", lambda: None)() + self._async_not_empty = asyncio.Condition(self._async_mutex) + self._async_not_full = asyncio.Condition(self._async_mutex) + self._finished = asyncio.Event() + self._finished.set() + + self._closing = False + self._pending = set() # type: Set[asyncio.Future[Any]] + + def checked_call_soon_threadsafe( + callback: Callable[..., None], *args: Any + ) -> None: + try: + self._loop.call_soon_threadsafe(callback, *args) + except RuntimeError: + # swallowing agreed in #2 + pass + + self._call_soon_threadsafe = checked_call_soon_threadsafe + + def checked_call_soon(callback: Callable[..., None], *args: Any) -> None: + if not self._loop.is_closed(): + self._loop.call_soon(callback, *args) + + self._call_soon = checked_call_soon + + self._sync_queue = _SyncQueueProxy(self) + self._async_queue = _AsyncQueueProxy(self) + + def close(self) -> None: + with self._sync_mutex: + self._closing = True + for fut in self._pending: + fut.cancel() + self._finished.set() # unblocks all async_q.join() + self._all_tasks_done.notify_all() # unblocks all sync_q.join() + + async def wait_closed(self) -> None: + # should be called from loop after close(). + # Nobody should put/get at this point, + # so lock acquiring is not required + if not self._closing: + raise RuntimeError("Waiting for non-closed queue") + # give execution chances for the task-done callbacks + # of async tasks created inside + # _notify_async_not_empty, _notify_async_not_full + # methods. + await asyncio.sleep(0) + if not self._pending: + return + await asyncio.wait(self._pending) + + @property + def closed(self) -> bool: + return self._closing and not self._pending + + @property + def maxsize(self) -> int: + return self._maxsize + + @property + def sync_q(self) -> "_SyncQueueProxy[T]": + return self._sync_queue + + @property + def async_q(self) -> "_AsyncQueueProxy[T]": + return self._async_queue + + # Override these methods to implement other queue organizations + # (e.g. stack or priority queue). + # These will only be called with appropriate locks held + + def _init(self, maxsize: int) -> None: + self._queue = deque() # type: Deque[T] + + def _qsize(self) -> int: + return len(self._queue) + + # Put a new item in the queue + def _put(self, item: T) -> None: + self._queue.append(item) + + # Get an item from the queue + def _get(self) -> T: + return self._queue.popleft() + + def _put_internal(self, item: T) -> None: + self._put(item) + self._unfinished_tasks += 1 + self._finished.clear() + + def _notify_sync_not_empty(self) -> None: + def f() -> None: + with self._sync_mutex: + self._sync_not_empty.notify() + + self._loop.run_in_executor(None, f) + + def _notify_sync_not_full(self) -> None: + def f() -> None: + with self._sync_mutex: + self._sync_not_full.notify() + + fut = asyncio.ensure_future(self._loop.run_in_executor(None, f)) + fut.add_done_callback(self._pending.discard) + self._pending.add(fut) + + def _notify_async_not_empty(self, *, threadsafe: bool) -> None: + async def f() -> None: + async with self._async_mutex: + self._async_not_empty.notify() + + def task_maker() -> None: + task = self._loop.create_task(f()) + task.add_done_callback(self._pending.discard) + self._pending.add(task) + + if threadsafe: + self._call_soon_threadsafe(task_maker) + else: + self._call_soon(task_maker) + + def _notify_async_not_full(self, *, threadsafe: bool) -> None: + async def f() -> None: + async with self._async_mutex: + self._async_not_full.notify() + + def task_maker() -> None: + task = self._loop.create_task(f()) + task.add_done_callback(self._pending.discard) + self._pending.add(task) + + if threadsafe: + self._call_soon_threadsafe(task_maker) + else: + self._call_soon(task_maker) + + def _check_closing(self) -> None: + if self._closing: + raise RuntimeError("Operation on the closed queue is forbidden") + + +class _SyncQueueProxy(SyncQueue[T]): + """Create a queue object with a given maximum size. + + If maxsize is <= 0, the queue size is infinite. + """ + + def __init__(self, parent: Queue[T]): + self._parent = parent + + @property + def maxsize(self) -> int: + return self._parent._maxsize + + @property + def closed(self) -> bool: + return self._parent.closed + + def task_done(self) -> None: + """Indicate that a formerly enqueued task is complete. + + Used by Queue consumer threads. For each get() used to fetch a task, + a subsequent call to task_done() tells the queue that the processing + on the task is complete. + + If a join() is currently blocking, it will resume when all items + have been processed (meaning that a task_done() call was received + for every item that had been put() into the queue). + + Raises a ValueError if called more times than there were items + placed in the queue. + """ + self._parent._check_closing() + with self._parent._all_tasks_done: + unfinished = self._parent._unfinished_tasks - 1 + if unfinished <= 0: + if unfinished < 0: + raise ValueError("task_done() called too many times") + self._parent._all_tasks_done.notify_all() + self._parent._loop.call_soon_threadsafe(self._parent._finished.set) + self._parent._unfinished_tasks = unfinished + + def join(self) -> None: + """Blocks until all items in the Queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer thread calls task_done() + to indicate the item was retrieved and all work on it is complete. + + When the count of unfinished tasks drops to zero, join() unblocks. + """ + self._parent._check_closing() + with self._parent._all_tasks_done: + while self._parent._unfinished_tasks: + self._parent._all_tasks_done.wait() + self._parent._check_closing() + + def qsize(self) -> int: + """Return the approximate size of the queue (not reliable!).""" + return self._parent._qsize() + + @property + def unfinished_tasks(self) -> int: + """Return the number of unfinished tasks.""" + return self._parent._unfinished_tasks + + def empty(self) -> bool: + """Return True if the queue is empty, False otherwise (not reliable!). + + This method is likely to be removed at some point. Use qsize() == 0 + as a direct substitute, but be aware that either approach risks a race + condition where a queue can grow before the result of empty() or + qsize() can be used. + + To create code that needs to wait for all queued tasks to be + completed, the preferred technique is to use the join() method. + """ + return not self._parent._qsize() + + def full(self) -> bool: + """Return True if the queue is full, False otherwise (not reliable!). + + This method is likely to be removed at some point. Use qsize() >= n + as a direct substitute, but be aware that either approach risks a race + condition where a queue can shrink before the result of full() or + qsize() can be used. + """ + return 0 < self._parent._maxsize <= self._parent._qsize() + + def put(self, item: T, block: bool = True, timeout: OptFloat = None) -> None: + """Put an item into the queue. + + If optional args 'block' is true and 'timeout' is None (the default), + block if necessary until a free slot is available. If 'timeout' is + a non-negative number, it blocks at most 'timeout' seconds and raises + the Full exception if no free slot was available within that time. + Otherwise ('block' is false), put an item on the queue if a free slot + is immediately available, else raise the Full exception ('timeout' + is ignored in that case). + """ + self._parent._check_closing() + with self._parent._sync_not_full: + if self._parent._maxsize > 0: + if not block: + if self._parent._qsize() >= self._parent._maxsize: + raise SyncQueueFull + elif timeout is None: + while self._parent._qsize() >= self._parent._maxsize: + self._parent._sync_not_full.wait() + elif timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + else: + time = self._parent._loop.time + endtime = time() + timeout + while self._parent._qsize() >= self._parent._maxsize: + remaining = endtime - time() + if remaining <= 0.0: + raise SyncQueueFull + self._parent._sync_not_full.wait(remaining) + self._parent._put_internal(item) + self._parent._sync_not_empty.notify() + self._parent._notify_async_not_empty(threadsafe=True) + + def get(self, block: bool = True, timeout: OptFloat = None) -> T: + """Remove and return an item from the queue. + + If optional args 'block' is true and 'timeout' is None (the default), + block if necessary until an item is available. If 'timeout' is + a non-negative number, it blocks at most 'timeout' seconds and raises + the Empty exception if no item was available within that time. + Otherwise ('block' is false), return an item if one is immediately + available, else raise the Empty exception ('timeout' is ignored + in that case). + """ + self._parent._check_closing() + with self._parent._sync_not_empty: + if not block: + if not self._parent._qsize(): + raise SyncQueueEmpty + elif timeout is None: + while not self._parent._qsize(): + self._parent._sync_not_empty.wait() + elif timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + else: + time = self._parent._loop.time + endtime = time() + timeout + while not self._parent._qsize(): + remaining = endtime - time() + if remaining <= 0.0: + raise SyncQueueEmpty + self._parent._sync_not_empty.wait(remaining) + item = self._parent._get() + self._parent._sync_not_full.notify() + self._parent._notify_async_not_full(threadsafe=True) + return item + + def put_nowait(self, item: T) -> None: + """Put an item into the queue without blocking. + + Only enqueue the item if a free slot is immediately available. + Otherwise raise the Full exception. + """ + return self.put(item, block=False) + + def get_nowait(self) -> T: + """Remove and return an item from the queue without blocking. + + Only get an item if one is immediately available. Otherwise + raise the Empty exception. + """ + return self.get(block=False) + + +class _AsyncQueueProxy(AsyncQueue[T]): + """Create a queue object with a given maximum size. + + If maxsize is <= 0, the queue size is infinite. + """ + + def __init__(self, parent: Queue[T]): + self._parent = parent + + @property + def closed(self) -> bool: + return self._parent.closed + + def qsize(self) -> int: + """Number of items in the queue.""" + return self._parent._qsize() + + @property + def unfinished_tasks(self) -> int: + """Return the number of unfinished tasks.""" + return self._parent._unfinished_tasks + + @property + def maxsize(self) -> int: + """Number of items allowed in the queue.""" + return self._parent._maxsize + + def empty(self) -> bool: + """Return True if the queue is empty, False otherwise.""" + return self.qsize() == 0 + + def full(self) -> bool: + """Return True if there are maxsize items in the queue. + + Note: if the Queue was initialized with maxsize=0 (the default), + then full() is never True. + """ + if self._parent._maxsize <= 0: + return False + else: + return self.qsize() >= self._parent._maxsize + + async def put(self, item: T) -> None: + """Put an item into the queue. + + Put an item into the queue. If the queue is full, wait until a free + slot is available before adding item. + + This method is a coroutine. + """ + self._parent._check_closing() + async with self._parent._async_not_full: + self._parent._sync_mutex.acquire() + locked = True + try: + if self._parent._maxsize > 0: + do_wait = True + while do_wait: + do_wait = self._parent._qsize() >= self._parent._maxsize + if do_wait: + locked = False + self._parent._sync_mutex.release() + await self._parent._async_not_full.wait() + self._parent._sync_mutex.acquire() + locked = True + + self._parent._put_internal(item) + self._parent._async_not_empty.notify() + self._parent._notify_sync_not_empty() + finally: + if locked: + self._parent._sync_mutex.release() + + def put_nowait(self, item: T) -> None: + """Put an item into the queue without blocking. + + If no free slot is immediately available, raise QueueFull. + """ + self._parent._check_closing() + with self._parent._sync_mutex: + if self._parent._maxsize > 0: + if self._parent._qsize() >= self._parent._maxsize: + raise AsyncQueueFull + + self._parent._put_internal(item) + self._parent._notify_async_not_empty(threadsafe=False) + self._parent._notify_sync_not_empty() + + async def get(self) -> T: + """Remove and return an item from the queue. + + If queue is empty, wait until an item is available. + + This method is a coroutine. + """ + self._parent._check_closing() + async with self._parent._async_not_empty: + self._parent._sync_mutex.acquire() + locked = True + try: + do_wait = True + while do_wait: + do_wait = self._parent._qsize() == 0 + + if do_wait: + locked = False + self._parent._sync_mutex.release() + await self._parent._async_not_empty.wait() + self._parent._sync_mutex.acquire() + locked = True + + item = self._parent._get() + self._parent._async_not_full.notify() + self._parent._notify_sync_not_full() + return item + finally: + if locked: + self._parent._sync_mutex.release() + + def get_nowait(self) -> T: + """Remove and return an item from the queue. + + Return an item if one is immediately available, else raise QueueEmpty. + """ + self._parent._check_closing() + with self._parent._sync_mutex: + if self._parent._qsize() == 0: + raise AsyncQueueEmpty + + item = self._parent._get() + self._parent._notify_async_not_full(threadsafe=False) + self._parent._notify_sync_not_full() + return item + + def task_done(self) -> None: + """Indicate that a formerly enqueued task is complete. + + Used by queue consumers. For each get() used to fetch a task, + a subsequent call to task_done() tells the queue that the processing + on the task is complete. + + If a join() is currently blocking, it will resume when all items have + been processed (meaning that a task_done() call was received for every + item that had been put() into the queue). + + Raises ValueError if called more times than there were items placed in + the queue. + """ + self._parent._check_closing() + with self._parent._all_tasks_done: + if self._parent._unfinished_tasks <= 0: + raise ValueError("task_done() called too many times") + self._parent._unfinished_tasks -= 1 + if self._parent._unfinished_tasks == 0: + self._parent._finished.set() + self._parent._all_tasks_done.notify_all() + + async def join(self) -> None: + """Block until all items in the queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer calls task_done() to + indicate that the item was retrieved and all work on it is complete. + When the count of unfinished tasks drops to zero, join() unblocks. + """ + while True: + with self._parent._sync_mutex: + self._parent._check_closing() + if self._parent._unfinished_tasks == 0: + break + await self._parent._finished.wait() + + +class PriorityQueue(Queue[T]): + """Variant of Queue that retrieves open entries in priority order + (lowest first). + + Entries are typically tuples of the form: (priority number, data). + + """ + + def _init(self, maxsize: int) -> None: + self._heap_queue = [] # type: List[T] + + def _qsize(self) -> int: + return len(self._heap_queue) + + def _put(self, item: T) -> None: + heappush(self._heap_queue, item) + + def _get(self) -> T: + return heappop(self._heap_queue) + + +class LifoQueue(Queue[T]): + """Variant of Queue that retrieves most recently added entries first.""" + + def _qsize(self) -> int: + return len(self._queue) + + def _put(self, item: T) -> None: + self._queue.append(item) + + def _get(self) -> T: + return self._queue.pop() diff --git a/freqtrade/rpc/replicate/types.py b/freqtrade/rpc/replicate/types.py new file mode 100644 index 000000000..5d8c158bd --- /dev/null +++ b/freqtrade/rpc/replicate/types.py @@ -0,0 +1,9 @@ +from typing import TypeVar + +from fastapi import WebSocket as FastAPIWebSocket +from websockets import WebSocketClientProtocol as WebSocket + +from freqtrade.rpc.replicate.channel import WebSocketProxy + + +WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket, WebSocketProxy) diff --git a/freqtrade/rpc/replicate/utils.py b/freqtrade/rpc/replicate/utils.py new file mode 100644 index 000000000..7b703810e --- /dev/null +++ b/freqtrade/rpc/replicate/utils.py @@ -0,0 +1,10 @@ +from starlette.websockets import WebSocket, WebSocketState + + +async def is_websocket_alive(ws: WebSocket) -> bool: + if ( + ws.application_state == WebSocketState.CONNECTED and + ws.client_state == WebSocketState.CONNECTED + ): + return True + return False diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 3ccf23228..140431586 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -44,10 +44,23 @@ class RPCManager: if config.get('api_server', {}).get('enabled', False): logger.info('Enabling rpc.api_server') from freqtrade.rpc.api_server import ApiServer + + # Pass replicate_rpc as param or defer starting api_server + # until we register the replicate rpc enpoint? apiserver = ApiServer(config) apiserver.add_rpc_handler(self._rpc) self.registered_modules.append(apiserver) + # Enable Replicate mode + # For this to be enabled, the API server must also be enabled + if config.get('replicate', {}).get('enabled', False): + logger.info('Enabling rpc.replicate') + from freqtrade.rpc.replicate import ReplicateController + replicate_rpc = ReplicateController(self._rpc, config, apiserver) + self.registered_modules.append(replicate_rpc) + + apiserver.start_api() + def cleanup(self) -> None: """ Stops all enabled rpc modules """ logger.info('Cleaning up rpc modules ...') diff --git a/requirements-replicate.txt b/requirements-replicate.txt new file mode 100644 index 000000000..7ee351d9d --- /dev/null +++ b/requirements-replicate.txt @@ -0,0 +1,5 @@ +# Include all requirements to run the bot. +-r requirements.txt + +# Required for follower +websockets From 6834db11f3ec4d0b9d9a6540633e1b363c11c889 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 19 Aug 2022 00:06:19 -0600 Subject: [PATCH 002/115] minor improvements and pairlist data transmission --- freqtrade/enums/replicate.py | 3 +- freqtrade/freqtradebot.py | 13 + .../plugins/pairlist/ExternalPairList.py | 59 +++++ freqtrade/rpc/replicate/__init__.py | 236 ++++++++++-------- freqtrade/rpc/replicate/channel.py | 23 +- freqtrade/rpc/replicate/proxy.py | 9 +- freqtrade/rpc/replicate/serializer.py | 8 +- freqtrade/rpc/replicate/types.py | 4 +- freqtrade/rpc/rpc_manager.py | 3 + 9 files changed, 243 insertions(+), 115 deletions(-) create mode 100644 freqtrade/plugins/pairlist/ExternalPairList.py diff --git a/freqtrade/enums/replicate.py b/freqtrade/enums/replicate.py index d55d45b45..501d119f3 100644 --- a/freqtrade/enums/replicate.py +++ b/freqtrade/enums/replicate.py @@ -7,5 +7,4 @@ class ReplicateModeType(str, Enum): class LeaderMessageType(str, Enum): - Pairlist = "pairlist" - Dataframe = "dataframe" + whitelist = "whitelist" diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 4e3af64ea..ac6a998c5 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -75,6 +75,8 @@ class FreqtradeBot(LoggingMixin): PairLocks.timeframe = self.config['timeframe'] + self.replicate_controller = None + # RPC runs in separate threads, can start handling external commands just after # initialization, even before Freqtradebot has a chance to start its throttling, # so anything in the Freqtradebot instance should be ready (initialized), including @@ -264,6 +266,17 @@ class FreqtradeBot(LoggingMixin): # Extend active-pair whitelist with pairs of open trades # It ensures that candle (OHLCV) data are downloaded for open trades as well _whitelist.extend([trade.pair for trade in trades if trade.pair not in _whitelist]) + + # If replicate leader, broadcast whitelist data + if self.replicate_controller: + if self.replicate_controller.is_leader(): + self.replicate_controller.send_message( + { + "data_type": "whitelist", + "data": _whitelist + } + ) + return _whitelist def get_free_open_trades(self) -> int: diff --git a/freqtrade/plugins/pairlist/ExternalPairList.py b/freqtrade/plugins/pairlist/ExternalPairList.py new file mode 100644 index 000000000..832c3d5eb --- /dev/null +++ b/freqtrade/plugins/pairlist/ExternalPairList.py @@ -0,0 +1,59 @@ +""" +External Pair List provider + +Provides pair list from Leader data +""" +import logging +from typing import Any, Dict, List + +from freqtrade.plugins.pairlist.IPairList import IPairList + + +logger = logging.getLogger(__name__) + + +class ExternalPairList(IPairList): + + def __init__(self, exchange, pairlistmanager, + config: Dict[str, Any], pairlistconfig: Dict[str, Any], + pairlist_pos: int) -> None: + super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos) + + self._num_assets = self._pairlistconfig.get('num_assets') + self._allow_inactive = self._pairlistconfig.get('allow_inactive', False) + + self._leader_pairs: List[str] = [] + + @property + def needstickers(self) -> bool: + """ + Boolean property defining if tickers are necessary. + If no Pairlist requires tickers, an empty Dict is passed + as tickers argument to filter_pairlist + """ + return False + + def short_desc(self) -> str: + """ + Short whitelist method description - used for startup-messages + -> Please overwrite in subclasses + """ + return f"{self.name}" + + def gen_pairlist(self, tickers: Dict) -> List[str]: + """ + Generate the pairlist + :param tickers: Tickers (from exchange.get_tickers()). May be cached. + :return: List of pairs + """ + pass + + def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]: + """ + Filters and sorts pairlist and returns the whitelist again. + Called on each bot iteration - please use internal caching if necessary + :param pairlist: pairlist to filter or sort + :param tickers: Tickers (from exchange.get_tickers()). May be cached. + :return: new whitelist + """ + pass diff --git a/freqtrade/rpc/replicate/__init__.py b/freqtrade/rpc/replicate/__init__.py index d725a4a90..80ac0836c 100644 --- a/freqtrade/rpc/replicate/__init__.py +++ b/freqtrade/rpc/replicate/__init__.py @@ -5,7 +5,7 @@ import asyncio import logging import secrets import socket -from threading import Thread +from threading import Event, Thread from typing import Any, Coroutine, Dict, Union import websockets @@ -50,6 +50,9 @@ class ReplicateController(RPCHandler): self._thread = None self._queue = None + self._stop_event = Event() + self._follower_tasks = None + self.channel_manager = ChannelManager() self.replicate_config = config.get('replicate', {}) @@ -93,10 +96,7 @@ class ReplicateController(RPCHandler): self.start_threaded_loop() - if self.mode == ReplicateModeType.follower: - self.start_follower_mode() - elif self.mode == ReplicateModeType.leader: - self.start_leader_mode() + self.start() def start_threaded_loop(self): """ @@ -129,6 +129,29 @@ class ReplicateController(RPCHandler): logger.error(f"Error running coroutine - {str(e)}") return None + async def main_loop(self): + """ + Main loop coro + + Start the loop based on what mode we're in + """ + try: + if self.mode == ReplicateModeType.leader: + await self.leader_loop() + elif self.mode == ReplicateModeType.follower: + await self.follower_loop() + + except asyncio.CancelledError: + pass + finally: + self._loop.stop() + + def start(self): + """ + Start the controller main loop + """ + self.submit_coroutine(self.main_loop()) + def cleanup(self) -> None: """ Cleanup pending module resources. @@ -144,27 +167,62 @@ class ReplicateController(RPCHandler): task.cancel() self._loop.call_soon_threadsafe(self.channel_manager.disconnect_all) - # This must be called threadsafe, otherwise would not work - self._loop.call_soon_threadsafe(self._loop.stop) self._thread.join() def send_msg(self, msg: Dict[str, Any]) -> None: - """ Push message through """ - + """ + Support RPC calls + """ if msg["type"] == RPCMessageType.EMIT_DATA: - self._send_message( + self.send_message( { - "type": msg["data_type"], - "content": msg["data"] + "data_type": msg.get("data_type"), + "data": msg.get("data") } ) + def send_message(self, msg: Dict[str, Any]) -> None: + """ Push message through """ + + if self.channel_manager.has_channels(): + self._send_message(msg) + else: + logger.debug("No listening followers, skipping...") + pass + + def _send_message(self, msg: Dict[Any, Any]): + """ + Add data to the internal queue to be broadcasted. This func will block + if the queue is full. This is meant to be called in the main thread. + """ + + if self._queue: + queue = self._queue.sync_q + queue.put(msg) + else: + logger.warning("Can not send data, leader loop has not started yet!") + + def is_leader(self): + """ + Leader flag + """ + return self.enabled() and self.mode == ReplicateModeType.leader + + def enabled(self): + """ + Enabled flag + """ + return self.replicate_config.get('enabled', False) + # ----------------------- LEADER LOGIC ------------------------------ - def start_leader_mode(self): + async def leader_loop(self): """ - Register the endpoint and start the leader loop + Main leader coroutine + + This starts all of the leader coros and registers the endpoint on + the ApiServer """ logger.info("Running rpc.replicate in Leader mode") @@ -173,30 +231,13 @@ class ReplicateController(RPCHandler): logger.info("-" * 15) self.register_leader_endpoint() - self.submit_coroutine(self.leader_loop()) - async def leader_loop(self): - """ - Main leader coroutine - At the moment this just broadcasts data that's in the queue to the followers - """ try: await self._broadcast_queue_data() except Exception as e: logger.error("Exception occurred in leader loop: ") logger.exception(e) - def _send_message(self, data: Dict[Any, Any]): - """ - Add data to the internal queue to be broadcasted. This func will block - if the queue is full. This is meant to be called in the main thread. - """ - - if self._queue: - self._queue.put(data) - else: - logger.warning("Can not send data, leader loop has not started yet!") - async def _broadcast_queue_data(self): """ Loop over queue data and broadcast it @@ -210,6 +251,8 @@ class ReplicateController(RPCHandler): # Get data from queue data = await async_queue.get() + logger.info(f"Found data - broadcasting: {data}") + # Broadcast it to everyone await self.channel_manager.broadcast(data) @@ -263,6 +306,9 @@ class ReplicateController(RPCHandler): channel = await self.channel_manager.on_connect(websocket) # Send initial data here + # Data is being broadcasted right away as soon as startup, + # we may not have to send initial data at all. Further testing + # required. # Keep connection open until explicitly closed, and sleep try: @@ -286,20 +332,15 @@ class ReplicateController(RPCHandler): # -------------------------------FOLLOWER LOGIC---------------------------- - def start_follower_mode(self): - """ - Start the ReplicateController in Follower mode - """ - logger.info("Starting rpc.replicate in Follower mode") - - self.submit_coroutine(self.follower_loop()) - async def follower_loop(self): """ Main follower coroutine - This starts all of the leader connection coros + This starts all of the follower connection coros """ + + logger.info("Starting rpc.replicate in Follower mode") + try: await self._connect_to_leaders() except Exception as e: @@ -307,79 +348,76 @@ class ReplicateController(RPCHandler): logger.exception(e) async def _connect_to_leaders(self): + """ + For each leader in `self.leaders_list` create a connection and + listen for data. + """ rpc_lock = asyncio.Lock() logger.info("Starting connections to Leaders...") - await asyncio.wait( - [ - self._handle_leader_connection(leader, rpc_lock) - for leader in self.leaders_list - ] - ) + + self.follower_tasks = [ + self._loop.create_task(self._handle_leader_connection(leader, rpc_lock)) + for leader in self.leaders_list + ] + return await asyncio.gather(*self.follower_tasks, return_exceptions=True) async def _handle_leader_connection(self, leader, lock): """ Given a leader, connect and wait on data. If connection is lost, it will attempt to reconnect. """ - url, token = leader["url"], leader["token"] + try: + url, token = leader["url"], leader["token"] - websocket_url = f"{url}?token={token}" + websocket_url = f"{url}?token={token}" - logger.info(f"Attempting to connect to leader at: {url}") - # TODO: limit the amount of connection retries - while True: - try: - async with websockets.connect(websocket_url) as ws: - channel = await self.channel_manager.on_connect(ws) - while True: - try: - data = await asyncio.wait_for( - channel.recv(), - timeout=self.reply_timeout - ) - except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): - # We haven't received data yet. Just check the connection and continue. + logger.info(f"Attempting to connect to leader at: {url}") + # TODO: limit the amount of connection retries + while True: + try: + async with websockets.connect(websocket_url) as ws: + channel = await self.channel_manager.on_connect(ws) + while True: try: - # ping - ping = await channel.ping() - await asyncio.wait_for(ping, timeout=self.ping_timeout) - logger.info(f"Connection to {url} still alive...") - continue - except Exception: - logger.info(f"Ping error {url} - retrying in {self.sleep_time}s") - asyncio.sleep(self.sleep_time) - break + data = await asyncio.wait_for( + channel.recv(), + timeout=self.reply_timeout + ) + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): + # We haven't received data yet. Check the connection and continue. + try: + # ping + ping = await channel.ping() + await asyncio.wait_for(ping, timeout=self.ping_timeout) + logger.debug(f"Connection to {url} still alive...") + continue + except Exception: + logger.info( + f"Ping error {url} - retrying in {self.sleep_time}s") + asyncio.sleep(self.sleep_time) + break - with lock: - # Should we have a lock here? - await self._handle_leader_message(data) + async with lock: + # Acquire lock so only 1 coro handling at a time + # as we might call the RPC module in the main thread + await self._handle_leader_message(data) - except socket.gaierror: - logger.info(f"Socket error - retrying connection in {self.sleep_time}s") - await asyncio.sleep(self.sleep_time) - continue - except ConnectionRefusedError: - logger.info(f"Connection Refused - retrying connection in {self.sleep_time}s") - await asyncio.sleep(self.sleep_time) - continue + except socket.gaierror: + logger.info(f"Socket error - retrying connection in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + continue + except ConnectionRefusedError: + logger.info(f"Connection Refused - retrying connection in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + continue + + except asyncio.CancelledError: + pass async def _handle_leader_message(self, message): - type = message.get("type") + type = message.get('data_type') + data = message.get('data') - message_type_handlers = { - LeaderMessageType.Pairlist.value: self._handle_pairlist_message, - LeaderMessageType.Dataframe.value: self._handle_dataframe_message - } - - handler = message_type_handlers.get(type, self._handle_default_message) - return await handler(message) - - async def _handle_default_message(self, message): - logger.info(f"Default message handled: {message}") - - async def _handle_pairlist_message(self, message): - logger.info(f"Pairlist message handled: {message}") - - async def _handle_dataframe_message(self, message): - logger.info(f"Dataframe message handled: {message}") + if type == LeaderMessageType.whitelist: + logger.info(f"Received whitelist from Leader: {data}") diff --git a/freqtrade/rpc/replicate/channel.py b/freqtrade/rpc/replicate/channel.py index 9950742da..7aa316ff5 100644 --- a/freqtrade/rpc/replicate/channel.py +++ b/freqtrade/rpc/replicate/channel.py @@ -1,3 +1,4 @@ +import logging from typing import Type from freqtrade.rpc.replicate.proxy import WebSocketProxy @@ -5,6 +6,9 @@ from freqtrade.rpc.replicate.serializer import JSONWebSocketSerializer, WebSocke from freqtrade.rpc.replicate.types import WebSocketType +logger = logging.getLogger(__name__) + + class WebSocketChannel: """ Object to help facilitate managing a websocket connection @@ -85,9 +89,12 @@ class ChannelManager: """ if websocket in self.channels.keys(): channel = self.channels[websocket] + + logger.debug(f"Disconnecting channel - {channel}") + if not channel.is_closed(): await channel.close() - del channel + del self.channels[websocket] async def disconnect_all(self): """ @@ -102,5 +109,15 @@ class ChannelManager: :param data: The data to send """ - for channel in self.channels.values(): - await channel.send(data) + for websocket, channel in self.channels.items(): + try: + await channel.send(data) + except RuntimeError: + # Handle cannot send after close cases + await self.on_disconnect(websocket) + + def has_channels(self): + """ + Flag for more than 0 channels + """ + return len(self.channels) > 0 diff --git a/freqtrade/rpc/replicate/proxy.py b/freqtrade/rpc/replicate/proxy.py index b2173670b..aae536b6d 100644 --- a/freqtrade/rpc/replicate/proxy.py +++ b/freqtrade/rpc/replicate/proxy.py @@ -1,11 +1,9 @@ -from typing import TYPE_CHECKING, Union +from typing import Union from fastapi import WebSocket as FastAPIWebSocket from websockets import WebSocketClientProtocol as WebSocket - -if TYPE_CHECKING: - from freqtrade.rpc.replicate.types import WebSocketType +from freqtrade.rpc.replicate.types import WebSocketType class WebSocketProxy: @@ -21,6 +19,9 @@ class WebSocketProxy: """ Send data on the wrapped websocket """ + if isinstance(data, str): + data = data.encode() + if hasattr(self._websocket, "send_bytes"): await self._websocket.send_bytes(data) else: diff --git a/freqtrade/rpc/replicate/serializer.py b/freqtrade/rpc/replicate/serializer.py index ae5e57b95..717458f09 100644 --- a/freqtrade/rpc/replicate/serializer.py +++ b/freqtrade/rpc/replicate/serializer.py @@ -33,10 +33,10 @@ class WebSocketSerializer(ABC): class JSONWebSocketSerializer(WebSocketSerializer): - def _serialize(self, data: bytes) -> bytes: + def _serialize(self, data): # json expects string not bytes - return json.dumps(data.decode()).encode() + return json.dumps(data) - def _deserialize(self, data: bytes) -> bytes: + def _deserialize(self, data): # The WebSocketSerializer gives bytes not string - return json.loads(data).encode() + return json.loads(data) diff --git a/freqtrade/rpc/replicate/types.py b/freqtrade/rpc/replicate/types.py index 5d8c158bd..763147196 100644 --- a/freqtrade/rpc/replicate/types.py +++ b/freqtrade/rpc/replicate/types.py @@ -3,7 +3,5 @@ from typing import TypeVar from fastapi import WebSocket as FastAPIWebSocket from websockets import WebSocketClientProtocol as WebSocket -from freqtrade.rpc.replicate.channel import WebSocketProxy - -WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket, WebSocketProxy) +WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket) diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 140431586..8eaec21ea 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -59,6 +59,9 @@ class RPCManager: replicate_rpc = ReplicateController(self._rpc, config, apiserver) self.registered_modules.append(replicate_rpc) + # Attach the controller to FreqTrade + freqtrade.replicate_controller = replicate_rpc + apiserver.start_api() def cleanup(self) -> None: From 739b68f8fd5c3ca5cc6eacc1f8a49a76fdedd620 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 19 Aug 2022 22:40:01 -0600 Subject: [PATCH 003/115] ExternalPairList plugin --- freqtrade/constants.py | 3 +- freqtrade/enums/replicate.py | 2 +- freqtrade/freqtradebot.py | 30 +++++---- .../plugins/pairlist/ExternalPairList.py | 61 +++++++++++++++++-- freqtrade/rpc/replicate/__init__.py | 27 +++++--- 5 files changed, 96 insertions(+), 27 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 416b4646f..55363cca1 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -33,7 +33,8 @@ HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss', AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'AgeFilter', 'OffsetFilter', 'PerformanceFilter', 'PrecisionFilter', 'PriceFilter', 'RangeStabilityFilter', - 'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter'] + 'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter', + 'ExternalPairList'] AVAILABLE_PROTECTIONS = ['CooldownPeriod', 'LowProfitPairs', 'MaxDrawdown', 'StoplossGuard'] AVAILABLE_DATAHANDLERS = ['json', 'jsongz', 'hdf5'] BACKTEST_BREAKDOWNS = ['day', 'week', 'month'] diff --git a/freqtrade/enums/replicate.py b/freqtrade/enums/replicate.py index 501d119f3..73be996c0 100644 --- a/freqtrade/enums/replicate.py +++ b/freqtrade/enums/replicate.py @@ -7,4 +7,4 @@ class ReplicateModeType(str, Enum): class LeaderMessageType(str, Enum): - whitelist = "whitelist" + pairlist = "pairlist" diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index ac6a998c5..b2ec1448e 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -17,8 +17,8 @@ from freqtrade.constants import BuySell, LongShort from freqtrade.data.converter import order_book_to_dataframe from freqtrade.data.dataprovider import DataProvider from freqtrade.edge import Edge -from freqtrade.enums import (ExitCheckTuple, ExitType, RPCMessageType, RunMode, SignalDirection, - State, TradingMode) +from freqtrade.enums import (ExitCheckTuple, ExitType, LeaderMessageType, RPCMessageType, RunMode, + SignalDirection, State, TradingMode) from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError, InvalidOrderException, PricingError) from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds @@ -257,6 +257,22 @@ class FreqtradeBot(LoggingMixin): self.pairlists.refresh_pairlist() _whitelist = self.pairlists.whitelist + # If replicate leader, broadcast whitelist data + # Should we broadcast before trade pairs are added? What if + # the follower doesn't have trades with those pairs. They would be added for + # no reason. + + # Or should this class be made available to the PairListManager and ran + # when filter_pairlist is called? + if self.replicate_controller: + if self.replicate_controller.is_leader(): + self.replicate_controller.send_message( + { + "data_type": LeaderMessageType.pairlist, + "data": _whitelist + } + ) + # Calculating Edge positioning if self.edge: self.edge.calculate(_whitelist) @@ -267,16 +283,6 @@ class FreqtradeBot(LoggingMixin): # It ensures that candle (OHLCV) data are downloaded for open trades as well _whitelist.extend([trade.pair for trade in trades if trade.pair not in _whitelist]) - # If replicate leader, broadcast whitelist data - if self.replicate_controller: - if self.replicate_controller.is_leader(): - self.replicate_controller.send_message( - { - "data_type": "whitelist", - "data": _whitelist - } - ) - return _whitelist def get_free_open_trades(self) -> int: diff --git a/freqtrade/plugins/pairlist/ExternalPairList.py b/freqtrade/plugins/pairlist/ExternalPairList.py index 832c3d5eb..82fc12ff9 100644 --- a/freqtrade/plugins/pairlist/ExternalPairList.py +++ b/freqtrade/plugins/pairlist/ExternalPairList.py @@ -4,6 +4,7 @@ External Pair List provider Provides pair list from Leader data """ import logging +from threading import Event from typing import Any, Dict, List from freqtrade.plugins.pairlist.IPairList import IPairList @@ -13,16 +14,41 @@ logger = logging.getLogger(__name__) class ExternalPairList(IPairList): + """ + PairList plugin for use with replicate follower mode. + Will use pairs given from leader data. + + Usage: + "pairlists": [ + { + "method": "ExternalPairList", + "number_assets": 5, # We can limit the amount of pairs to use from leader + } + ], + """ def __init__(self, exchange, pairlistmanager, config: Dict[str, Any], pairlistconfig: Dict[str, Any], pairlist_pos: int) -> None: super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos) - self._num_assets = self._pairlistconfig.get('num_assets') - self._allow_inactive = self._pairlistconfig.get('allow_inactive', False) + # Not sure how to enforce ExternalPairList as the only PairList + + self._num_assets = self._pairlistconfig.get('number_assets') self._leader_pairs: List[str] = [] + self._has_data = Event() + + def _clamped_pairlist(self): + """ + Return the self._leader_pairs pairlist limited to the maximum set num_assets + or the length of it. + """ + length = len(self._leader_pairs) + if self._num_assets: + return self._leader_pairs[:min(length, self._num_assets)] + else: + return self._leader_pairs @property def needstickers(self) -> bool: @@ -40,13 +66,40 @@ class ExternalPairList(IPairList): """ return f"{self.name}" + def add_pairlist_data(self, pairlist: List[str]): + """ + Add pairs from Leader + """ + + # If some pairs were removed on Leader, remove them here + for pair in self._leader_pairs: + if pair not in pairlist: + logger.debug(f"Leader removed pair: {pair}") + self._leader_pairs.remove(pair) + + # Only add new pairs + seen = set(self._leader_pairs) + for pair in pairlist: + if pair in seen: + logger.debug(f"Encountered already existing pair {pair}") + continue + self._leader_pairs.append(pair) + + if not self._has_data.is_set(): + self._has_data.set() + def gen_pairlist(self, tickers: Dict) -> List[str]: """ Generate the pairlist :param tickers: Tickers (from exchange.get_tickers()). May be cached. :return: List of pairs """ - pass + if not self._has_data.is_set(): + logger.info("Waiting on pairlists from Leaders...") + self._has_data.wait() + logger.info("Pairlist data received...") + + return self._clamped_pairlist() def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]: """ @@ -56,4 +109,4 @@ class ExternalPairList(IPairList): :param tickers: Tickers (from exchange.get_tickers()). May be cached. :return: new whitelist """ - pass + return self._clamped_pairlist() diff --git a/freqtrade/rpc/replicate/__init__.py b/freqtrade/rpc/replicate/__init__.py index 80ac0836c..fd718197e 100644 --- a/freqtrade/rpc/replicate/__init__.py +++ b/freqtrade/rpc/replicate/__init__.py @@ -40,6 +40,7 @@ class ReplicateController(RPCHandler): """ super().__init__(rpc, config) + self.freqtrade = rpc._freqtrade self.api_server = api_server if not self.api_server: @@ -122,7 +123,6 @@ class ReplicateController(RPCHandler): raise RuntimeError("Loop must be started before any function can" " be submitted") - logger.debug(f"Running coroutine {repr(coroutine)} in loop") try: return asyncio.run_coroutine_threadsafe(coroutine, self._loop) except Exception as e: @@ -185,6 +185,8 @@ class ReplicateController(RPCHandler): def send_message(self, msg: Dict[str, Any]) -> None: """ Push message through """ + # We should probably do some type of schema validation here + if self.channel_manager.has_channels(): self._send_message(msg) else: @@ -199,7 +201,7 @@ class ReplicateController(RPCHandler): if self._queue: queue = self._queue.sync_q - queue.put(msg) + queue.put(msg) # This will block if the queue is full else: logger.warning("Can not send data, leader loop has not started yet!") @@ -235,7 +237,7 @@ class ReplicateController(RPCHandler): try: await self._broadcast_queue_data() except Exception as e: - logger.error("Exception occurred in leader loop: ") + logger.error("Exception occurred in Leader loop: ") logger.exception(e) async def _broadcast_queue_data(self): @@ -342,10 +344,14 @@ class ReplicateController(RPCHandler): logger.info("Starting rpc.replicate in Follower mode") try: - await self._connect_to_leaders() + results = await self._connect_to_leaders() except Exception as e: - logger.error("Exception occurred in follower loop: ") + logger.error("Exception occurred in Follower loop: ") logger.exception(e) + finally: + for result in results: + if isinstance(result, Exception): + logger.debug(f"Exception in Follower loop: {result}") async def _connect_to_leaders(self): """ @@ -372,7 +378,7 @@ class ReplicateController(RPCHandler): websocket_url = f"{url}?token={token}" - logger.info(f"Attempting to connect to leader at: {url}") + logger.info(f"Attempting to connect to Leader at: {url}") # TODO: limit the amount of connection retries while True: try: @@ -415,9 +421,12 @@ class ReplicateController(RPCHandler): except asyncio.CancelledError: pass - async def _handle_leader_message(self, message): + async def _handle_leader_message(self, message: Dict[str, Any]): type = message.get('data_type') data = message.get('data') - if type == LeaderMessageType.whitelist: - logger.info(f"Received whitelist from Leader: {data}") + logger.info(f"Received message from Leader: {type} - {data}") + + if type == LeaderMessageType.pairlist: + # Add the data to the ExternalPairlist + self.freqtrade.pairlists._pairlist_handlers[0].add_pairlist_data(data) From 6f5478cc029bc146e3980affa61dd7956c5cb416 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sun, 21 Aug 2022 22:45:36 -0600 Subject: [PATCH 004/115] DataFrame transmission, strategy follower logic --- freqtrade/data/dataprovider.py | 57 ++++++++++- freqtrade/enums/replicate.py | 1 + freqtrade/freqtradebot.py | 43 +++++++-- freqtrade/misc.py | 22 +++++ .../plugins/pairlist/ExternalPairList.py | 3 +- freqtrade/rpc/replicate/__init__.py | 94 +++++++++++-------- freqtrade/rpc/replicate/channel.py | 16 +++- freqtrade/rpc/replicate/serializer.py | 27 +++++- freqtrade/rpc/replicate/types.py | 3 +- freqtrade/rpc/rpc.py | 39 +++++++- freqtrade/rpc/rpc_manager.py | 13 ++- freqtrade/strategy/interface.py | 92 +++++++++++++++--- requirements-replicate.txt | 1 + 13 files changed, 332 insertions(+), 79 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 21cead77f..3de73bb0d 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -7,6 +7,7 @@ Common Interface for bot and strategy to access data. import logging from collections import deque from datetime import datetime, timezone +from threading import Event from typing import Any, Dict, List, Optional, Tuple from pandas import DataFrame @@ -28,13 +29,16 @@ MAX_DATAFRAME_CANDLES = 1000 class DataProvider: - def __init__(self, config: dict, exchange: Optional[Exchange], pairlists=None) -> None: + def __init__(self, config: dict, exchange: Optional[Exchange], + pairlists=None, replicate_controller=None) -> None: self._config = config self._exchange = exchange self._pairlists = pairlists self.__cached_pairs: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {} self.__slice_index: Optional[int] = None self.__cached_pairs_backtesting: Dict[PairWithTimeframe, DataFrame] = {} + self.__external_pairs_df: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {} + self.__external_pairs_event: Dict[str, Event] = {} self._msg_queue: deque = deque() self.__msg_cache = PeriodicCache( @@ -63,9 +67,58 @@ class DataProvider: :param dataframe: analyzed dataframe :param candle_type: Any of the enum CandleType (must match trading mode!) """ - self.__cached_pairs[(pair, timeframe, candle_type)] = ( + pair_key = (pair, timeframe, candle_type) + self.__cached_pairs[pair_key] = ( dataframe, datetime.now(timezone.utc)) + def add_external_df( + self, + pair: str, + timeframe: str, + dataframe: DataFrame, + candle_type: CandleType + ) -> None: + """ + Add the DataFrame to the __external_pairs_df. If a pair event exists, + set it to release the main thread from waiting. + """ + pair_key = (pair, timeframe, candle_type) + + # Delete stale data + if pair_key in self.__external_pairs_df: + del self.__external_pairs_df[pair_key] + + self.__external_pairs_df[pair_key] = (dataframe, datetime.now(timezone.utc)) + + pair_event = self.__external_pairs_event.get(pair) + if pair_event: + logger.debug(f"Leader data for pair {pair_key} has been added") + pair_event.set() + + def get_external_df( + self, + pair: str, + timeframe: str, + candle_type: CandleType + ) -> DataFrame: + """ + If the pair exists in __external_pairs_df, return it. If it doesn't, + create a new threading Event in __external_pairs_event and wait on it. + """ + pair_key = (pair, timeframe, candle_type) + if pair_key not in self.__external_pairs_df: + pair_event = Event() + self.__external_pairs_event[pair] = pair_event + + logger.debug(f"Waiting on Leader data for: {pair_key}") + self.__external_pairs_event[pair].wait() + + if pair_key in self.__external_pairs_df: + return self.__external_pairs_df[pair_key] + + # Because of the waiting mechanism, this should never return + return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) + def add_pairlisthandler(self, pairlists) -> None: """ Allow adding pairlisthandler after initialization diff --git a/freqtrade/enums/replicate.py b/freqtrade/enums/replicate.py index 73be996c0..8d036f0b9 100644 --- a/freqtrade/enums/replicate.py +++ b/freqtrade/enums/replicate.py @@ -8,3 +8,4 @@ class ReplicateModeType(str, Enum): class LeaderMessageType(str, Enum): pairlist = "pairlist" + analyzed_df = "analyzed_df" diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index b2ec1448e..3b850dd4e 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -23,7 +23,7 @@ from freqtrade.exceptions import (DependencyException, ExchangeError, Insufficie InvalidOrderException, PricingError) from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds from freqtrade.exchange.exchange import timeframe_to_next_date -from freqtrade.misc import safe_value_fallback, safe_value_fallback2 +from freqtrade.misc import dataframe_to_json, safe_value_fallback, safe_value_fallback2 from freqtrade.mixins import LoggingMixin from freqtrade.persistence import Order, PairLocks, Trade, init_db from freqtrade.plugins.pairlistmanager import PairListManager @@ -77,6 +77,8 @@ class FreqtradeBot(LoggingMixin): self.replicate_controller = None + self.pairlists = PairListManager(self.exchange, self.config) + # RPC runs in separate threads, can start handling external commands just after # initialization, even before Freqtradebot has a chance to start its throttling, # so anything in the Freqtradebot instance should be ready (initialized), including @@ -84,8 +86,6 @@ class FreqtradeBot(LoggingMixin): # Keep this at the end of this initialization method. self.rpc: RPCManager = RPCManager(self) - self.pairlists = PairListManager(self.exchange, self.config) - self.dataprovider = DataProvider(self.config, self.exchange, self.pairlists) # Attach Dataprovider to strategy instance @@ -93,6 +93,9 @@ class FreqtradeBot(LoggingMixin): # Attach Wallets to strategy instance self.strategy.wallets = self.wallets + # Attach ReplicateController to the strategy + # self.strategy.replicate_controller = self.replicate_controller + # Initializing Edge only if enabled self.edge = Edge(self.config, self.exchange, self.strategy) if \ self.config.get('edge', {}).get('enabled', False) else None @@ -194,7 +197,28 @@ class FreqtradeBot(LoggingMixin): strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)() - self.strategy.analyze(self.active_pair_whitelist) + if self.replicate_controller: + if not self.replicate_controller.is_leader(): + # Run Follower mode analyzing + leader_pairs = self.pairlists._whitelist + self.strategy.analyze_external(self.active_pair_whitelist, leader_pairs) + else: + # We are leader, make sure to pass callback func to emit data + def emit_on_finish(pair, dataframe, timeframe, candle_type): + logger.debug(f"Emitting dataframe for {pair}") + return self.rpc.emit_data( + { + "data_type": LeaderMessageType.analyzed_df, + "data": { + "key": (pair, timeframe, candle_type), + "value": dataframe_to_json(dataframe) + } + } + ) + + self.strategy.analyze(self.active_pair_whitelist, finish_callback=emit_on_finish) + else: + self.strategy.analyze(self.active_pair_whitelist) with self._exit_lock: # Check for exchange cancelations, timeouts and user requested replace @@ -264,14 +288,13 @@ class FreqtradeBot(LoggingMixin): # Or should this class be made available to the PairListManager and ran # when filter_pairlist is called? + if self.replicate_controller: if self.replicate_controller.is_leader(): - self.replicate_controller.send_message( - { - "data_type": LeaderMessageType.pairlist, - "data": _whitelist - } - ) + self.rpc.emit_data({ + "data_type": LeaderMessageType.pairlist, + "data": _whitelist + }) # Calculating Edge positioning if self.edge: diff --git a/freqtrade/misc.py b/freqtrade/misc.py index c3968e61c..bc644a7ec 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -10,6 +10,7 @@ from typing import Any, Iterator, List from typing.io import IO from urllib.parse import urlparse +import pandas import rapidjson from freqtrade.constants import DECIMAL_PER_COIN_FALLBACK, DECIMALS_PER_COIN @@ -249,3 +250,24 @@ def parse_db_uri_for_logging(uri: str): return uri pwd = parsed_db_uri.netloc.split(':')[1].split('@')[0] return parsed_db_uri.geturl().replace(f':{pwd}@', ':*****@') + + +def dataframe_to_json(dataframe: pandas.DataFrame) -> str: + """ + Serialize a DataFrame for transmission over the wire using JSON + :param dataframe: A pandas DataFrame + :returns: A JSON string of the pandas DataFrame + """ + return dataframe.to_json(orient='records') + + +def json_to_dataframe(data: str) -> pandas.DataFrame: + """ + Deserialize JSON into a DataFrame + :param data: A JSON string + :returns: A pandas DataFrame from the JSON string + """ + dataframe = pandas.read_json(data) + dataframe['date'] = pandas.to_datetime(dataframe['date'], unit='ms', utc=True) + + return dataframe diff --git a/freqtrade/plugins/pairlist/ExternalPairList.py b/freqtrade/plugins/pairlist/ExternalPairList.py index 82fc12ff9..bd36c7cf3 100644 --- a/freqtrade/plugins/pairlist/ExternalPairList.py +++ b/freqtrade/plugins/pairlist/ExternalPairList.py @@ -81,11 +81,10 @@ class ExternalPairList(IPairList): seen = set(self._leader_pairs) for pair in pairlist: if pair in seen: - logger.debug(f"Encountered already existing pair {pair}") continue self._leader_pairs.append(pair) - if not self._has_data.is_set(): + if not self._has_data.is_set() and len(self._leader_pairs) > 0: self._has_data.set() def gen_pairlist(self, tickers: Dict) -> List[str]: diff --git a/freqtrade/rpc/replicate/__init__.py b/freqtrade/rpc/replicate/__init__.py index fd718197e..5cc2ae6a9 100644 --- a/freqtrade/rpc/replicate/__init__.py +++ b/freqtrade/rpc/replicate/__init__.py @@ -5,6 +5,7 @@ import asyncio import logging import secrets import socket +import traceback from threading import Event, Thread from typing import Any, Coroutine, Dict, Union @@ -17,6 +18,7 @@ from freqtrade.enums import LeaderMessageType, ReplicateModeType, RPCMessageType from freqtrade.rpc import RPC, RPCHandler from freqtrade.rpc.replicate.channel import ChannelManager from freqtrade.rpc.replicate.thread_queue import Queue as ThreadedQueue +from freqtrade.rpc.replicate.types import MessageType from freqtrade.rpc.replicate.utils import is_websocket_alive @@ -79,11 +81,11 @@ class ReplicateController(RPCHandler): self.mode = ReplicateModeType[self.replicate_config.get('mode', 'leader').lower()] self.leaders_list = self.replicate_config.get('leaders', []) - self.push_throttle_secs = self.replicate_config.get('push_throttle_secs', 1) + self.push_throttle_secs = self.replicate_config.get('push_throttle_secs', 0.1) self.reply_timeout = self.replicate_config.get('follower_reply_timeout', 10) self.ping_timeout = self.replicate_config.get('follower_ping_timeout', 2) - self.sleep_time = self.replicate_config.get('follower_sleep_time', 1) + self.sleep_time = self.replicate_config.get('follower_sleep_time', 5) if self.mode == ReplicateModeType.follower and len(self.leaders_list) == 0: raise ValueError("You must specify at least 1 leader in follower mode.") @@ -143,6 +145,8 @@ class ReplicateController(RPCHandler): except asyncio.CancelledError: pass + except Exception: + pass finally: self._loop.stop() @@ -170,22 +174,19 @@ class ReplicateController(RPCHandler): self._thread.join() - def send_msg(self, msg: Dict[str, Any]) -> None: + def send_msg(self, msg: MessageType) -> None: """ Support RPC calls """ if msg["type"] == RPCMessageType.EMIT_DATA: - self.send_message( - { - "data_type": msg.get("data_type"), - "data": msg.get("data") - } - ) + message = msg.get("message") + if message: + self.send_message(message) + else: + logger.error(f"Message is empty! {msg}") - def send_message(self, msg: Dict[str, Any]) -> None: - """ Push message through """ - - # We should probably do some type of schema validation here + def send_message(self, msg: MessageType) -> None: + """ Broadcast message over all channels if there are any """ if self.channel_manager.has_channels(): self._send_message(msg) @@ -193,12 +194,11 @@ class ReplicateController(RPCHandler): logger.debug("No listening followers, skipping...") pass - def _send_message(self, msg: Dict[Any, Any]): + def _send_message(self, msg: MessageType): """ Add data to the internal queue to be broadcasted. This func will block if the queue is full. This is meant to be called in the main thread. """ - if self._queue: queue = self._queue.sync_q queue.put(msg) # This will block if the queue is full @@ -226,7 +226,6 @@ class ReplicateController(RPCHandler): This starts all of the leader coros and registers the endpoint on the ApiServer """ - logger.info("Running rpc.replicate in Leader mode") logger.info("-" * 15) logger.info(f"API_KEY: {self.secret_api_key}") @@ -253,16 +252,17 @@ class ReplicateController(RPCHandler): # Get data from queue data = await async_queue.get() - logger.info(f"Found data - broadcasting: {data}") - # Broadcast it to everyone await self.channel_manager.broadcast(data) # Sleep await asyncio.sleep(self.push_throttle_secs) + except asyncio.CancelledError: # Silently stop pass + except Exception as e: + logger.exception(e) async def get_api_token( self, @@ -285,7 +285,6 @@ class ReplicateController(RPCHandler): :param path: The endpoint path """ - if not self.api_server: raise RuntimeError("The leader needs the ApiServer to be active") @@ -312,10 +311,13 @@ class ReplicateController(RPCHandler): # we may not have to send initial data at all. Further testing # required. + await self.send_initial_data(channel) + # Keep connection open until explicitly closed, and sleep try: while not channel.is_closed(): - await channel.recv() + request = await channel.recv() + logger.info(f"Follower request - {request}") except WebSocketDisconnect: # Handle client disconnects @@ -332,6 +334,17 @@ class ReplicateController(RPCHandler): logger.error(f"Failed to serve - {websocket.client}") await self.channel_manager.on_disconnect(websocket) + async def send_initial_data(self, channel): + logger.info("Sending initial data through channel") + + # We first send pairlist data + initial_data = { + "data_type": LeaderMessageType.pairlist, + "data": self.freqtrade.pairlists.whitelist + } + + await channel.send(initial_data) + # -------------------------------FOLLOWER LOGIC---------------------------- async def follower_loop(self): @@ -340,18 +353,27 @@ class ReplicateController(RPCHandler): This starts all of the follower connection coros """ - logger.info("Starting rpc.replicate in Follower mode") - try: - results = await self._connect_to_leaders() - except Exception as e: - logger.error("Exception occurred in Follower loop: ") - logger.exception(e) - finally: - for result in results: - if isinstance(result, Exception): - logger.debug(f"Exception in Follower loop: {result}") + responses = await self._connect_to_leaders() + + # Eventually add the ability to send requests to the Leader + # await self._send_requests() + + for result in responses: + if isinstance(result, Exception): + logger.debug(f"Exception in Follower loop: {result}") + traceback_message = ''.join(traceback.format_tb(result.__traceback__)) + logger.error(traceback_message) + + async def _handle_leader_message(self, message: MessageType): + """ + Handle message received from a Leader + """ + type = message.get("data_type") + data = message.get("data") + + self._rpc._handle_emitted_data(type, data) async def _connect_to_leaders(self): """ @@ -375,7 +397,6 @@ class ReplicateController(RPCHandler): """ try: url, token = leader["url"], leader["token"] - websocket_url = f"{url}?token={token}" logger.info(f"Attempting to connect to Leader at: {url}") @@ -384,6 +405,7 @@ class ReplicateController(RPCHandler): try: async with websockets.connect(websocket_url) as ws: channel = await self.channel_manager.on_connect(ws) + logger.info(f"Connection to Leader at {url} successful") while True: try: data = await asyncio.wait_for( @@ -420,13 +442,3 @@ class ReplicateController(RPCHandler): except asyncio.CancelledError: pass - - async def _handle_leader_message(self, message: Dict[str, Any]): - type = message.get('data_type') - data = message.get('data') - - logger.info(f"Received message from Leader: {type} - {data}") - - if type == LeaderMessageType.pairlist: - # Add the data to the ExternalPairlist - self.freqtrade.pairlists._pairlist_handlers[0].add_pairlist_data(data) diff --git a/freqtrade/rpc/replicate/channel.py b/freqtrade/rpc/replicate/channel.py index 7aa316ff5..62ed3e025 100644 --- a/freqtrade/rpc/replicate/channel.py +++ b/freqtrade/rpc/replicate/channel.py @@ -2,7 +2,7 @@ import logging from typing import Type from freqtrade.rpc.replicate.proxy import WebSocketProxy -from freqtrade.rpc.replicate.serializer import JSONWebSocketSerializer, WebSocketSerializer +from freqtrade.rpc.replicate.serializer import MsgPackWebSocketSerializer, WebSocketSerializer from freqtrade.rpc.replicate.types import WebSocketType @@ -17,7 +17,7 @@ class WebSocketChannel: def __init__( self, websocket: WebSocketType, - serializer_cls: Type[WebSocketSerializer] = JSONWebSocketSerializer + serializer_cls: Type[WebSocketSerializer] = MsgPackWebSocketSerializer ): # The WebSocket object self._websocket = WebSocketProxy(websocket) @@ -34,6 +34,7 @@ class WebSocketChannel: """ Send data on the wrapped websocket """ + # logger.info(f"Serialized Send - {self._wrapped_ws._serialize(data)}") await self._wrapped_ws.send(data) async def recv(self): @@ -116,6 +117,17 @@ class ChannelManager: # Handle cannot send after close cases await self.on_disconnect(websocket) + async def send_direct(self, channel, data): + """ + Send data directly through direct_channel only + + :param direct_channel: The WebSocketChannel object to send data through + :param data: The data to send + """ + # We iterate over the channels to get reference to the websocket object + # so we can disconnect incase of failure + await channel.send(data) + def has_channels(self): """ Flag for more than 0 channels diff --git a/freqtrade/rpc/replicate/serializer.py b/freqtrade/rpc/replicate/serializer.py index 717458f09..98bdc8934 100644 --- a/freqtrade/rpc/replicate/serializer.py +++ b/freqtrade/rpc/replicate/serializer.py @@ -1,9 +1,16 @@ import json +import logging from abc import ABC, abstractmethod +import msgpack +import orjson + from freqtrade.rpc.replicate.proxy import WebSocketProxy +logger = logging.getLogger(__name__) + + class WebSocketSerializer(ABC): def __init__(self, websocket: WebSocketProxy): self._websocket: WebSocketProxy = websocket @@ -34,9 +41,25 @@ class WebSocketSerializer(ABC): class JSONWebSocketSerializer(WebSocketSerializer): def _serialize(self, data): - # json expects string not bytes return json.dumps(data) def _deserialize(self, data): - # The WebSocketSerializer gives bytes not string return json.loads(data) + + +class ORJSONWebSocketSerializer(WebSocketSerializer): + ORJSON_OPTIONS = orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY + + def _serialize(self, data): + return orjson.dumps(data, option=self.ORJSON_OPTIONS) + + def _deserialize(self, data): + return orjson.loads(data, option=self.ORJSON_OPTIONS) + + +class MsgPackWebSocketSerializer(WebSocketSerializer): + def _serialize(self, data): + return msgpack.packb(data, use_bin_type=True) + + def _deserialize(self, data): + return msgpack.unpackb(data, raw=False) diff --git a/freqtrade/rpc/replicate/types.py b/freqtrade/rpc/replicate/types.py index 763147196..814fe6649 100644 --- a/freqtrade/rpc/replicate/types.py +++ b/freqtrade/rpc/replicate/types.py @@ -1,7 +1,8 @@ -from typing import TypeVar +from typing import Any, Dict, TypeVar from fastapi import WebSocket as FastAPIWebSocket from websockets import WebSocketClientProtocol as WebSocket WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket) +MessageType = Dict[str, Any] diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index ed7f13a96..2c7b2ec72 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -19,12 +19,12 @@ from freqtrade.configuration.timerange import TimeRange from freqtrade.constants import CANCEL_REASON, DATETIME_PRINT_FORMAT from freqtrade.data.history import load_data from freqtrade.data.metrics import calculate_max_drawdown -from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirection, State, - TradingMode) +from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, LeaderMessageType, + SignalDirection, State, TradingMode) from freqtrade.exceptions import ExchangeError, PricingError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs from freqtrade.loggers import bufferHandler -from freqtrade.misc import decimals_per_coin, shorten_date +from freqtrade.misc import decimals_per_coin, json_to_dataframe, shorten_date from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence.models import PairLock from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist @@ -1089,3 +1089,36 @@ class RPC: 'last_process_loc': last_p.astimezone(tzlocal()).strftime(DATETIME_PRINT_FORMAT), 'last_process_ts': int(last_p.timestamp()), } + + def _handle_emitted_data(self, type, data): + """ + Handles the emitted data from the Leaders + + :param type: The data_type of the data + :param data: The data + """ + logger.debug(f"Handling emitted data of type ({type})") + + if type == LeaderMessageType.pairlist: + pairlist = data + + logger.debug(pairlist) + + # Add the pairlist data to the ExternalPairList object + external_pairlist = self._freqtrade.pairlists._pairlist_handlers[0] + external_pairlist.add_pairlist_data(pairlist) + + elif type == LeaderMessageType.analyzed_df: + # Convert the dataframe back from json + key, value = data["key"], data["value"] + + pair, timeframe, candle_type = key + dataframe = json_to_dataframe(value) + + dataprovider = self._freqtrade.dataprovider + + logger.debug(f"Received analyzed dataframe for {pair}") + logger.debug(dataframe.tail()) + + # Add the dataframe to the dataprovider + dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 8eaec21ea..3d561cc8e 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -20,6 +20,7 @@ class RPCManager: def __init__(self, freqtrade) -> None: """ Initializes all enabled rpc modules """ self.registered_modules: List[RPCHandler] = [] + self._freqtrade = freqtrade self._rpc = RPC(freqtrade) config = freqtrade.config # Enable telegram @@ -82,7 +83,8 @@ class RPCManager: 'status': 'stopping bot' } """ - logger.info('Sending rpc message: %s', msg) + if msg.get("type") != RPCMessageType.EMIT_DATA: + logger.info('Sending rpc message: %s', msg) if 'pair' in msg: msg.update({ 'base_currency': self._rpc._freqtrade.exchange.get_pair_base_currency(msg['pair']) @@ -141,3 +143,12 @@ class RPCManager: 'type': RPCMessageType.STARTUP, 'status': f'Using Protections: \n{prots}' }) + + def emit_data(self, data: Dict[str, Any]): + """ + Send a message via RPC with type RPCMessageType.EMIT_DATA + """ + self.send_msg({ + "type": RPCMessageType.EMIT_DATA, + "message": data + }) diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index 79dbd4c69..ddd10dd8e 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -5,7 +5,7 @@ This module defines the interface to apply for strategies import logging from abc import ABC, abstractmethod from datetime import datetime, timedelta, timezone -from typing import Dict, List, Optional, Tuple, Union +from typing import Callable, Dict, List, Optional, Tuple, Union import arrow from pandas import DataFrame @@ -18,6 +18,7 @@ from freqtrade.enums.runmode import RunMode from freqtrade.exceptions import OperationalException, StrategyError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date, timeframe_to_seconds from freqtrade.persistence import Order, PairLocks, Trade +from freqtrade.rpc.replicate import ReplicateController from freqtrade.strategy.hyper import HyperStrategyMixin from freqtrade.strategy.informative_decorator import (InformativeData, PopulateIndicators, _create_and_merge_informative_pair, @@ -110,6 +111,7 @@ class IStrategy(ABC, HyperStrategyMixin): # the dataprovider (dp) (access to other candles, historic data, ...) # and wallets - access to the current balance. dp: DataProvider + replicate_controller: Optional[ReplicateController] wallets: Optional[Wallets] = None # Filled from configuration stake_currency: str @@ -123,6 +125,7 @@ class IStrategy(ABC, HyperStrategyMixin): self.config = config # Dict to determine if analysis is necessary self._last_candle_seen_per_pair: Dict[str, datetime] = {} + self._last_candle_seen_external: Dict[str, datetime] = {} super().__init__(config) # Gather informative pairs from @informative-decorated methods. @@ -678,7 +681,12 @@ class IStrategy(ABC, HyperStrategyMixin): lock_time = timeframe_to_next_date(self.timeframe, candle_date) return PairLocks.is_pair_locked(pair, lock_time, side=side) - def analyze_ticker(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + def analyze_ticker( + self, + dataframe: DataFrame, + metadata: dict, + populate_indicators: bool = True + ) -> DataFrame: """ Parses the given candle (OHLCV) data and returns a populated DataFrame add several TA indicators and entry order signal to it @@ -687,12 +695,19 @@ class IStrategy(ABC, HyperStrategyMixin): :return: DataFrame of candle (OHLCV) data with indicator data and signals added """ logger.debug("TA Analysis Launched") - dataframe = self.advise_indicators(dataframe, metadata) + if populate_indicators: + dataframe = self.advise_indicators(dataframe, metadata) dataframe = self.advise_entry(dataframe, metadata) dataframe = self.advise_exit(dataframe, metadata) return dataframe - def _analyze_ticker_internal(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + def _analyze_ticker_internal( + self, + dataframe: DataFrame, + metadata: dict, + external_data: bool = False, + finish_callback: Optional[Callable] = None, + ) -> DataFrame: """ Parses the given candle (OHLCV) data and returns a populated DataFrame add several TA indicators and buy signal to it @@ -707,12 +722,19 @@ class IStrategy(ABC, HyperStrategyMixin): # always run if process_only_new_candles is set to false if (not self.process_only_new_candles or self._last_candle_seen_per_pair.get(pair, None) != dataframe.iloc[-1]['date']): + + populate_indicators = not external_data # Defs that only make change on new candle data. - dataframe = self.analyze_ticker(dataframe, metadata) + dataframe = self.analyze_ticker(dataframe, metadata, populate_indicators) + self._last_candle_seen_per_pair[pair] = dataframe.iloc[-1]['date'] - self.dp._set_cached_df( - pair, self.timeframe, dataframe, - candle_type=self.config.get('candle_type_def', CandleType.SPOT)) + + candle_type = self.config.get('candle_type_def', CandleType.SPOT) + self.dp._set_cached_df(pair, self.timeframe, dataframe, candle_type=candle_type) + + if finish_callback: + finish_callback(pair, dataframe, self.timeframe, candle_type) + else: logger.debug("Skipping TA Analysis for already analyzed candle") dataframe[SignalType.ENTER_LONG.value] = 0 @@ -726,16 +748,25 @@ class IStrategy(ABC, HyperStrategyMixin): return dataframe - def analyze_pair(self, pair: str) -> None: + def analyze_pair( + self, + pair: str, + external_data: bool = False, + finish_callback: Optional[Callable] = None, + ) -> None: """ Fetch data for this pair from dataprovider and analyze. Stores the dataframe into the dataprovider. The analyzed dataframe is then accessible via `dp.get_analyzed_dataframe()`. :param pair: Pair to analyze. """ - dataframe = self.dp.ohlcv( - pair, self.timeframe, candle_type=self.config.get('candle_type_def', CandleType.SPOT) - ) + candle_type = self.config.get('candle_type_def', CandleType.SPOT) + + if not external_data: + dataframe = self.dp.ohlcv(pair, self.timeframe, candle_type) + else: + dataframe, last_analyzed = self.dp.get_external_df(pair, self.timeframe, candle_type) + if not isinstance(dataframe, DataFrame) or dataframe.empty: logger.warning('Empty candle (OHLCV) data for pair %s', pair) return @@ -745,7 +776,7 @@ class IStrategy(ABC, HyperStrategyMixin): dataframe = strategy_safe_wrapper( self._analyze_ticker_internal, message="" - )(dataframe, {'pair': pair}) + )(dataframe, {'pair': pair}, external_data, finish_callback) self.assert_df(dataframe, df_len, df_close, df_date) except StrategyError as error: @@ -756,15 +787,43 @@ class IStrategy(ABC, HyperStrategyMixin): logger.warning('Empty dataframe for pair %s', pair) return - def analyze(self, pairs: List[str]) -> None: + def analyze( + self, + pairs: List[str], + finish_callback: Optional[Callable] = None + ) -> None: """ Analyze all pairs using analyze_pair(). :param pairs: List of pairs to analyze """ for pair in pairs: + self.analyze_pair(pair, finish_callback=finish_callback) + + def analyze_external(self, pairs: List[str], leader_pairs: List[str]) -> None: + """ + Analyze the pre-populated dataframes from the Leader + + :param pairs: The active pair whitelist + :param leader_pairs: The list of pairs from the Leaders + """ + + # Get the extra pairs not listed in Leader pairs, and process + # them normally. + # List order is not preserved when doing this! + # We use ^ instead of - for symmetric difference + # What do we do with these? + extra_pairs = list(set(pairs) ^ set(leader_pairs)) + # These would be the pairs that we have trades in, which means + # we would have to analyze them normally + + for pair in leader_pairs: + # Analyze the pairs, but get the dataframe from the external data + self.analyze_pair(pair, external_data=True) + + for pair in extra_pairs: self.analyze_pair(pair) - @staticmethod + @ staticmethod def preserve_df(dataframe: DataFrame) -> Tuple[int, float, datetime]: """ keep some data for dataframes """ return len(dataframe), dataframe["close"].iloc[-1], dataframe["date"].iloc[-1] @@ -1185,6 +1244,9 @@ class IStrategy(ABC, HyperStrategyMixin): dataframe = _create_and_merge_informative_pair( self, dataframe, metadata, inf_data, populate_fn) + # If in follower mode, get analyzed dataframe from leader df's in dp + # otherise run populate_indicators + return self.populate_indicators(dataframe, metadata) def advise_entry(self, dataframe: DataFrame, metadata: dict) -> DataFrame: diff --git a/requirements-replicate.txt b/requirements-replicate.txt index 7ee351d9d..2c994ea2f 100644 --- a/requirements-replicate.txt +++ b/requirements-replicate.txt @@ -3,3 +3,4 @@ # Required for follower websockets +msgpack From 4fa01548f6c6ac49e63b7a4960ede268c0bf3aab Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sun, 21 Aug 2022 22:49:42 -0600 Subject: [PATCH 005/115] Remove old var from strategy interface --- freqtrade/strategy/interface.py | 1 - 1 file changed, 1 deletion(-) diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index ddd10dd8e..1084838ec 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -125,7 +125,6 @@ class IStrategy(ABC, HyperStrategyMixin): self.config = config # Dict to determine if analysis is necessary self._last_candle_seen_per_pair: Dict[str, datetime] = {} - self._last_candle_seen_external: Dict[str, datetime] = {} super().__init__(config) # Gather informative pairs from @informative-decorated methods. From 592373f096ce80c458673b92715b82b09e6b57eb Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 24 Aug 2022 18:30:30 -0600 Subject: [PATCH 006/115] Remove pairlist waiting, add .db files to .gitignore --- .gitignore | 1 + freqtrade/plugins/pairlist/ExternalPairList.py | 10 ---------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/.gitignore b/.gitignore index df2121990..015c0a8d9 100644 --- a/.gitignore +++ b/.gitignore @@ -115,3 +115,4 @@ target/ !config_examples/config_freqai.example.json *-config.json +*.db* diff --git a/freqtrade/plugins/pairlist/ExternalPairList.py b/freqtrade/plugins/pairlist/ExternalPairList.py index bd36c7cf3..40e3f9a7f 100644 --- a/freqtrade/plugins/pairlist/ExternalPairList.py +++ b/freqtrade/plugins/pairlist/ExternalPairList.py @@ -4,7 +4,6 @@ External Pair List provider Provides pair list from Leader data """ import logging -from threading import Event from typing import Any, Dict, List from freqtrade.plugins.pairlist.IPairList import IPairList @@ -37,7 +36,6 @@ class ExternalPairList(IPairList): self._num_assets = self._pairlistconfig.get('number_assets') self._leader_pairs: List[str] = [] - self._has_data = Event() def _clamped_pairlist(self): """ @@ -84,20 +82,12 @@ class ExternalPairList(IPairList): continue self._leader_pairs.append(pair) - if not self._has_data.is_set() and len(self._leader_pairs) > 0: - self._has_data.set() - def gen_pairlist(self, tickers: Dict) -> List[str]: """ Generate the pairlist :param tickers: Tickers (from exchange.get_tickers()). May be cached. :return: List of pairs """ - if not self._has_data.is_set(): - logger.info("Waiting on pairlists from Leaders...") - self._has_data.wait() - logger.info("Pairlist data received...") - return self._clamped_pairlist() def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]: From d474111a65a07c3133d7e2502be648b362fb72ce Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 24 Aug 2022 22:42:29 -0600 Subject: [PATCH 007/115] Renamed to external signals, controller class refactored --- freqtrade/constants.py | 8 +- freqtrade/data/dataprovider.py | 33 +- freqtrade/enums/__init__.py | 2 +- .../enums/{replicate.py => externalsignal.py} | 2 +- freqtrade/freqtradebot.py | 19 +- .../plugins/pairlist/ExternalPairList.py | 4 +- freqtrade/rpc/external_signal/__init__.py | 5 + .../{replicate => external_signal}/channel.py | 6 +- .../controller.py} | 288 +++++++++--------- .../{replicate => external_signal}/proxy.py | 2 +- .../serializer.py | 2 +- .../thread_queue.py | 0 .../{replicate => external_signal}/types.py | 0 .../{replicate => external_signal}/utils.py | 0 freqtrade/rpc/rpc.py | 10 +- freqtrade/rpc/rpc_manager.py | 12 +- freqtrade/strategy/interface.py | 4 +- 17 files changed, 203 insertions(+), 194 deletions(-) rename freqtrade/enums/{replicate.py => externalsignal.py} (80%) create mode 100644 freqtrade/rpc/external_signal/__init__.py rename freqtrade/rpc/{replicate => external_signal}/channel.py (94%) rename freqtrade/rpc/{replicate/__init__.py => external_signal/controller.py} (74%) rename freqtrade/rpc/{replicate => external_signal}/proxy.py (96%) rename freqtrade/rpc/{replicate => external_signal}/serializer.py (96%) rename freqtrade/rpc/{replicate => external_signal}/thread_queue.py (100%) rename freqtrade/rpc/{replicate => external_signal}/types.py (100%) rename freqtrade/rpc/{replicate => external_signal}/utils.py (100%) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 55363cca1..ad0758e22 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -245,7 +245,7 @@ CONF_SCHEMA = { 'exchange': {'$ref': '#/definitions/exchange'}, 'edge': {'$ref': '#/definitions/edge'}, 'freqai': {'$ref': '#/definitions/freqai'}, - 'replicate': {'$ref': '#/definitions/replicate'}, + 'external_signal': {'$ref': '#/definitions/external_signal'}, 'experimental': { 'type': 'object', 'properties': { @@ -487,7 +487,7 @@ CONF_SCHEMA = { }, 'required': ['process_throttle_secs', 'allowed_risk'] }, - 'replicate': { + 'external_signal': { 'type': 'object', 'properties': { 'enabled': {'type': 'boolean', 'default': False}, @@ -495,14 +495,14 @@ CONF_SCHEMA = { 'type': 'string', 'enum': FOLLOWER_MODE_OPTIONS }, - 'api_key': {'type': 'string', 'default': ''}, + 'api_token': {'type': 'string', 'default': ''}, 'leaders': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'url': {'type': 'string', 'default': ''}, - 'token': {'type': 'string', 'default': ''}, + 'api_token': {'type': 'string', 'default': ''}, } } }, diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 3de73bb0d..036005c84 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -29,8 +29,7 @@ MAX_DATAFRAME_CANDLES = 1000 class DataProvider: - def __init__(self, config: dict, exchange: Optional[Exchange], - pairlists=None, replicate_controller=None) -> None: + def __init__(self, config: dict, exchange: Optional[Exchange], pairlists=None) -> None: self._config = config self._exchange = exchange self._pairlists = pairlists @@ -99,25 +98,33 @@ class DataProvider: self, pair: str, timeframe: str, - candle_type: CandleType + candle_type: CandleType, + wait: bool = True ) -> DataFrame: """ - If the pair exists in __external_pairs_df, return it. If it doesn't, - create a new threading Event in __external_pairs_event and wait on it. + If the pair exists in __external_pairs_df, return it. + If it doesn't, and wait is False, then return an empty df with the columns filled. + If it doesn't, and wait is True (default) create a new threading Event + in __external_pairs_event and wait on it. """ pair_key = (pair, timeframe, candle_type) + if pair_key not in self.__external_pairs_df: - pair_event = Event() - self.__external_pairs_event[pair] = pair_event + if wait: + pair_event = Event() + self.__external_pairs_event[pair] = pair_event - logger.debug(f"Waiting on Leader data for: {pair_key}") - self.__external_pairs_event[pair].wait() + logger.debug(f"Waiting on Leader data for: {pair_key}") + self.__external_pairs_event[pair].wait(timeout=5) - if pair_key in self.__external_pairs_df: - return self.__external_pairs_df[pair_key] + if pair_key not in self.__external_pairs_df: + # Return empty dataframe but with expected columns merged and filled with NaN + return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) + else: + # Return empty dataframe but with expected columns merged and filled with NaN + return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) - # Because of the waiting mechanism, this should never return - return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) + return self.__external_pairs_df[pair_key] def add_pairlisthandler(self, pairlists) -> None: """ diff --git a/freqtrade/enums/__init__.py b/freqtrade/enums/__init__.py index e1057208a..913ef82dd 100644 --- a/freqtrade/enums/__init__.py +++ b/freqtrade/enums/__init__.py @@ -3,9 +3,9 @@ from freqtrade.enums.backteststate import BacktestState from freqtrade.enums.candletype import CandleType from freqtrade.enums.exitchecktuple import ExitCheckTuple from freqtrade.enums.exittype import ExitType +from freqtrade.enums.externalsignal import ExternalSignalModeType, LeaderMessageType from freqtrade.enums.marginmode import MarginMode from freqtrade.enums.ordertypevalue import OrderTypeValues -from freqtrade.enums.replicate import LeaderMessageType, ReplicateModeType from freqtrade.enums.rpcmessagetype import RPCMessageType from freqtrade.enums.runmode import NON_UTIL_MODES, OPTIMIZE_MODES, TRADING_MODES, RunMode from freqtrade.enums.signaltype import SignalDirection, SignalTagType, SignalType diff --git a/freqtrade/enums/replicate.py b/freqtrade/enums/externalsignal.py similarity index 80% rename from freqtrade/enums/replicate.py rename to freqtrade/enums/externalsignal.py index 8d036f0b9..4695a4eab 100644 --- a/freqtrade/enums/replicate.py +++ b/freqtrade/enums/externalsignal.py @@ -1,7 +1,7 @@ from enum import Enum -class ReplicateModeType(str, Enum): +class ExternalSignalModeType(str, Enum): leader = "leader" follower = "follower" diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 3b850dd4e..9704b7e08 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -75,7 +75,7 @@ class FreqtradeBot(LoggingMixin): PairLocks.timeframe = self.config['timeframe'] - self.replicate_controller = None + self.external_signal_controller = None self.pairlists = PairListManager(self.exchange, self.config) @@ -93,9 +93,6 @@ class FreqtradeBot(LoggingMixin): # Attach Wallets to strategy instance self.strategy.wallets = self.wallets - # Attach ReplicateController to the strategy - # self.strategy.replicate_controller = self.replicate_controller - # Initializing Edge only if enabled self.edge = Edge(self.config, self.exchange, self.strategy) if \ self.config.get('edge', {}).get('enabled', False) else None @@ -197,8 +194,8 @@ class FreqtradeBot(LoggingMixin): strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)() - if self.replicate_controller: - if not self.replicate_controller.is_leader(): + if self.external_signal_controller: + if not self.external_signal_controller.is_leader(): # Run Follower mode analyzing leader_pairs = self.pairlists._whitelist self.strategy.analyze_external(self.active_pair_whitelist, leader_pairs) @@ -281,16 +278,14 @@ class FreqtradeBot(LoggingMixin): self.pairlists.refresh_pairlist() _whitelist = self.pairlists.whitelist - # If replicate leader, broadcast whitelist data - # Should we broadcast before trade pairs are added? What if - # the follower doesn't have trades with those pairs. They would be added for - # no reason. + # If external signal leader, broadcast whitelist data + # Should we broadcast before trade pairs are added? # Or should this class be made available to the PairListManager and ran # when filter_pairlist is called? - if self.replicate_controller: - if self.replicate_controller.is_leader(): + if self.external_signal_controller: + if self.external_signal_controller.is_leader(): self.rpc.emit_data({ "data_type": LeaderMessageType.pairlist, "data": _whitelist diff --git a/freqtrade/plugins/pairlist/ExternalPairList.py b/freqtrade/plugins/pairlist/ExternalPairList.py index 40e3f9a7f..27a328060 100644 --- a/freqtrade/plugins/pairlist/ExternalPairList.py +++ b/freqtrade/plugins/pairlist/ExternalPairList.py @@ -14,7 +14,7 @@ logger = logging.getLogger(__name__) class ExternalPairList(IPairList): """ - PairList plugin for use with replicate follower mode. + PairList plugin for use with external signal follower mode. Will use pairs given from leader data. Usage: @@ -67,6 +67,8 @@ class ExternalPairList(IPairList): def add_pairlist_data(self, pairlist: List[str]): """ Add pairs from Leader + + :param pairlist: List of pairs """ # If some pairs were removed on Leader, remove them here diff --git a/freqtrade/rpc/external_signal/__init__.py b/freqtrade/rpc/external_signal/__init__.py new file mode 100644 index 000000000..c1b05b3f0 --- /dev/null +++ b/freqtrade/rpc/external_signal/__init__.py @@ -0,0 +1,5 @@ +# flake8: noqa: F401 +from freqtrade.rpc.external_signal.controller import ExternalSignalController + + +__all__ = ('ExternalSignalController') diff --git a/freqtrade/rpc/replicate/channel.py b/freqtrade/rpc/external_signal/channel.py similarity index 94% rename from freqtrade/rpc/replicate/channel.py rename to freqtrade/rpc/external_signal/channel.py index 62ed3e025..585b6bae5 100644 --- a/freqtrade/rpc/replicate/channel.py +++ b/freqtrade/rpc/external_signal/channel.py @@ -1,9 +1,9 @@ import logging from typing import Type -from freqtrade.rpc.replicate.proxy import WebSocketProxy -from freqtrade.rpc.replicate.serializer import MsgPackWebSocketSerializer, WebSocketSerializer -from freqtrade.rpc.replicate.types import WebSocketType +from freqtrade.rpc.external_signal.proxy import WebSocketProxy +from freqtrade.rpc.external_signal.serializer import MsgPackWebSocketSerializer, WebSocketSerializer +from freqtrade.rpc.external_signal.types import WebSocketType logger = logging.getLogger(__name__) diff --git a/freqtrade/rpc/replicate/__init__.py b/freqtrade/rpc/external_signal/controller.py similarity index 74% rename from freqtrade/rpc/replicate/__init__.py rename to freqtrade/rpc/external_signal/controller.py index 5cc2ae6a9..af91a67b7 100644 --- a/freqtrade/rpc/replicate/__init__.py +++ b/freqtrade/rpc/external_signal/controller.py @@ -5,8 +5,7 @@ import asyncio import logging import secrets import socket -import traceback -from threading import Event, Thread +from threading import Thread from typing import Any, Coroutine, Dict, Union import websockets @@ -14,18 +13,18 @@ from fastapi import Depends from fastapi import WebSocket as FastAPIWebSocket from fastapi import WebSocketDisconnect, status -from freqtrade.enums import LeaderMessageType, ReplicateModeType, RPCMessageType +from freqtrade.enums import ExternalSignalModeType, LeaderMessageType, RPCMessageType from freqtrade.rpc import RPC, RPCHandler -from freqtrade.rpc.replicate.channel import ChannelManager -from freqtrade.rpc.replicate.thread_queue import Queue as ThreadedQueue -from freqtrade.rpc.replicate.types import MessageType -from freqtrade.rpc.replicate.utils import is_websocket_alive +from freqtrade.rpc.external_signal.channel import ChannelManager +from freqtrade.rpc.external_signal.thread_queue import Queue as ThreadedQueue +from freqtrade.rpc.external_signal.types import MessageType +from freqtrade.rpc.external_signal.utils import is_websocket_alive logger = logging.getLogger(__name__) -class ReplicateController(RPCHandler): +class ExternalSignalController(RPCHandler): """ This class handles all websocket communication """ def __init__( @@ -35,9 +34,10 @@ class ReplicateController(RPCHandler): api_server: Union[Any, None] = None ) -> None: """ - Init the ReplicateRPC class, and init the super class RPCHandler + Init the ExternalSignalController class, and init the super class RPCHandler :param rpc: instance of RPC Helper class :param config: Configuration object + :param api_server: The ApiServer object :return: None """ super().__init__(rpc, config) @@ -46,48 +46,50 @@ class ReplicateController(RPCHandler): self.api_server = api_server if not self.api_server: - raise RuntimeError("The API server must be enabled for replicate to work") + raise RuntimeError("The API server must be enabled for external signals to work") self._loop = None self._running = False self._thread = None self._queue = None - self._stop_event = Event() - self._follower_tasks = None + self._main_task = None + self._sub_tasks = None self.channel_manager = ChannelManager() - self.replicate_config = config.get('replicate', {}) + self.external_signal_config = config.get('external_signal', {}) # What the config should look like - # "replicate": { + # "external_signal": { # "enabled": true, # "mode": "follower", # "leaders": [ # { - # "url": "ws://localhost:8080/replicate/ws", - # "token": "test" + # "url": "ws://localhost:8080/signals/ws", + # "api_token": "test" # } # ] # } - # "replicate": { + # "external_signal": { # "enabled": true, # "mode": "leader", - # "api_key": "test" + # "api_token": "test" # } - self.mode = ReplicateModeType[self.replicate_config.get('mode', 'leader').lower()] + self.mode = ExternalSignalModeType[ + self.external_signal_config.get('mode', 'leader').lower() + ] - self.leaders_list = self.replicate_config.get('leaders', []) - self.push_throttle_secs = self.replicate_config.get('push_throttle_secs', 0.1) + self.leaders_list = self.external_signal_config.get('leaders', []) + self.push_throttle_secs = self.external_signal_config.get('push_throttle_secs', 0.1) - self.reply_timeout = self.replicate_config.get('follower_reply_timeout', 10) - self.ping_timeout = self.replicate_config.get('follower_ping_timeout', 2) - self.sleep_time = self.replicate_config.get('follower_sleep_time', 5) + self.reply_timeout = self.external_signal_config.get('follower_reply_timeout', 10) + self.ping_timeout = self.external_signal_config.get('follower_ping_timeout', 2) + self.sleep_time = self.external_signal_config.get('follower_sleep_time', 5) - if self.mode == ReplicateModeType.follower and len(self.leaders_list) == 0: + if self.mode == ExternalSignalModeType.follower and len(self.leaders_list) == 0: raise ValueError("You must specify at least 1 leader in follower mode.") # This is only used by the leader, the followers use the tokens specified @@ -95,12 +97,23 @@ class ReplicateController(RPCHandler): # If you do not specify an API key in the config, one will be randomly # generated and logged on startup default_api_key = secrets.token_urlsafe(16) - self.secret_api_key = self.replicate_config.get('api_key', default_api_key) + self.secret_api_key = self.external_signal_config.get('api_token', default_api_key) self.start_threaded_loop() - self.start() + def is_leader(self): + """ + Leader flag + """ + return self.enabled() and self.mode == ExternalSignalModeType.leader + + def enabled(self): + """ + Enabled flag + """ + return self.external_signal_config.get('enabled', False) + def start_threaded_loop(self): """ Start the main internal loop in another thread to run coroutines @@ -125,36 +138,29 @@ class ReplicateController(RPCHandler): raise RuntimeError("Loop must be started before any function can" " be submitted") - try: - return asyncio.run_coroutine_threadsafe(coroutine, self._loop) - except Exception as e: - logger.error(f"Error running coroutine - {str(e)}") - return None - - async def main_loop(self): - """ - Main loop coro - - Start the loop based on what mode we're in - """ - try: - if self.mode == ReplicateModeType.leader: - await self.leader_loop() - elif self.mode == ReplicateModeType.follower: - await self.follower_loop() - - except asyncio.CancelledError: - pass - except Exception: - pass - finally: - self._loop.stop() + return asyncio.run_coroutine_threadsafe(coroutine, self._loop) def start(self): """ Start the controller main loop """ - self.submit_coroutine(self.main_loop()) + self._main_task = self.submit_coroutine(self.main()) + + async def shutdown(self): + """ + Shutdown all tasks and close up + """ + logger.info("Stopping rpc.externalsignalcontroller") + + # Flip running flag + self._running = False + + # Cancel sub tasks + for task in self._sub_tasks: + task.cancel() + + # Then disconnect all channels + await self.channel_manager.disconnect_all() def cleanup(self) -> None: """ @@ -162,18 +168,44 @@ class ReplicateController(RPCHandler): """ if self._thread: if self._loop.is_running(): - - self._running = False - - # Tell all coroutines submitted to the loop they're cancelled - pending = asyncio.all_tasks(loop=self._loop) - for task in pending: - task.cancel() - - self._loop.call_soon_threadsafe(self.channel_manager.disconnect_all) - + self._main_task.cancel() self._thread.join() + async def main(self): + """ + Main coro + + Start the loop based on what mode we're in + """ + try: + if self.mode == ExternalSignalModeType.leader: + logger.info("Starting rpc.externalsignalcontroller in Leader mode") + + await self.run_leader_mode() + elif self.mode == ExternalSignalModeType.follower: + logger.info("Starting rpc.externalsignalcontroller in Follower mode") + + await self.run_follower_mode() + + except asyncio.CancelledError: + # We're cancelled + await self.shutdown() + except Exception as e: + # Log the error + logger.error(f"Exception occurred in main task: {e}") + logger.exception(e) + finally: + # This coroutine is the last thing to be ended, so it should stop the loop + self._loop.stop() + + def log_api_token(self): + """ + Log the API token + """ + logger.info("-" * 15) + logger.info(f"API_KEY: {self.secret_api_key}") + logger.info("-" * 15) + def send_msg(self, msg: MessageType) -> None: """ Support RPC calls @@ -186,7 +218,9 @@ class ReplicateController(RPCHandler): logger.error(f"Message is empty! {msg}") def send_message(self, msg: MessageType) -> None: - """ Broadcast message over all channels if there are any """ + """ + Broadcast message over all channels if there are any + """ if self.channel_manager.has_channels(): self._send_message(msg) @@ -205,39 +239,60 @@ class ReplicateController(RPCHandler): else: logger.warning("Can not send data, leader loop has not started yet!") - def is_leader(self): - """ - Leader flag - """ - return self.enabled() and self.mode == ReplicateModeType.leader + async def send_initial_data(self, channel): + logger.info("Sending initial data through channel") - def enabled(self): - """ - Enabled flag - """ - return self.replicate_config.get('enabled', False) + # We first send pairlist data + # We should move this to a func in the RPC object + initial_data = { + "data_type": LeaderMessageType.pairlist, + "data": self.freqtrade.pairlists.whitelist + } - # ----------------------- LEADER LOGIC ------------------------------ + await channel.send(initial_data) - async def leader_loop(self): + async def _handle_leader_message(self, message: MessageType): + """ + Handle message received from a Leader + """ + type = message.get("data_type") + data = message.get("data") + + self._rpc._handle_emitted_data(type, data) + + # ---------------------------------------------------------------------- + + async def run_leader_mode(self): """ Main leader coroutine This starts all of the leader coros and registers the endpoint on the ApiServer """ - logger.info("Running rpc.replicate in Leader mode") - logger.info("-" * 15) - logger.info(f"API_KEY: {self.secret_api_key}") - logger.info("-" * 15) - self.register_leader_endpoint() + self.log_api_token() - try: - await self._broadcast_queue_data() - except Exception as e: - logger.error("Exception occurred in Leader loop: ") - logger.exception(e) + self._sub_tasks = [ + self._loop.create_task(self._broadcast_queue_data()) + ] + + return await asyncio.gather(*self._sub_tasks) + + async def run_follower_mode(self): + """ + Main follower coroutine + + This starts all of the follower connection coros + """ + + rpc_lock = asyncio.Lock() + + self._sub_tasks = [ + self._loop.create_task(self._handle_leader_connection(leader, rpc_lock)) + for leader in self.leaders_list + ] + + return await asyncio.gather(*self._sub_tasks) async def _broadcast_queue_data(self): """ @@ -261,8 +316,6 @@ class ReplicateController(RPCHandler): except asyncio.CancelledError: # Silently stop pass - except Exception as e: - logger.exception(e) async def get_api_token( self, @@ -279,7 +332,7 @@ class ReplicateController(RPCHandler): logger.info("Denying websocket request...") await websocket.close(code=status.WS_1008_POLICY_VIOLATION) - def register_leader_endpoint(self, path: str = "/replicate/ws"): + def register_leader_endpoint(self, path: str = "/signals/ws"): """ Attach and start the main leader loop to the ApiServer @@ -334,73 +387,16 @@ class ReplicateController(RPCHandler): logger.error(f"Failed to serve - {websocket.client}") await self.channel_manager.on_disconnect(websocket) - async def send_initial_data(self, channel): - logger.info("Sending initial data through channel") - - # We first send pairlist data - initial_data = { - "data_type": LeaderMessageType.pairlist, - "data": self.freqtrade.pairlists.whitelist - } - - await channel.send(initial_data) - - # -------------------------------FOLLOWER LOGIC---------------------------- - - async def follower_loop(self): - """ - Main follower coroutine - - This starts all of the follower connection coros - """ - logger.info("Starting rpc.replicate in Follower mode") - - responses = await self._connect_to_leaders() - - # Eventually add the ability to send requests to the Leader - # await self._send_requests() - - for result in responses: - if isinstance(result, Exception): - logger.debug(f"Exception in Follower loop: {result}") - traceback_message = ''.join(traceback.format_tb(result.__traceback__)) - logger.error(traceback_message) - - async def _handle_leader_message(self, message: MessageType): - """ - Handle message received from a Leader - """ - type = message.get("data_type") - data = message.get("data") - - self._rpc._handle_emitted_data(type, data) - - async def _connect_to_leaders(self): - """ - For each leader in `self.leaders_list` create a connection and - listen for data. - """ - rpc_lock = asyncio.Lock() - - logger.info("Starting connections to Leaders...") - - self.follower_tasks = [ - self._loop.create_task(self._handle_leader_connection(leader, rpc_lock)) - for leader in self.leaders_list - ] - return await asyncio.gather(*self.follower_tasks, return_exceptions=True) - async def _handle_leader_connection(self, leader, lock): """ Given a leader, connect and wait on data. If connection is lost, it will attempt to reconnect. """ try: - url, token = leader["url"], leader["token"] + url, token = leader["url"], leader["api_token"] websocket_url = f"{url}?token={token}" logger.info(f"Attempting to connect to Leader at: {url}") - # TODO: limit the amount of connection retries while True: try: async with websockets.connect(websocket_url) as ws: diff --git a/freqtrade/rpc/replicate/proxy.py b/freqtrade/rpc/external_signal/proxy.py similarity index 96% rename from freqtrade/rpc/replicate/proxy.py rename to freqtrade/rpc/external_signal/proxy.py index aae536b6d..36ff4a74e 100644 --- a/freqtrade/rpc/replicate/proxy.py +++ b/freqtrade/rpc/external_signal/proxy.py @@ -3,7 +3,7 @@ from typing import Union from fastapi import WebSocket as FastAPIWebSocket from websockets import WebSocketClientProtocol as WebSocket -from freqtrade.rpc.replicate.types import WebSocketType +from freqtrade.rpc.external_signal.types import WebSocketType class WebSocketProxy: diff --git a/freqtrade/rpc/replicate/serializer.py b/freqtrade/rpc/external_signal/serializer.py similarity index 96% rename from freqtrade/rpc/replicate/serializer.py rename to freqtrade/rpc/external_signal/serializer.py index 98bdc8934..2a0f53037 100644 --- a/freqtrade/rpc/replicate/serializer.py +++ b/freqtrade/rpc/external_signal/serializer.py @@ -5,7 +5,7 @@ from abc import ABC, abstractmethod import msgpack import orjson -from freqtrade.rpc.replicate.proxy import WebSocketProxy +from freqtrade.rpc.external_signal.proxy import WebSocketProxy logger = logging.getLogger(__name__) diff --git a/freqtrade/rpc/replicate/thread_queue.py b/freqtrade/rpc/external_signal/thread_queue.py similarity index 100% rename from freqtrade/rpc/replicate/thread_queue.py rename to freqtrade/rpc/external_signal/thread_queue.py diff --git a/freqtrade/rpc/replicate/types.py b/freqtrade/rpc/external_signal/types.py similarity index 100% rename from freqtrade/rpc/replicate/types.py rename to freqtrade/rpc/external_signal/types.py diff --git a/freqtrade/rpc/replicate/utils.py b/freqtrade/rpc/external_signal/utils.py similarity index 100% rename from freqtrade/rpc/replicate/utils.py rename to freqtrade/rpc/external_signal/utils.py diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 2c7b2ec72..68871a15a 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -1109,16 +1109,22 @@ class RPC: external_pairlist.add_pairlist_data(pairlist) elif type == LeaderMessageType.analyzed_df: + # Convert the dataframe back from json key, value = data["key"], data["value"] pair, timeframe, candle_type = key - dataframe = json_to_dataframe(value) - dataprovider = self._freqtrade.dataprovider + # Skip any pairs that we don't have in the pairlist? + # leader_pairlist = self._freqtrade.pairlists._whitelist + # if pair not in leader_pairlist: + # return + + dataframe = json_to_dataframe(value) logger.debug(f"Received analyzed dataframe for {pair}") logger.debug(dataframe.tail()) # Add the dataframe to the dataprovider + dataprovider = self._freqtrade.dataprovider dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 3d561cc8e..0a0e285a4 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -54,14 +54,14 @@ class RPCManager: # Enable Replicate mode # For this to be enabled, the API server must also be enabled - if config.get('replicate', {}).get('enabled', False): - logger.info('Enabling rpc.replicate') - from freqtrade.rpc.replicate import ReplicateController - replicate_rpc = ReplicateController(self._rpc, config, apiserver) - self.registered_modules.append(replicate_rpc) + if config.get('external_signal', {}).get('enabled', False): + logger.info('Enabling RPC.ExternalSignalController') + from freqtrade.rpc.external_signal import ExternalSignalController + external_signal_rpc = ExternalSignalController(self._rpc, config, apiserver) + self.registered_modules.append(external_signal_rpc) # Attach the controller to FreqTrade - freqtrade.replicate_controller = replicate_rpc + freqtrade.external_signal_controller = external_signal_rpc apiserver.start_api() diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index 1084838ec..22a10b4d3 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -18,7 +18,6 @@ from freqtrade.enums.runmode import RunMode from freqtrade.exceptions import OperationalException, StrategyError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date, timeframe_to_seconds from freqtrade.persistence import Order, PairLocks, Trade -from freqtrade.rpc.replicate import ReplicateController from freqtrade.strategy.hyper import HyperStrategyMixin from freqtrade.strategy.informative_decorator import (InformativeData, PopulateIndicators, _create_and_merge_informative_pair, @@ -111,7 +110,6 @@ class IStrategy(ABC, HyperStrategyMixin): # the dataprovider (dp) (access to other candles, historic data, ...) # and wallets - access to the current balance. dp: DataProvider - replicate_controller: Optional[ReplicateController] wallets: Optional[Wallets] = None # Filled from configuration stake_currency: str @@ -764,7 +762,7 @@ class IStrategy(ABC, HyperStrategyMixin): if not external_data: dataframe = self.dp.ohlcv(pair, self.timeframe, candle_type) else: - dataframe, last_analyzed = self.dp.get_external_df(pair, self.timeframe, candle_type) + dataframe, _ = self.dp.get_external_df(pair, self.timeframe, candle_type) if not isinstance(dataframe, DataFrame) or dataframe.empty: logger.warning('Empty candle (OHLCV) data for pair %s', pair) From 3e786a9b8b791f06c1cf24e7af738ea29f23dc75 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 24 Aug 2022 22:44:22 -0600 Subject: [PATCH 008/115] added example configs --- .gitignore | 2 + config_examples/config_follower.example.json | 85 +++++++++++++++++ config_examples/config_leader.example.json | 97 ++++++++++++++++++++ 3 files changed, 184 insertions(+) create mode 100644 config_examples/config_follower.example.json create mode 100644 config_examples/config_leader.example.json diff --git a/.gitignore b/.gitignore index 015c0a8d9..b8c4c3846 100644 --- a/.gitignore +++ b/.gitignore @@ -113,6 +113,8 @@ target/ !config_examples/config_full.example.json !config_examples/config_kraken.example.json !config_examples/config_freqai.example.json +!config_examples/config_leader.example.json +!config_examples/config_follower.example.json *-config.json *.db* diff --git a/config_examples/config_follower.example.json b/config_examples/config_follower.example.json new file mode 100644 index 000000000..5317c8df2 --- /dev/null +++ b/config_examples/config_follower.example.json @@ -0,0 +1,85 @@ + +{ + "db_url": "sqlite:///follower.db", + "strategy": "SampleStrategy", + "max_open_trades": 3, + "stake_currency": "USDT", + "stake_amount": 100, + "tradable_balance_ratio": 0.99, + "fiat_display_currency": "USD", + "dry_run": true, + "cancel_open_orders_on_exit": false, + "trading_mode": "spot", + "margin_mode": "", + "unfilledtimeout": { + "entry": 10, + "exit": 10, + "exit_timeout_count": 0, + "unit": "minutes" + }, + "entry_pricing": { + "price_side": "same", + "use_order_book": true, + "order_book_top": 1, + "price_last_balance": 0.0, + "check_depth_of_market": { + "enabled": false, + "bids_to_ask_delta": 1 + } + }, + "exit_pricing":{ + "price_side": "same", + "use_order_book": true, + "order_book_top": 1 + }, + "exchange": { + "name": "kucoin", + "key": "", + "secret": "", + "password": "", + "ccxt_config": {}, + "ccxt_async_config": {}, + "pair_whitelist": [ + ], + "pair_blacklist": [ + ] + }, + "pairlists": [ + { + "method": "ExternalPairList", + "number_assets": 5, + } + ], + "telegram": { + "enabled": false, + "token": "", + "chat_id": "" + }, + "api_server": { + "enabled": true, + "listen_ip_address": "127.0.0.1", + "listen_port": 8081, + "verbosity": "error", + "enable_openapi": false, + "jwt_secret_key": "fcc24d31d6581ad2c90c3fc438c8a8b2ccce1393126959934568707f0bd2d647", + "CORS_origins": [], + "username": "freqtrader", + "password": "testing123" + }, + "external_signal": { + "enabled": true, + "mode": "follower", + "leaders": [ + { + "url": "ws://localhost:8080/signals/ws", + "api_token": "testtoken" + } + ] + }, + "bot_name": "freqtrade", + "initial_state": "running", + "force_entry_enable": false, + "internals": { + "process_throttle_secs": 5, + } +} diff --git a/config_examples/config_leader.example.json b/config_examples/config_leader.example.json new file mode 100644 index 000000000..5103fdbd4 --- /dev/null +++ b/config_examples/config_leader.example.json @@ -0,0 +1,97 @@ + +{ + "db_url": "sqlite:///leader.db", + "strategy": "SampleStrategy", + "max_open_trades": 3, + "stake_currency": "USDT", + "stake_amount": 100, + "tradable_balance_ratio": 0.99, + "fiat_display_currency": "USD", + "dry_run": true, + "cancel_open_orders_on_exit": false, + "trading_mode": "spot", + "margin_mode": "", + "unfilledtimeout": { + "entry": 10, + "exit": 10, + "exit_timeout_count": 0, + "unit": "minutes" + }, + "entry_pricing": { + "price_side": "same", + "use_order_book": true, + "order_book_top": 1, + "price_last_balance": 0.0, + "check_depth_of_market": { + "enabled": false, + "bids_to_ask_delta": 1 + } + }, + "exit_pricing":{ + "price_side": "same", + "use_order_book": true, + "order_book_top": 1 + }, + "exchange": { + "name": "kucoin", + "key": "", + "secret": "", + "password": "", + "ccxt_config": {}, + "ccxt_async_config": {}, + "pair_whitelist": [ + ], + "pair_blacklist": [ + ] + }, + "pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume", + "min_value": 0, + "refresh_period": 1800 + } + ], + "edge": { + "enabled": false, + "process_throttle_secs": 3600, + "calculate_since_number_of_days": 7, + "allowed_risk": 0.01, + "stoploss_range_min": -0.01, + "stoploss_range_max": -0.1, + "stoploss_range_step": -0.01, + "minimum_winrate": 0.60, + "minimum_expectancy": 0.20, + "min_trade_number": 10, + "max_trade_duration_minute": 1440, + "remove_pumps": false + }, + "telegram": { + "enabled": false, + "token": "", + "chat_id": "" + }, + "api_server": { + "enabled": true, + "listen_ip_address": "127.0.0.1", + "listen_port": 8080, + "verbosity": "error", + "enable_openapi": false, + "jwt_secret_key": "fcc24d31d6581ad2c90c3fc438c8a8b2ccce1393126959934568707f0bd2d647", + "CORS_origins": [], + "username": "freqtrader", + "password": "testing123" + }, + "external_signal": { + "enabled": true, + "mode": "leader", + "api_token": "testtoken", + }, + "bot_name": "freqtrade", + "initial_state": "running", + "force_entry_enable": false, + "internals": { + "process_throttle_secs": 5, + } +} From a998d6d7735a37b37259e988bf2ed17152891338 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 26 Aug 2022 14:52:15 -0600 Subject: [PATCH 009/115] fix tests --- tests/rpc/test_rpc_apiserver.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 9aa965da2..9a7bdfef6 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -52,6 +52,7 @@ def botclient(default_conf, mocker): try: apiserver = ApiServer(default_conf) apiserver.add_rpc_handler(rpc) + apiserver.start_api() yield ftbot, TestClient(apiserver.app) # Cleanup ... ? finally: @@ -332,6 +333,7 @@ def test_api_run(default_conf, mocker, caplog): apiserver = ApiServer(default_conf) apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf))) + apiserver.start_api() assert server_mock.call_count == 1 assert apiserver._config == default_conf apiserver.start_api() @@ -406,6 +408,7 @@ def test_api_cleanup(default_conf, mocker, caplog): apiserver = ApiServer(default_conf) apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf))) + apiserver.start_api() apiserver.cleanup() assert apiserver._server.cleanup.call_count == 1 From 2b5f0678772bea0abaf4abe93efc55de43ea3e0e Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 26 Aug 2022 23:40:13 -0600 Subject: [PATCH 010/115] Refactoring, minor improvements, data provider improvements --- freqtrade/constants.py | 6 + freqtrade/data/dataprovider.py | 106 ++++++++++++------ freqtrade/enums/__init__.py | 2 +- freqtrade/enums/externalsignal.py | 7 ++ freqtrade/freqtradebot.py | 3 - freqtrade/misc.py | 17 +++ freqtrade/rpc/api_server/webserver.py | 1 + freqtrade/rpc/external_signal/channel.py | 40 ++++--- freqtrade/rpc/external_signal/controller.py | 34 ++++-- freqtrade/rpc/external_signal/utils.py | 12 ++ freqtrade/rpc/rpc.py | 72 ++++++++---- freqtrade/rpc/rpc_manager.py | 13 +-- ...te.txt => requirements-externalsignals.txt | 1 + tests/rpc/test_rpc_apiserver.py | 2 - 14 files changed, 218 insertions(+), 98 deletions(-) rename requirements-replicate.txt => requirements-externalsignals.txt (94%) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index ad0758e22..b1f189093 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -62,6 +62,7 @@ TELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent'] WEBHOOK_FORMAT_OPTIONS = ['form', 'json', 'raw'] FOLLOWER_MODE_OPTIONS = ['follower', 'leader'] +WAIT_DATA_POLICY_OPTIONS = ['none', 'first', 'all'] ENV_VAR_PREFIX = 'FREQTRADE__' @@ -509,6 +510,11 @@ CONF_SCHEMA = { 'follower_reply_timeout': {'type': 'integer'}, 'follower_sleep_time': {'type': 'integer'}, 'follower_ping_timeout': {'type': 'integer'}, + 'wait_data_policy': { + 'type': 'string', + 'enum': WAIT_DATA_POLICY_OPTIONS + }, + 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False} }, 'required': ['mode'] }, diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 036005c84..cd70db9a3 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -15,7 +15,7 @@ from pandas import DataFrame from freqtrade.configuration import TimeRange from freqtrade.constants import ListPairsWithTimeframes, PairWithTimeframe from freqtrade.data.history import load_pair_history -from freqtrade.enums import CandleType, RunMode +from freqtrade.enums import CandleType, RunMode, WaitDataPolicy from freqtrade.exceptions import ExchangeError, OperationalException from freqtrade.exchange import Exchange, timeframe_to_seconds from freqtrade.util import PeriodicCache @@ -29,7 +29,12 @@ MAX_DATAFRAME_CANDLES = 1000 class DataProvider: - def __init__(self, config: dict, exchange: Optional[Exchange], pairlists=None) -> None: + def __init__( + self, + config: dict, + exchange: Optional[Exchange], + pairlists=None + ) -> None: self._config = config self._exchange = exchange self._pairlists = pairlists @@ -37,12 +42,18 @@ class DataProvider: self.__slice_index: Optional[int] = None self.__cached_pairs_backtesting: Dict[PairWithTimeframe, DataFrame] = {} self.__external_pairs_df: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {} - self.__external_pairs_event: Dict[str, Event] = {} + self.__external_pairs_event: Dict[PairWithTimeframe, Tuple[int, Event]] = {} self._msg_queue: deque = deque() self.__msg_cache = PeriodicCache( maxsize=1000, ttl=timeframe_to_seconds(self._config.get('timeframe', '1h'))) + self._num_sources = len(self._config.get('external_signal', {}).get('leader_list', [])) + self._wait_data_policy = self._config.get('external_signal', {}).get( + 'wait_data_policy', WaitDataPolicy.all) + self._wait_data_timeout = self._config.get( + 'external_signal', {}).get('wait_data_timeout', 5) + def _set_dataframe_max_index(self, limit_index: int): """ Limit analyzed dataframe to max specified index. @@ -75,57 +86,88 @@ class DataProvider: pair: str, timeframe: str, dataframe: DataFrame, - candle_type: CandleType + candle_type: CandleType, ) -> None: """ - Add the DataFrame to the __external_pairs_df. If a pair event exists, - set it to release the main thread from waiting. + Add the pair data to this class from an external source. + + :param pair: pair to get the data for + :param timeframe: Timeframe to get data for + :param candle_type: Any of the enum CandleType (must match trading mode!) """ pair_key = (pair, timeframe, candle_type) - # Delete stale data - if pair_key in self.__external_pairs_df: - del self.__external_pairs_df[pair_key] - + # For multiple leaders, if the data already exists, we'd merge self.__external_pairs_df[pair_key] = (dataframe, datetime.now(timezone.utc)) - - pair_event = self.__external_pairs_event.get(pair) - if pair_event: - logger.debug(f"Leader data for pair {pair_key} has been added") - pair_event.set() + self._set_data_event(pair_key) def get_external_df( self, pair: str, timeframe: str, - candle_type: CandleType, - wait: bool = True + candle_type: CandleType ) -> DataFrame: """ - If the pair exists in __external_pairs_df, return it. - If it doesn't, and wait is False, then return an empty df with the columns filled. - If it doesn't, and wait is True (default) create a new threading Event - in __external_pairs_event and wait on it. + Get the pair data from the external sources. Will wait if the policy is + set to, and data is not available. + + :param pair: pair to get the data for + :param timeframe: Timeframe to get data for + :param candle_type: Any of the enum CandleType (must match trading mode!) """ pair_key = (pair, timeframe, candle_type) if pair_key not in self.__external_pairs_df: - if wait: - pair_event = Event() - self.__external_pairs_event[pair] = pair_event + self._wait_on_data(pair_key) - logger.debug(f"Waiting on Leader data for: {pair_key}") - self.__external_pairs_event[pair].wait(timeout=5) - - if pair_key not in self.__external_pairs_df: - # Return empty dataframe but with expected columns merged and filled with NaN - return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) - else: - # Return empty dataframe but with expected columns merged and filled with NaN + if pair_key not in self.__external_pairs_df: return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) return self.__external_pairs_df[pair_key] + def _set_data_event(self, key: PairWithTimeframe): + """ + Depending on the WaitDataPolicy, if an event exists for this PairWithTimeframe + then set the event to release main thread from waiting. + + :param key: PairWithTimeframe + """ + pair_event = self.__external_pairs_event.get(key) + + if pair_event: + num_concat, event = pair_event + self.__external_pairs_event[key] = (num_concat + 1, event) + + if self._wait_data_policy == WaitDataPolicy.one: + logger.debug("Setting Data as policy is One") + event.set() + elif self._wait_data_policy == WaitDataPolicy.all and num_concat == self._num_sources: + logger.debug("Setting Data as policy is all, and is complete") + event.set() + + del self.__external_pairs_event[key] + + def _wait_on_data(self, key: PairWithTimeframe): + """ + Depending on the WaitDataPolicy, we will create and wait on an event until + set that determines the full amount of data is available + + :param key: PairWithTimeframe + """ + if self._wait_data_policy is not WaitDataPolicy.none: + pair, timeframe, candle_type = key + + pair_event = Event() + self.__external_pairs_event[key] = (0, pair_event) + + timeout = self._wait_data_timeout \ + if self._wait_data_policy is not WaitDataPolicy.all else 0 + + timeout_str = f"for {timeout} seconds" if timeout > 0 else "indefinitely" + logger.debug(f"Waiting for external data on {pair} for {timeout_str}") + + pair_event.wait(timeout=timeout) + def add_pairlisthandler(self, pairlists) -> None: """ Allow adding pairlisthandler after initialization diff --git a/freqtrade/enums/__init__.py b/freqtrade/enums/__init__.py index 913ef82dd..ffeb8cc12 100644 --- a/freqtrade/enums/__init__.py +++ b/freqtrade/enums/__init__.py @@ -3,7 +3,7 @@ from freqtrade.enums.backteststate import BacktestState from freqtrade.enums.candletype import CandleType from freqtrade.enums.exitchecktuple import ExitCheckTuple from freqtrade.enums.exittype import ExitType -from freqtrade.enums.externalsignal import ExternalSignalModeType, LeaderMessageType +from freqtrade.enums.externalsignal import ExternalSignalModeType, LeaderMessageType, WaitDataPolicy from freqtrade.enums.marginmode import MarginMode from freqtrade.enums.ordertypevalue import OrderTypeValues from freqtrade.enums.rpcmessagetype import RPCMessageType diff --git a/freqtrade/enums/externalsignal.py b/freqtrade/enums/externalsignal.py index 4695a4eab..05dc604a2 100644 --- a/freqtrade/enums/externalsignal.py +++ b/freqtrade/enums/externalsignal.py @@ -7,5 +7,12 @@ class ExternalSignalModeType(str, Enum): class LeaderMessageType(str, Enum): + default = "default" pairlist = "pairlist" analyzed_df = "analyzed_df" + + +class WaitDataPolicy(str, Enum): + none = "none" + one = "one" + all = "all" diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 9704b7e08..6aee3d104 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -281,9 +281,6 @@ class FreqtradeBot(LoggingMixin): # If external signal leader, broadcast whitelist data # Should we broadcast before trade pairs are added? - # Or should this class be made available to the PairListManager and ran - # when filter_pairlist is called? - if self.external_signal_controller: if self.external_signal_controller.is_leader(): self.rpc.emit_data({ diff --git a/freqtrade/misc.py b/freqtrade/misc.py index bc644a7ec..ceace4ed8 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -14,6 +14,7 @@ import pandas import rapidjson from freqtrade.constants import DECIMAL_PER_COIN_FALLBACK, DECIMALS_PER_COIN +from freqtrade.enums.signaltype import SignalTagType, SignalType logger = logging.getLogger(__name__) @@ -271,3 +272,19 @@ def json_to_dataframe(data: str) -> pandas.DataFrame: dataframe['date'] = pandas.to_datetime(dataframe['date'], unit='ms', utc=True) return dataframe + + +def remove_entry_exit_signals(dataframe: pandas.DataFrame): + """ + Remove Entry and Exit signals from a DataFrame + + :param dataframe: The DataFrame to remove signals from + """ + dataframe[SignalType.ENTER_LONG.value] = 0 + dataframe[SignalType.EXIT_LONG.value] = 0 + dataframe[SignalType.ENTER_SHORT.value] = 0 + dataframe[SignalType.EXIT_SHORT.value] = 0 + dataframe[SignalTagType.ENTER_TAG.value] = None + dataframe[SignalTagType.EXIT_TAG.value] = None + + return dataframe diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index c98fb9fd4..049e7dbc2 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -74,6 +74,7 @@ class ApiServer(RPCHandler): default_response_class=FTJSONResponse, ) self.configure_app(self.app, self._config) + self.start_api() def add_rpc_handler(self, rpc: RPC): """ diff --git a/freqtrade/rpc/external_signal/channel.py b/freqtrade/rpc/external_signal/channel.py index 585b6bae5..4ccb2d864 100644 --- a/freqtrade/rpc/external_signal/channel.py +++ b/freqtrade/rpc/external_signal/channel.py @@ -1,4 +1,5 @@ import logging +from threading import RLock from typing import Type from freqtrade.rpc.external_signal.proxy import WebSocketProxy @@ -63,6 +64,7 @@ class WebSocketChannel: class ChannelManager: def __init__(self): self.channels = dict() + self._lock = RLock() # Re-entrant Lock async def on_connect(self, websocket: WebSocketType): """ @@ -78,7 +80,9 @@ class ChannelManager: return ws_channel = WebSocketChannel(websocket) - self.channels[websocket] = ws_channel + + with self._lock: + self.channels[websocket] = ws_channel return ws_channel @@ -88,21 +92,26 @@ class ChannelManager: :param websocket: The WebSocket objet attached to the Channel """ - if websocket in self.channels.keys(): - channel = self.channels[websocket] + with self._lock: + channel = self.channels.get(websocket) + if channel: + logger.debug(f"Disconnecting channel - {channel}") - logger.debug(f"Disconnecting channel - {channel}") + if not channel.is_closed(): + await channel.close() - if not channel.is_closed(): - await channel.close() - del self.channels[websocket] + del self.channels[websocket] async def disconnect_all(self): """ Disconnect all Channels """ - for websocket in self.channels.keys(): - await self.on_disconnect(websocket) + with self._lock: + for websocket, channel in self.channels.items(): + if not channel.is_closed(): + await channel.close() + + self.channels = dict() async def broadcast(self, data): """ @@ -110,12 +119,13 @@ class ChannelManager: :param data: The data to send """ - for websocket, channel in self.channels.items(): - try: - await channel.send(data) - except RuntimeError: - # Handle cannot send after close cases - await self.on_disconnect(websocket) + with self._lock: + for websocket, channel in self.channels.items(): + try: + await channel.send(data) + except RuntimeError: + # Handle cannot send after close cases + await self.on_disconnect(websocket) async def send_direct(self, channel, data): """ diff --git a/freqtrade/rpc/external_signal/controller.py b/freqtrade/rpc/external_signal/controller.py index af91a67b7..01c15fc15 100644 --- a/freqtrade/rpc/external_signal/controller.py +++ b/freqtrade/rpc/external_signal/controller.py @@ -6,7 +6,7 @@ import logging import secrets import socket from threading import Thread -from typing import Any, Coroutine, Dict, Union +from typing import Any, Callable, Coroutine, Dict, Union import websockets from fastapi import Depends @@ -56,8 +56,13 @@ class ExternalSignalController(RPCHandler): self._main_task = None self._sub_tasks = None - self.channel_manager = ChannelManager() + self._message_handlers = { + LeaderMessageType.pairlist: self._rpc._handle_pairlist_message, + LeaderMessageType.analyzed_df: self._rpc._handle_analyzed_df_message, + LeaderMessageType.default: self._rpc._handle_default_message + } + self.channel_manager = ChannelManager() self.external_signal_config = config.get('external_signal', {}) # What the config should look like @@ -89,6 +94,8 @@ class ExternalSignalController(RPCHandler): self.ping_timeout = self.external_signal_config.get('follower_ping_timeout', 2) self.sleep_time = self.external_signal_config.get('follower_sleep_time', 5) + # Validate external_signal_config here? + if self.mode == ExternalSignalModeType.follower and len(self.leaders_list) == 0: raise ValueError("You must specify at least 1 leader in follower mode.") @@ -99,7 +106,6 @@ class ExternalSignalController(RPCHandler): default_api_key = secrets.token_urlsafe(16) self.secret_api_key = self.external_signal_config.get('api_token', default_api_key) - self.start_threaded_loop() self.start() def is_leader(self): @@ -114,6 +120,12 @@ class ExternalSignalController(RPCHandler): """ return self.external_signal_config.get('enabled', False) + def num_leaders(self): + """ + The number of leaders we should be connected to + """ + return len(self.leaders_list) + def start_threaded_loop(self): """ Start the main internal loop in another thread to run coroutines @@ -144,6 +156,7 @@ class ExternalSignalController(RPCHandler): """ Start the controller main loop """ + self.start_threaded_loop() self._main_task = self.submit_coroutine(self.main()) async def shutdown(self): @@ -242,23 +255,20 @@ class ExternalSignalController(RPCHandler): async def send_initial_data(self, channel): logger.info("Sending initial data through channel") - # We first send pairlist data - # We should move this to a func in the RPC object - initial_data = { - "data_type": LeaderMessageType.pairlist, - "data": self.freqtrade.pairlists.whitelist - } + data = self._rpc._initial_leader_data() - await channel.send(initial_data) + for message in data: + await channel.send(message) async def _handle_leader_message(self, message: MessageType): """ Handle message received from a Leader """ - type = message.get("data_type") + type = message.get("data_type", LeaderMessageType.default) data = message.get("data") - self._rpc._handle_emitted_data(type, data) + handler: Callable = self._message_handlers[type] + handler(type, data) # ---------------------------------------------------------------------- diff --git a/freqtrade/rpc/external_signal/utils.py b/freqtrade/rpc/external_signal/utils.py index 7b703810e..e5469dce3 100644 --- a/freqtrade/rpc/external_signal/utils.py +++ b/freqtrade/rpc/external_signal/utils.py @@ -1,5 +1,8 @@ +from pandas import DataFrame from starlette.websockets import WebSocket, WebSocketState +from freqtrade.enums.signaltype import SignalTagType, SignalType + async def is_websocket_alive(ws: WebSocket) -> bool: if ( @@ -8,3 +11,12 @@ async def is_websocket_alive(ws: WebSocket) -> bool: ): return True return False + + +def remove_entry_exit_signals(dataframe: DataFrame): + dataframe[SignalType.ENTER_LONG.value] = 0 + dataframe[SignalType.EXIT_LONG.value] = 0 + dataframe[SignalType.ENTER_SHORT.value] = 0 + dataframe[SignalType.EXIT_SHORT.value] = 0 + dataframe[SignalTagType.ENTER_TAG.value] = None + dataframe[SignalTagType.EXIT_TAG.value] = None diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 68871a15a..82d50f33c 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -24,7 +24,8 @@ from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, LeaderMessage from freqtrade.exceptions import ExchangeError, PricingError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs from freqtrade.loggers import bufferHandler -from freqtrade.misc import decimals_per_coin, json_to_dataframe, shorten_date +from freqtrade.misc import (decimals_per_coin, json_to_dataframe, remove_entry_exit_signals, + shorten_date) from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence.models import PairLock from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist @@ -1090,41 +1091,64 @@ class RPC: 'last_process_ts': int(last_p.timestamp()), } - def _handle_emitted_data(self, type, data): + # ------------------------------ EXTERNAL SIGNALS ----------------------- + + def _initial_leader_data(self): + # We create a list of Messages to send to the follower on connect + data = [] + + # Send Pairlist data + data.append({ + "data_type": LeaderMessageType.pairlist, + "data": self._freqtrade.pairlists._whitelist + }) + + return data + + def _handle_pairlist_message(self, type, data): """ - Handles the emitted data from the Leaders + Handles the emitted pairlists from the Leaders :param type: The data_type of the data :param data: The data """ - logger.debug(f"Handling emitted data of type ({type})") + pairlist = data - if type == LeaderMessageType.pairlist: - pairlist = data + logger.debug(f"Handling Pairlist message: {pairlist}") - logger.debug(pairlist) + external_pairlist = self._freqtrade.pairlists._pairlist_handlers[0] + external_pairlist.add_pairlist_data(pairlist) - # Add the pairlist data to the ExternalPairList object - external_pairlist = self._freqtrade.pairlists._pairlist_handlers[0] - external_pairlist.add_pairlist_data(pairlist) + def _handle_analyzed_df_message(self, type, data): + """ + Handles the analyzed dataframes from the Leaders - elif type == LeaderMessageType.analyzed_df: + :param type: The data_type of the data + :param data: The data + """ + key, value = data["key"], data["value"] + pair, timeframe, candle_type = key - # Convert the dataframe back from json - key, value = data["key"], data["value"] + # Skip any pairs that we don't have in the pairlist? + # leader_pairlist = self._freqtrade.pairlists._whitelist + # if pair not in leader_pairlist: + # return - pair, timeframe, candle_type = key + dataframe = json_to_dataframe(value) - # Skip any pairs that we don't have in the pairlist? - # leader_pairlist = self._freqtrade.pairlists._whitelist - # if pair not in leader_pairlist: - # return + if self._config.get('external_signal', {}).get('remove_signals_analyzed_df', False): + dataframe = remove_entry_exit_signals(dataframe) - dataframe = json_to_dataframe(value) + logger.debug(f"Handling analyzed dataframe for {pair}") + logger.debug(dataframe.tail()) - logger.debug(f"Received analyzed dataframe for {pair}") - logger.debug(dataframe.tail()) + # Add the dataframe to the dataprovider + dataprovider = self._freqtrade.dataprovider + dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) - # Add the dataframe to the dataprovider - dataprovider = self._freqtrade.dataprovider - dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) + def _handle_default_message(self, type, data): + """ + Default leader message handler, just logs it. We should never have to + run this unless the leader sends us some weird message. + """ + logger.debug(f"Received message from Leader of type {type}: {data}") diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 0a0e285a4..11e21da6f 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -45,25 +45,20 @@ class RPCManager: if config.get('api_server', {}).get('enabled', False): logger.info('Enabling rpc.api_server') from freqtrade.rpc.api_server import ApiServer - - # Pass replicate_rpc as param or defer starting api_server - # until we register the replicate rpc enpoint? apiserver = ApiServer(config) apiserver.add_rpc_handler(self._rpc) self.registered_modules.append(apiserver) - # Enable Replicate mode + # Enable External Signals mode # For this to be enabled, the API server must also be enabled if config.get('external_signal', {}).get('enabled', False): logger.info('Enabling RPC.ExternalSignalController') from freqtrade.rpc.external_signal import ExternalSignalController - external_signal_rpc = ExternalSignalController(self._rpc, config, apiserver) - self.registered_modules.append(external_signal_rpc) + external_signals = ExternalSignalController(self._rpc, config, apiserver) + self.registered_modules.append(external_signals) # Attach the controller to FreqTrade - freqtrade.external_signal_controller = external_signal_rpc - - apiserver.start_api() + freqtrade.external_signal_controller = external_signals def cleanup(self) -> None: """ Stops all enabled rpc modules """ diff --git a/requirements-replicate.txt b/requirements-externalsignals.txt similarity index 94% rename from requirements-replicate.txt rename to requirements-externalsignals.txt index 2c994ea2f..7920b34f6 100644 --- a/requirements-replicate.txt +++ b/requirements-externalsignals.txt @@ -4,3 +4,4 @@ # Required for follower websockets msgpack +janus diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 9a7bdfef6..af9f9d248 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -52,7 +52,6 @@ def botclient(default_conf, mocker): try: apiserver = ApiServer(default_conf) apiserver.add_rpc_handler(rpc) - apiserver.start_api() yield ftbot, TestClient(apiserver.app) # Cleanup ... ? finally: @@ -333,7 +332,6 @@ def test_api_run(default_conf, mocker, caplog): apiserver = ApiServer(default_conf) apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf))) - apiserver.start_api() assert server_mock.call_count == 1 assert apiserver._config == default_conf apiserver.start_api() From fcceb744c5b0362464b59c13fb462291f4a977bb Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 26 Aug 2022 23:43:05 -0600 Subject: [PATCH 011/115] Add janus to requirements.txt --- freqtrade/rpc/external_signal/controller.py | 2 +- freqtrade/rpc/external_signal/thread_queue.py | 650 ------------------ 2 files changed, 1 insertion(+), 651 deletions(-) delete mode 100644 freqtrade/rpc/external_signal/thread_queue.py diff --git a/freqtrade/rpc/external_signal/controller.py b/freqtrade/rpc/external_signal/controller.py index 01c15fc15..0d43b0b2d 100644 --- a/freqtrade/rpc/external_signal/controller.py +++ b/freqtrade/rpc/external_signal/controller.py @@ -12,11 +12,11 @@ import websockets from fastapi import Depends from fastapi import WebSocket as FastAPIWebSocket from fastapi import WebSocketDisconnect, status +from janus import Queue as ThreadedQueue from freqtrade.enums import ExternalSignalModeType, LeaderMessageType, RPCMessageType from freqtrade.rpc import RPC, RPCHandler from freqtrade.rpc.external_signal.channel import ChannelManager -from freqtrade.rpc.external_signal.thread_queue import Queue as ThreadedQueue from freqtrade.rpc.external_signal.types import MessageType from freqtrade.rpc.external_signal.utils import is_websocket_alive diff --git a/freqtrade/rpc/external_signal/thread_queue.py b/freqtrade/rpc/external_signal/thread_queue.py deleted file mode 100644 index 88321321b..000000000 --- a/freqtrade/rpc/external_signal/thread_queue.py +++ /dev/null @@ -1,650 +0,0 @@ -import asyncio -import sys -import threading -from asyncio import QueueEmpty as AsyncQueueEmpty -from asyncio import QueueFull as AsyncQueueFull -from collections import deque -from heapq import heappop, heappush -from queue import Empty as SyncQueueEmpty -from queue import Full as SyncQueueFull -from typing import Any, Callable, Deque, Generic, List, Optional, Set, TypeVar - -from typing_extensions import Protocol - - -__version__ = "1.0.0" -__all__ = ( - "Queue", - "PriorityQueue", - "LifoQueue", - "SyncQueue", - "AsyncQueue", - "BaseQueue", -) - - -T = TypeVar("T") -OptFloat = Optional[float] - - -class BaseQueue(Protocol[T]): - @property - def maxsize(self) -> int: - ... - - @property - def closed(self) -> bool: - ... - - def task_done(self) -> None: - ... - - def qsize(self) -> int: - ... - - @property - def unfinished_tasks(self) -> int: - ... - - def empty(self) -> bool: - ... - - def full(self) -> bool: - ... - - def put_nowait(self, item: T) -> None: - ... - - def get_nowait(self) -> T: - ... - - -class SyncQueue(BaseQueue[T], Protocol[T]): - @property - def maxsize(self) -> int: - ... - - @property - def closed(self) -> bool: - ... - - def task_done(self) -> None: - ... - - def qsize(self) -> int: - ... - - @property - def unfinished_tasks(self) -> int: - ... - - def empty(self) -> bool: - ... - - def full(self) -> bool: - ... - - def put_nowait(self, item: T) -> None: - ... - - def get_nowait(self) -> T: - ... - - def put(self, item: T, block: bool = True, timeout: OptFloat = None) -> None: - ... - - def get(self, block: bool = True, timeout: OptFloat = None) -> T: - ... - - def join(self) -> None: - ... - - -class AsyncQueue(BaseQueue[T], Protocol[T]): - async def put(self, item: T) -> None: - ... - - async def get(self) -> T: - ... - - async def join(self) -> None: - ... - - -class Queue(Generic[T]): - def __init__(self, maxsize: int = 0) -> None: - self._loop = asyncio.get_running_loop() - self._maxsize = maxsize - - self._init(maxsize) - - self._unfinished_tasks = 0 - - self._sync_mutex = threading.Lock() - self._sync_not_empty = threading.Condition(self._sync_mutex) - self._sync_not_full = threading.Condition(self._sync_mutex) - self._all_tasks_done = threading.Condition(self._sync_mutex) - - self._async_mutex = asyncio.Lock() - if sys.version_info[:3] == (3, 10, 0): - # Workaround for Python 3.10 bug, see #358: - getattr(self._async_mutex, "_get_loop", lambda: None)() - self._async_not_empty = asyncio.Condition(self._async_mutex) - self._async_not_full = asyncio.Condition(self._async_mutex) - self._finished = asyncio.Event() - self._finished.set() - - self._closing = False - self._pending = set() # type: Set[asyncio.Future[Any]] - - def checked_call_soon_threadsafe( - callback: Callable[..., None], *args: Any - ) -> None: - try: - self._loop.call_soon_threadsafe(callback, *args) - except RuntimeError: - # swallowing agreed in #2 - pass - - self._call_soon_threadsafe = checked_call_soon_threadsafe - - def checked_call_soon(callback: Callable[..., None], *args: Any) -> None: - if not self._loop.is_closed(): - self._loop.call_soon(callback, *args) - - self._call_soon = checked_call_soon - - self._sync_queue = _SyncQueueProxy(self) - self._async_queue = _AsyncQueueProxy(self) - - def close(self) -> None: - with self._sync_mutex: - self._closing = True - for fut in self._pending: - fut.cancel() - self._finished.set() # unblocks all async_q.join() - self._all_tasks_done.notify_all() # unblocks all sync_q.join() - - async def wait_closed(self) -> None: - # should be called from loop after close(). - # Nobody should put/get at this point, - # so lock acquiring is not required - if not self._closing: - raise RuntimeError("Waiting for non-closed queue") - # give execution chances for the task-done callbacks - # of async tasks created inside - # _notify_async_not_empty, _notify_async_not_full - # methods. - await asyncio.sleep(0) - if not self._pending: - return - await asyncio.wait(self._pending) - - @property - def closed(self) -> bool: - return self._closing and not self._pending - - @property - def maxsize(self) -> int: - return self._maxsize - - @property - def sync_q(self) -> "_SyncQueueProxy[T]": - return self._sync_queue - - @property - def async_q(self) -> "_AsyncQueueProxy[T]": - return self._async_queue - - # Override these methods to implement other queue organizations - # (e.g. stack or priority queue). - # These will only be called with appropriate locks held - - def _init(self, maxsize: int) -> None: - self._queue = deque() # type: Deque[T] - - def _qsize(self) -> int: - return len(self._queue) - - # Put a new item in the queue - def _put(self, item: T) -> None: - self._queue.append(item) - - # Get an item from the queue - def _get(self) -> T: - return self._queue.popleft() - - def _put_internal(self, item: T) -> None: - self._put(item) - self._unfinished_tasks += 1 - self._finished.clear() - - def _notify_sync_not_empty(self) -> None: - def f() -> None: - with self._sync_mutex: - self._sync_not_empty.notify() - - self._loop.run_in_executor(None, f) - - def _notify_sync_not_full(self) -> None: - def f() -> None: - with self._sync_mutex: - self._sync_not_full.notify() - - fut = asyncio.ensure_future(self._loop.run_in_executor(None, f)) - fut.add_done_callback(self._pending.discard) - self._pending.add(fut) - - def _notify_async_not_empty(self, *, threadsafe: bool) -> None: - async def f() -> None: - async with self._async_mutex: - self._async_not_empty.notify() - - def task_maker() -> None: - task = self._loop.create_task(f()) - task.add_done_callback(self._pending.discard) - self._pending.add(task) - - if threadsafe: - self._call_soon_threadsafe(task_maker) - else: - self._call_soon(task_maker) - - def _notify_async_not_full(self, *, threadsafe: bool) -> None: - async def f() -> None: - async with self._async_mutex: - self._async_not_full.notify() - - def task_maker() -> None: - task = self._loop.create_task(f()) - task.add_done_callback(self._pending.discard) - self._pending.add(task) - - if threadsafe: - self._call_soon_threadsafe(task_maker) - else: - self._call_soon(task_maker) - - def _check_closing(self) -> None: - if self._closing: - raise RuntimeError("Operation on the closed queue is forbidden") - - -class _SyncQueueProxy(SyncQueue[T]): - """Create a queue object with a given maximum size. - - If maxsize is <= 0, the queue size is infinite. - """ - - def __init__(self, parent: Queue[T]): - self._parent = parent - - @property - def maxsize(self) -> int: - return self._parent._maxsize - - @property - def closed(self) -> bool: - return self._parent.closed - - def task_done(self) -> None: - """Indicate that a formerly enqueued task is complete. - - Used by Queue consumer threads. For each get() used to fetch a task, - a subsequent call to task_done() tells the queue that the processing - on the task is complete. - - If a join() is currently blocking, it will resume when all items - have been processed (meaning that a task_done() call was received - for every item that had been put() into the queue). - - Raises a ValueError if called more times than there were items - placed in the queue. - """ - self._parent._check_closing() - with self._parent._all_tasks_done: - unfinished = self._parent._unfinished_tasks - 1 - if unfinished <= 0: - if unfinished < 0: - raise ValueError("task_done() called too many times") - self._parent._all_tasks_done.notify_all() - self._parent._loop.call_soon_threadsafe(self._parent._finished.set) - self._parent._unfinished_tasks = unfinished - - def join(self) -> None: - """Blocks until all items in the Queue have been gotten and processed. - - The count of unfinished tasks goes up whenever an item is added to the - queue. The count goes down whenever a consumer thread calls task_done() - to indicate the item was retrieved and all work on it is complete. - - When the count of unfinished tasks drops to zero, join() unblocks. - """ - self._parent._check_closing() - with self._parent._all_tasks_done: - while self._parent._unfinished_tasks: - self._parent._all_tasks_done.wait() - self._parent._check_closing() - - def qsize(self) -> int: - """Return the approximate size of the queue (not reliable!).""" - return self._parent._qsize() - - @property - def unfinished_tasks(self) -> int: - """Return the number of unfinished tasks.""" - return self._parent._unfinished_tasks - - def empty(self) -> bool: - """Return True if the queue is empty, False otherwise (not reliable!). - - This method is likely to be removed at some point. Use qsize() == 0 - as a direct substitute, but be aware that either approach risks a race - condition where a queue can grow before the result of empty() or - qsize() can be used. - - To create code that needs to wait for all queued tasks to be - completed, the preferred technique is to use the join() method. - """ - return not self._parent._qsize() - - def full(self) -> bool: - """Return True if the queue is full, False otherwise (not reliable!). - - This method is likely to be removed at some point. Use qsize() >= n - as a direct substitute, but be aware that either approach risks a race - condition where a queue can shrink before the result of full() or - qsize() can be used. - """ - return 0 < self._parent._maxsize <= self._parent._qsize() - - def put(self, item: T, block: bool = True, timeout: OptFloat = None) -> None: - """Put an item into the queue. - - If optional args 'block' is true and 'timeout' is None (the default), - block if necessary until a free slot is available. If 'timeout' is - a non-negative number, it blocks at most 'timeout' seconds and raises - the Full exception if no free slot was available within that time. - Otherwise ('block' is false), put an item on the queue if a free slot - is immediately available, else raise the Full exception ('timeout' - is ignored in that case). - """ - self._parent._check_closing() - with self._parent._sync_not_full: - if self._parent._maxsize > 0: - if not block: - if self._parent._qsize() >= self._parent._maxsize: - raise SyncQueueFull - elif timeout is None: - while self._parent._qsize() >= self._parent._maxsize: - self._parent._sync_not_full.wait() - elif timeout < 0: - raise ValueError("'timeout' must be a non-negative number") - else: - time = self._parent._loop.time - endtime = time() + timeout - while self._parent._qsize() >= self._parent._maxsize: - remaining = endtime - time() - if remaining <= 0.0: - raise SyncQueueFull - self._parent._sync_not_full.wait(remaining) - self._parent._put_internal(item) - self._parent._sync_not_empty.notify() - self._parent._notify_async_not_empty(threadsafe=True) - - def get(self, block: bool = True, timeout: OptFloat = None) -> T: - """Remove and return an item from the queue. - - If optional args 'block' is true and 'timeout' is None (the default), - block if necessary until an item is available. If 'timeout' is - a non-negative number, it blocks at most 'timeout' seconds and raises - the Empty exception if no item was available within that time. - Otherwise ('block' is false), return an item if one is immediately - available, else raise the Empty exception ('timeout' is ignored - in that case). - """ - self._parent._check_closing() - with self._parent._sync_not_empty: - if not block: - if not self._parent._qsize(): - raise SyncQueueEmpty - elif timeout is None: - while not self._parent._qsize(): - self._parent._sync_not_empty.wait() - elif timeout < 0: - raise ValueError("'timeout' must be a non-negative number") - else: - time = self._parent._loop.time - endtime = time() + timeout - while not self._parent._qsize(): - remaining = endtime - time() - if remaining <= 0.0: - raise SyncQueueEmpty - self._parent._sync_not_empty.wait(remaining) - item = self._parent._get() - self._parent._sync_not_full.notify() - self._parent._notify_async_not_full(threadsafe=True) - return item - - def put_nowait(self, item: T) -> None: - """Put an item into the queue without blocking. - - Only enqueue the item if a free slot is immediately available. - Otherwise raise the Full exception. - """ - return self.put(item, block=False) - - def get_nowait(self) -> T: - """Remove and return an item from the queue without blocking. - - Only get an item if one is immediately available. Otherwise - raise the Empty exception. - """ - return self.get(block=False) - - -class _AsyncQueueProxy(AsyncQueue[T]): - """Create a queue object with a given maximum size. - - If maxsize is <= 0, the queue size is infinite. - """ - - def __init__(self, parent: Queue[T]): - self._parent = parent - - @property - def closed(self) -> bool: - return self._parent.closed - - def qsize(self) -> int: - """Number of items in the queue.""" - return self._parent._qsize() - - @property - def unfinished_tasks(self) -> int: - """Return the number of unfinished tasks.""" - return self._parent._unfinished_tasks - - @property - def maxsize(self) -> int: - """Number of items allowed in the queue.""" - return self._parent._maxsize - - def empty(self) -> bool: - """Return True if the queue is empty, False otherwise.""" - return self.qsize() == 0 - - def full(self) -> bool: - """Return True if there are maxsize items in the queue. - - Note: if the Queue was initialized with maxsize=0 (the default), - then full() is never True. - """ - if self._parent._maxsize <= 0: - return False - else: - return self.qsize() >= self._parent._maxsize - - async def put(self, item: T) -> None: - """Put an item into the queue. - - Put an item into the queue. If the queue is full, wait until a free - slot is available before adding item. - - This method is a coroutine. - """ - self._parent._check_closing() - async with self._parent._async_not_full: - self._parent._sync_mutex.acquire() - locked = True - try: - if self._parent._maxsize > 0: - do_wait = True - while do_wait: - do_wait = self._parent._qsize() >= self._parent._maxsize - if do_wait: - locked = False - self._parent._sync_mutex.release() - await self._parent._async_not_full.wait() - self._parent._sync_mutex.acquire() - locked = True - - self._parent._put_internal(item) - self._parent._async_not_empty.notify() - self._parent._notify_sync_not_empty() - finally: - if locked: - self._parent._sync_mutex.release() - - def put_nowait(self, item: T) -> None: - """Put an item into the queue without blocking. - - If no free slot is immediately available, raise QueueFull. - """ - self._parent._check_closing() - with self._parent._sync_mutex: - if self._parent._maxsize > 0: - if self._parent._qsize() >= self._parent._maxsize: - raise AsyncQueueFull - - self._parent._put_internal(item) - self._parent._notify_async_not_empty(threadsafe=False) - self._parent._notify_sync_not_empty() - - async def get(self) -> T: - """Remove and return an item from the queue. - - If queue is empty, wait until an item is available. - - This method is a coroutine. - """ - self._parent._check_closing() - async with self._parent._async_not_empty: - self._parent._sync_mutex.acquire() - locked = True - try: - do_wait = True - while do_wait: - do_wait = self._parent._qsize() == 0 - - if do_wait: - locked = False - self._parent._sync_mutex.release() - await self._parent._async_not_empty.wait() - self._parent._sync_mutex.acquire() - locked = True - - item = self._parent._get() - self._parent._async_not_full.notify() - self._parent._notify_sync_not_full() - return item - finally: - if locked: - self._parent._sync_mutex.release() - - def get_nowait(self) -> T: - """Remove and return an item from the queue. - - Return an item if one is immediately available, else raise QueueEmpty. - """ - self._parent._check_closing() - with self._parent._sync_mutex: - if self._parent._qsize() == 0: - raise AsyncQueueEmpty - - item = self._parent._get() - self._parent._notify_async_not_full(threadsafe=False) - self._parent._notify_sync_not_full() - return item - - def task_done(self) -> None: - """Indicate that a formerly enqueued task is complete. - - Used by queue consumers. For each get() used to fetch a task, - a subsequent call to task_done() tells the queue that the processing - on the task is complete. - - If a join() is currently blocking, it will resume when all items have - been processed (meaning that a task_done() call was received for every - item that had been put() into the queue). - - Raises ValueError if called more times than there were items placed in - the queue. - """ - self._parent._check_closing() - with self._parent._all_tasks_done: - if self._parent._unfinished_tasks <= 0: - raise ValueError("task_done() called too many times") - self._parent._unfinished_tasks -= 1 - if self._parent._unfinished_tasks == 0: - self._parent._finished.set() - self._parent._all_tasks_done.notify_all() - - async def join(self) -> None: - """Block until all items in the queue have been gotten and processed. - - The count of unfinished tasks goes up whenever an item is added to the - queue. The count goes down whenever a consumer calls task_done() to - indicate that the item was retrieved and all work on it is complete. - When the count of unfinished tasks drops to zero, join() unblocks. - """ - while True: - with self._parent._sync_mutex: - self._parent._check_closing() - if self._parent._unfinished_tasks == 0: - break - await self._parent._finished.wait() - - -class PriorityQueue(Queue[T]): - """Variant of Queue that retrieves open entries in priority order - (lowest first). - - Entries are typically tuples of the form: (priority number, data). - - """ - - def _init(self, maxsize: int) -> None: - self._heap_queue = [] # type: List[T] - - def _qsize(self) -> int: - return len(self._heap_queue) - - def _put(self, item: T) -> None: - heappush(self._heap_queue, item) - - def _get(self) -> T: - return heappop(self._heap_queue) - - -class LifoQueue(Queue[T]): - """Variant of Queue that retrieves most recently added entries first.""" - - def _qsize(self) -> int: - return len(self._queue) - - def _put(self, item: T) -> None: - self._queue.append(item) - - def _get(self) -> T: - return self._queue.pop() From 05ca673883146a543bfb3d739a1ad05368dd28bc Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 27 Aug 2022 00:06:03 -0600 Subject: [PATCH 012/115] Catch status code errors --- freqtrade/rpc/external_signal/controller.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/freqtrade/rpc/external_signal/controller.py b/freqtrade/rpc/external_signal/controller.py index 0d43b0b2d..29a318b53 100644 --- a/freqtrade/rpc/external_signal/controller.py +++ b/freqtrade/rpc/external_signal/controller.py @@ -437,12 +437,12 @@ class ExternalSignalController(RPCHandler): # as we might call the RPC module in the main thread await self._handle_leader_message(data) - except socket.gaierror: - logger.info(f"Socket error - retrying connection in {self.sleep_time}s") + except (socket.gaierror, ConnectionRefusedError): + logger.info(f"Connection Refused - retrying connection in {self.sleep_time}s") await asyncio.sleep(self.sleep_time) continue - except ConnectionRefusedError: - logger.info(f"Connection Refused - retrying connection in {self.sleep_time}s") + except websockets.exceptions.InvalidStatusCode as e: + logger.error(f"Connection Refused - {e}") await asyncio.sleep(self.sleep_time) continue From 8c4e68b8eb21e6bb0e04e47befb15a9d2ad40913 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sun, 28 Aug 2022 13:00:52 -0600 Subject: [PATCH 013/115] updated example configs --- config_examples/config_follower.example.json | 8 +++++--- freqtrade/rpc/external_signal/controller.py | 3 +-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/config_examples/config_follower.example.json b/config_examples/config_follower.example.json index 5317c8df2..646310d9a 100644 --- a/config_examples/config_follower.example.json +++ b/config_examples/config_follower.example.json @@ -46,8 +46,8 @@ }, "pairlists": [ { - "method": "ExternalPairList", - "number_assets": 5, + "method": "ExternalPairList", // ExternalPairList is required in follower mode + "number_assets": 5, // We can limit the amount of pairs to use from the leaders } ], "telegram": { @@ -74,7 +74,9 @@ "url": "ws://localhost:8080/signals/ws", "api_token": "testtoken" } - ] + ], + "wait_data_policy": "all", // ['all', 'first', none] defaults to all + "remove_signals_analyzed_df": true, // Remove entry/exit signals from Leader df, Defaults to false }, "bot_name": "freqtrade", "initial_state": "running", diff --git a/freqtrade/rpc/external_signal/controller.py b/freqtrade/rpc/external_signal/controller.py index 29a318b53..2b29cde6f 100644 --- a/freqtrade/rpc/external_signal/controller.py +++ b/freqtrade/rpc/external_signal/controller.py @@ -373,7 +373,6 @@ class ExternalSignalController(RPCHandler): # Data is being broadcasted right away as soon as startup, # we may not have to send initial data at all. Further testing # required. - await self.send_initial_data(channel) # Keep connection open until explicitly closed, and sleep @@ -434,7 +433,7 @@ class ExternalSignalController(RPCHandler): async with lock: # Acquire lock so only 1 coro handling at a time - # as we might call the RPC module in the main thread + # as we call the RPC module in the main thread await self._handle_leader_message(data) except (socket.gaierror, ConnectionRefusedError): From 7952e0df25914bef04bc0f8acda729e2b9a685d6 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 29 Aug 2022 13:41:15 -0600 Subject: [PATCH 014/115] initial rework separating server and client impl --- .gitignore | 3 - config_examples/config_follower.example.json | 87 -- config_examples/config_leader.example.json | 97 -- freqtrade/constants.py | 1 + freqtrade/enums/rpcmessagetype.py | 5 +- freqtrade/freqtradebot.py | 41 +- freqtrade/rpc/api_server/api_auth.py | 24 +- freqtrade/rpc/api_server/api_ws.py | 52 ++ freqtrade/rpc/api_server/deps.py | 4 + freqtrade/rpc/api_server/webserver.py | 76 +- freqtrade/rpc/api_server/ws/channel.py | 146 +++ freqtrade/rpc/api_server/ws/proxy.py | 61 ++ freqtrade/rpc/api_server/ws/serializer.py | 65 ++ freqtrade/rpc/api_server/ws/types.py | 8 + freqtrade/rpc/api_server/ws/utils.py | 12 + freqtrade/rpc/external_signal/__init__.py | 10 +- freqtrade/rpc/external_signal/channel.py | 290 +++--- freqtrade/rpc/external_signal/controller.py | 898 +++++++++---------- freqtrade/rpc/external_signal/proxy.py | 122 +-- freqtrade/rpc/external_signal/serializer.py | 130 +-- freqtrade/rpc/external_signal/types.py | 16 +- freqtrade/rpc/external_signal/utils.py | 32 +- freqtrade/rpc/rpc.py | 131 ++- freqtrade/rpc/rpc_manager.py | 28 +- scripts/test_ws_client.py | 58 ++ 25 files changed, 1329 insertions(+), 1068 deletions(-) delete mode 100644 config_examples/config_follower.example.json delete mode 100644 config_examples/config_leader.example.json create mode 100644 freqtrade/rpc/api_server/api_ws.py create mode 100644 freqtrade/rpc/api_server/ws/channel.py create mode 100644 freqtrade/rpc/api_server/ws/proxy.py create mode 100644 freqtrade/rpc/api_server/ws/serializer.py create mode 100644 freqtrade/rpc/api_server/ws/types.py create mode 100644 freqtrade/rpc/api_server/ws/utils.py create mode 100644 scripts/test_ws_client.py diff --git a/.gitignore b/.gitignore index b8c4c3846..6a47a7f81 100644 --- a/.gitignore +++ b/.gitignore @@ -115,6 +115,3 @@ target/ !config_examples/config_freqai.example.json !config_examples/config_leader.example.json !config_examples/config_follower.example.json - -*-config.json -*.db* diff --git a/config_examples/config_follower.example.json b/config_examples/config_follower.example.json deleted file mode 100644 index 646310d9a..000000000 --- a/config_examples/config_follower.example.json +++ /dev/null @@ -1,87 +0,0 @@ - -{ - "db_url": "sqlite:///follower.db", - "strategy": "SampleStrategy", - "max_open_trades": 3, - "stake_currency": "USDT", - "stake_amount": 100, - "tradable_balance_ratio": 0.99, - "fiat_display_currency": "USD", - "dry_run": true, - "cancel_open_orders_on_exit": false, - "trading_mode": "spot", - "margin_mode": "", - "unfilledtimeout": { - "entry": 10, - "exit": 10, - "exit_timeout_count": 0, - "unit": "minutes" - }, - "entry_pricing": { - "price_side": "same", - "use_order_book": true, - "order_book_top": 1, - "price_last_balance": 0.0, - "check_depth_of_market": { - "enabled": false, - "bids_to_ask_delta": 1 - } - }, - "exit_pricing":{ - "price_side": "same", - "use_order_book": true, - "order_book_top": 1 - }, - "exchange": { - "name": "kucoin", - "key": "", - "secret": "", - "password": "", - "ccxt_config": {}, - "ccxt_async_config": {}, - "pair_whitelist": [ - ], - "pair_blacklist": [ - ] - }, - "pairlists": [ - { - "method": "ExternalPairList", // ExternalPairList is required in follower mode - "number_assets": 5, // We can limit the amount of pairs to use from the leaders - } - ], - "telegram": { - "enabled": false, - "token": "", - "chat_id": "" - }, - "api_server": { - "enabled": true, - "listen_ip_address": "127.0.0.1", - "listen_port": 8081, - "verbosity": "error", - "enable_openapi": false, - "jwt_secret_key": "fcc24d31d6581ad2c90c3fc438c8a8b2ccce1393126959934568707f0bd2d647", - "CORS_origins": [], - "username": "freqtrader", - "password": "testing123" - }, - "external_signal": { - "enabled": true, - "mode": "follower", - "leaders": [ - { - "url": "ws://localhost:8080/signals/ws", - "api_token": "testtoken" - } - ], - "wait_data_policy": "all", // ['all', 'first', none] defaults to all - "remove_signals_analyzed_df": true, // Remove entry/exit signals from Leader df, Defaults to false - }, - "bot_name": "freqtrade", - "initial_state": "running", - "force_entry_enable": false, - "internals": { - "process_throttle_secs": 5, - } -} diff --git a/config_examples/config_leader.example.json b/config_examples/config_leader.example.json deleted file mode 100644 index 5103fdbd4..000000000 --- a/config_examples/config_leader.example.json +++ /dev/null @@ -1,97 +0,0 @@ - -{ - "db_url": "sqlite:///leader.db", - "strategy": "SampleStrategy", - "max_open_trades": 3, - "stake_currency": "USDT", - "stake_amount": 100, - "tradable_balance_ratio": 0.99, - "fiat_display_currency": "USD", - "dry_run": true, - "cancel_open_orders_on_exit": false, - "trading_mode": "spot", - "margin_mode": "", - "unfilledtimeout": { - "entry": 10, - "exit": 10, - "exit_timeout_count": 0, - "unit": "minutes" - }, - "entry_pricing": { - "price_side": "same", - "use_order_book": true, - "order_book_top": 1, - "price_last_balance": 0.0, - "check_depth_of_market": { - "enabled": false, - "bids_to_ask_delta": 1 - } - }, - "exit_pricing":{ - "price_side": "same", - "use_order_book": true, - "order_book_top": 1 - }, - "exchange": { - "name": "kucoin", - "key": "", - "secret": "", - "password": "", - "ccxt_config": {}, - "ccxt_async_config": {}, - "pair_whitelist": [ - ], - "pair_blacklist": [ - ] - }, - "pairlists": [ - { - "method": "VolumePairList", - "number_assets": 20, - "sort_key": "quoteVolume", - "min_value": 0, - "refresh_period": 1800 - } - ], - "edge": { - "enabled": false, - "process_throttle_secs": 3600, - "calculate_since_number_of_days": 7, - "allowed_risk": 0.01, - "stoploss_range_min": -0.01, - "stoploss_range_max": -0.1, - "stoploss_range_step": -0.01, - "minimum_winrate": 0.60, - "minimum_expectancy": 0.20, - "min_trade_number": 10, - "max_trade_duration_minute": 1440, - "remove_pumps": false - }, - "telegram": { - "enabled": false, - "token": "", - "chat_id": "" - }, - "api_server": { - "enabled": true, - "listen_ip_address": "127.0.0.1", - "listen_port": 8080, - "verbosity": "error", - "enable_openapi": false, - "jwt_secret_key": "fcc24d31d6581ad2c90c3fc438c8a8b2ccce1393126959934568707f0bd2d647", - "CORS_origins": [], - "username": "freqtrader", - "password": "testing123" - }, - "external_signal": { - "enabled": true, - "mode": "leader", - "api_token": "testtoken", - }, - "bot_name": "freqtrade", - "initial_state": "running", - "force_entry_enable": false, - "internals": { - "process_throttle_secs": 5, - } -} diff --git a/freqtrade/constants.py b/freqtrade/constants.py index b1f189093..96f8413b0 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -404,6 +404,7 @@ CONF_SCHEMA = { }, 'username': {'type': 'string'}, 'password': {'type': 'string'}, + 'api_token': {'type': 'string'}, 'jwt_secret_key': {'type': 'string'}, 'CORS_origins': {'type': 'array', 'items': {'type': 'string'}}, 'verbosity': {'type': 'string', 'enum': ['error', 'info']}, diff --git a/freqtrade/enums/rpcmessagetype.py b/freqtrade/enums/rpcmessagetype.py index d5b3ce89c..8e4182b33 100644 --- a/freqtrade/enums/rpcmessagetype.py +++ b/freqtrade/enums/rpcmessagetype.py @@ -1,7 +1,8 @@ from enum import Enum -class RPCMessageType(Enum): +# We need to inherit from str so we can use as a str +class RPCMessageType(str, Enum): STATUS = 'status' WARNING = 'warning' STARTUP = 'startup' @@ -19,7 +20,7 @@ class RPCMessageType(Enum): STRATEGY_MSG = 'strategy_msg' - EMIT_DATA = 'emit_data' + WHITELIST = 'whitelist' def __repr__(self): return self.value diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 6aee3d104..c9caaace6 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -17,13 +17,13 @@ from freqtrade.constants import BuySell, LongShort from freqtrade.data.converter import order_book_to_dataframe from freqtrade.data.dataprovider import DataProvider from freqtrade.edge import Edge -from freqtrade.enums import (ExitCheckTuple, ExitType, LeaderMessageType, RPCMessageType, RunMode, - SignalDirection, State, TradingMode) +from freqtrade.enums import (ExitCheckTuple, ExitType, RPCMessageType, RunMode, SignalDirection, + State, TradingMode) from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError, InvalidOrderException, PricingError) from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds from freqtrade.exchange.exchange import timeframe_to_next_date -from freqtrade.misc import dataframe_to_json, safe_value_fallback, safe_value_fallback2 +from freqtrade.misc import safe_value_fallback, safe_value_fallback2 from freqtrade.mixins import LoggingMixin from freqtrade.persistence import Order, PairLocks, Trade, init_db from freqtrade.plugins.pairlistmanager import PairListManager @@ -75,8 +75,6 @@ class FreqtradeBot(LoggingMixin): PairLocks.timeframe = self.config['timeframe'] - self.external_signal_controller = None - self.pairlists = PairListManager(self.exchange, self.config) # RPC runs in separate threads, can start handling external commands just after @@ -194,28 +192,7 @@ class FreqtradeBot(LoggingMixin): strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)() - if self.external_signal_controller: - if not self.external_signal_controller.is_leader(): - # Run Follower mode analyzing - leader_pairs = self.pairlists._whitelist - self.strategy.analyze_external(self.active_pair_whitelist, leader_pairs) - else: - # We are leader, make sure to pass callback func to emit data - def emit_on_finish(pair, dataframe, timeframe, candle_type): - logger.debug(f"Emitting dataframe for {pair}") - return self.rpc.emit_data( - { - "data_type": LeaderMessageType.analyzed_df, - "data": { - "key": (pair, timeframe, candle_type), - "value": dataframe_to_json(dataframe) - } - } - ) - - self.strategy.analyze(self.active_pair_whitelist, finish_callback=emit_on_finish) - else: - self.strategy.analyze(self.active_pair_whitelist) + self.strategy.analyze(self.active_pair_whitelist) with self._exit_lock: # Check for exchange cancelations, timeouts and user requested replace @@ -278,15 +255,7 @@ class FreqtradeBot(LoggingMixin): self.pairlists.refresh_pairlist() _whitelist = self.pairlists.whitelist - # If external signal leader, broadcast whitelist data - # Should we broadcast before trade pairs are added? - - if self.external_signal_controller: - if self.external_signal_controller.is_leader(): - self.rpc.emit_data({ - "data_type": LeaderMessageType.pairlist, - "data": _whitelist - }) + self.rpc.send_msg({'type': RPCMessageType.WHITELIST, 'msg': _whitelist}) # Calculating Edge positioning if self.edge: diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index a39e31b85..fd90918e1 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -1,8 +1,10 @@ +import logging import secrets from datetime import datetime, timedelta +from typing import Any, Dict, Union import jwt -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, Depends, HTTPException, WebSocket, status from fastapi.security import OAuth2PasswordBearer from fastapi.security.http import HTTPBasic, HTTPBasicCredentials @@ -10,6 +12,8 @@ from freqtrade.rpc.api_server.api_schemas import AccessAndRefreshToken, AccessTo from freqtrade.rpc.api_server.deps import get_api_config +logger = logging.getLogger(__name__) + ALGORITHM = "HS256" router_login = APIRouter() @@ -44,6 +48,24 @@ def get_user_from_token(token, secret_key: str, token_type: str = "access"): return username +# This should be reimplemented to better realign with the existing tools provided +# by FastAPI regarding API Tokens +async def get_ws_token( + ws: WebSocket, + token: Union[str, None] = None, + api_config: Dict[str, Any] = Depends(get_api_config) +): + secret_ws_token = api_config['ws_token'] + + if token == secret_ws_token: + # Just return the token if it matches + return token + else: + logger.debug("Denying websocket request") + # If it doesn't match, close the websocket connection + await ws.close(code=status.WS_1008_POLICY_VIOLATION) + + def create_token(data: dict, secret_key: str, token_type: str = "access") -> str: to_encode = data.copy() if token_type == "access": diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py new file mode 100644 index 000000000..464ea22b2 --- /dev/null +++ b/freqtrade/rpc/api_server/api_ws.py @@ -0,0 +1,52 @@ +import logging + +from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect + +from freqtrade.rpc.api_server.deps import get_channel_manager +from freqtrade.rpc.api_server.ws.utils import is_websocket_alive + + +logger = logging.getLogger(__name__) + +# Private router, protected by API Key authentication +router = APIRouter() + + +@router.websocket("/message/ws") +async def message_endpoint( + ws: WebSocket, + channel_manager=Depends(get_channel_manager) +): + try: + if is_websocket_alive(ws): + logger.info(f"Consumer connected - {ws.client}") + + # TODO: + # Return a channel ID, pass that instead of ws to the rest of the methods + channel = await channel_manager.on_connect(ws) + + # Keep connection open until explicitly closed, and sleep + try: + while not channel.is_closed(): + request = await channel.recv() + + # This is where we'd parse the request. For now this should only + # be a list of topics to subscribe too. List[str] + # Maybe allow the consumer to update the topics subscribed + # during runtime? + logger.info(f"Consumer request - {request}") + + except WebSocketDisconnect: + # Handle client disconnects + logger.info(f"Consumer disconnected - {ws.client}") + await channel_manager.on_disconnect(ws) + except Exception as e: + logger.info(f"Consumer connection failed - {ws.client}") + logger.exception(e) + # Handle cases like - + # RuntimeError('Cannot call "send" once a closed message has been sent') + await channel_manager.on_disconnect(ws) + + except Exception: + logger.error(f"Failed to serve - {ws.client}") + await channel_manager.on_disconnect(ws) diff --git a/freqtrade/rpc/api_server/deps.py b/freqtrade/rpc/api_server/deps.py index 66654c0b1..360771d77 100644 --- a/freqtrade/rpc/api_server/deps.py +++ b/freqtrade/rpc/api_server/deps.py @@ -41,6 +41,10 @@ def get_exchange(config=Depends(get_config)): return ApiServer._exchange +def get_channel_manager(): + return ApiServer._channel_manager + + def is_webserver_mode(config=Depends(get_config)): if config['runmode'] != RunMode.WEBSERVER: raise RPCException('Bot is not in the correct state') diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 049e7dbc2..94cb8cd45 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -1,15 +1,20 @@ +import asyncio import logging from ipaddress import IPv4Address +from threading import Thread from typing import Any, Dict import orjson import uvicorn from fastapi import Depends, FastAPI from fastapi.middleware.cors import CORSMiddleware +# Look into alternatives +from janus import Queue as ThreadedQueue from starlette.responses import JSONResponse from freqtrade.exceptions import OperationalException from freqtrade.rpc.api_server.uvicorn_threaded import UvicornServer +from freqtrade.rpc.api_server.ws.channel import ChannelManager from freqtrade.rpc.rpc import RPC, RPCException, RPCHandler @@ -43,6 +48,10 @@ class ApiServer(RPCHandler): _config: Dict[str, Any] = {} # Exchange - only available in webserver mode. _exchange = None + # websocket message queue stuff + _channel_manager = None + _thread = None + _loop = None def __new__(cls, *args, **kwargs): """ @@ -64,10 +73,15 @@ class ApiServer(RPCHandler): return self._standalone: bool = standalone self._server = None + self._queue = None + self._background_task = None + ApiServer.__initialized = True api_config = self._config['api_server'] + ApiServer._channel_manager = ChannelManager() + self.app = FastAPI(title="Freqtrade API", docs_url='/docs' if api_config.get('enable_openapi', False) else None, redoc_url=None, @@ -95,6 +109,18 @@ class ApiServer(RPCHandler): logger.info("Stopping API Server") self._server.cleanup() + if self._thread and self._loop: + logger.info("Stopping API Server background tasks") + + if self._background_task: + # Cancel the queue task + self._background_task.cancel() + + # Finally stop the loop + self._loop.call_soon_threadsafe(self._loop.stop) + + self._thread.join() + @classmethod def shutdown(cls): cls.__initialized = False @@ -104,7 +130,10 @@ class ApiServer(RPCHandler): cls._rpc = None def send_msg(self, msg: Dict[str, str]) -> None: - pass + if self._queue: + logger.info(f"Adding message to queue: {msg}") + sync_q = self._queue.sync_q + sync_q.put(msg) def handle_rpc_exception(self, request, exc): logger.exception(f"API Error calling: {exc}") @@ -114,10 +143,12 @@ class ApiServer(RPCHandler): ) def configure_app(self, app: FastAPI, config): - from freqtrade.rpc.api_server.api_auth import http_basic_or_jwt_token, router_login + from freqtrade.rpc.api_server.api_auth import (get_ws_token, http_basic_or_jwt_token, + router_login) from freqtrade.rpc.api_server.api_backtest import router as api_backtest from freqtrade.rpc.api_server.api_v1 import router as api_v1 from freqtrade.rpc.api_server.api_v1 import router_public as api_v1_public + from freqtrade.rpc.api_server.api_ws import router as ws_router from freqtrade.rpc.api_server.web_ui import router_ui app.include_router(api_v1_public, prefix="/api/v1") @@ -128,6 +159,9 @@ class ApiServer(RPCHandler): app.include_router(api_backtest, prefix="/api/v1", dependencies=[Depends(http_basic_or_jwt_token)], ) + app.include_router(ws_router, prefix="/api/v1", + dependencies=[Depends(get_ws_token)] + ) app.include_router(router_login, prefix="/api/v1", tags=["auth"]) # UI Router MUST be last! app.include_router(router_ui, prefix='') @@ -142,6 +176,43 @@ class ApiServer(RPCHandler): app.add_exception_handler(RPCException, self.handle_rpc_exception) + def start_message_queue(self): + # Create a new loop, as it'll be just for the background thread + self._loop = asyncio.new_event_loop() + + # Start the thread + if not self._thread: + self._thread = Thread(target=self._loop.run_forever) + self._thread.start() + else: + raise RuntimeError("Threaded loop is already running") + + # Finally, submit the coro to the thread + self._background_task = asyncio.run_coroutine_threadsafe( + self._broadcast_queue_data(), loop=self._loop) + + async def _broadcast_queue_data(self): + # Instantiate the queue in this coroutine so it's attached to our loop + self._queue = ThreadedQueue() + async_queue = self._queue.async_q + + try: + while True: + logger.debug("Getting queue data...") + # Get data from queue + data = await async_queue.get() + logger.debug(f"Found data: {data}") + # Broadcast it + await self._channel_manager.broadcast(data) + # Sleep, make this configurable? + await asyncio.sleep(0.1) + except asyncio.CancelledError: + # Silently stop + pass + # For testing, shouldn't happen when stable + except Exception as e: + logger.info(f"Exception happened in background task: {e}") + def start_api(self): """ Start API ... should be run in thread. @@ -179,6 +250,7 @@ class ApiServer(RPCHandler): if self._standalone: self._server.run() else: + self.start_message_queue() self._server.run_in_thread() except Exception: logger.exception("Api server failed to start.") diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py new file mode 100644 index 000000000..486e8657b --- /dev/null +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -0,0 +1,146 @@ +import logging +from threading import RLock +from typing import Type + +from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy +from freqtrade.rpc.api_server.ws.serializer import ORJSONWebSocketSerializer, WebSocketSerializer +from freqtrade.rpc.api_server.ws.types import WebSocketType + + +logger = logging.getLogger(__name__) + + +class WebSocketChannel: + """ + Object to help facilitate managing a websocket connection + """ + + def __init__( + self, + websocket: WebSocketType, + serializer_cls: Type[WebSocketSerializer] = ORJSONWebSocketSerializer + ): + # The WebSocket object + self._websocket = WebSocketProxy(websocket) + # The Serializing class for the WebSocket object + self._serializer_cls = serializer_cls + + # Internal event to signify a closed websocket + self._closed = False + + # Wrap the WebSocket in the Serializing class + self._wrapped_ws = self._serializer_cls(self._websocket) + + async def send(self, data): + """ + Send data on the wrapped websocket + """ + # logger.info(f"Serialized Send - {self._wrapped_ws._serialize(data)}") + await self._wrapped_ws.send(data) + + async def recv(self): + """ + Receive data on the wrapped websocket + """ + return await self._wrapped_ws.recv() + + async def ping(self): + """ + Ping the websocket + """ + return await self._websocket.ping() + + async def close(self): + """ + Close the WebSocketChannel + """ + + self._closed = True + + def is_closed(self): + return self._closed + + +class ChannelManager: + def __init__(self): + self.channels = dict() + self._lock = RLock() # Re-entrant Lock + + async def on_connect(self, websocket: WebSocketType): + """ + Wrap websocket connection into Channel and add to list + + :param websocket: The WebSocket object to attach to the Channel + """ + if hasattr(websocket, "accept"): + try: + await websocket.accept() + except RuntimeError: + # The connection was closed before we could accept it + return + + ws_channel = WebSocketChannel(websocket) + + with self._lock: + self.channels[websocket] = ws_channel + + return ws_channel + + async def on_disconnect(self, websocket: WebSocketType): + """ + Call close on the channel if it's not, and remove from channel list + + :param websocket: The WebSocket objet attached to the Channel + """ + with self._lock: + channel = self.channels.get(websocket) + if channel: + logger.debug(f"Disconnecting channel - {channel}") + + if not channel.is_closed(): + await channel.close() + + del self.channels[websocket] + + async def disconnect_all(self): + """ + Disconnect all Channels + """ + with self._lock: + for websocket, channel in self.channels.items(): + if not channel.is_closed(): + await channel.close() + + self.channels = dict() + + async def broadcast(self, data): + """ + Broadcast data on all Channels + + :param data: The data to send + """ + with self._lock: + logger.debug(f"Broadcasting data: {data}") + for websocket, channel in self.channels.items(): + try: + await channel.send(data) + except RuntimeError: + # Handle cannot send after close cases + await self.on_disconnect(websocket) + + async def send_direct(self, channel, data): + """ + Send data directly through direct_channel only + + :param direct_channel: The WebSocketChannel object to send data through + :param data: The data to send + """ + # We iterate over the channels to get reference to the websocket object + # so we can disconnect incase of failure + await channel.send(data) + + def has_channels(self): + """ + Flag for more than 0 channels + """ + return len(self.channels) > 0 diff --git a/freqtrade/rpc/api_server/ws/proxy.py b/freqtrade/rpc/api_server/ws/proxy.py new file mode 100644 index 000000000..6acc1d363 --- /dev/null +++ b/freqtrade/rpc/api_server/ws/proxy.py @@ -0,0 +1,61 @@ +from typing import Union + +from fastapi import WebSocket as FastAPIWebSocket +from websockets import WebSocketClientProtocol as WebSocket + +from freqtrade.rpc.api_server.ws.types import WebSocketType + + +class WebSocketProxy: + """ + WebSocketProxy object to bring the FastAPIWebSocket and websockets.WebSocketClientProtocol + under the same API + """ + + def __init__(self, websocket: WebSocketType): + self._websocket: Union[FastAPIWebSocket, WebSocket] = websocket + + async def send(self, data): + """ + Send data on the wrapped websocket + """ + if isinstance(data, str): + data = data.encode() + + if hasattr(self._websocket, "send_bytes"): + await self._websocket.send_bytes(data) + else: + await self._websocket.send(data) + + async def recv(self): + """ + Receive data on the wrapped websocket + """ + if hasattr(self._websocket, "receive_bytes"): + return await self._websocket.receive_bytes() + else: + return await self._websocket.recv() + + async def ping(self): + """ + Ping the websocket, not supported by FastAPI WebSockets + """ + if hasattr(self._websocket, "ping"): + return await self._websocket.ping() + return False + + async def close(self, code: int = 1000): + """ + Close the websocket connection, only supported by FastAPI WebSockets + """ + if hasattr(self._websocket, "close"): + return await self._websocket.close(code) + pass + + async def accept(self): + """ + Accept the WebSocket connection, only support by FastAPI WebSockets + """ + if hasattr(self._websocket, "accept"): + return await self._websocket.accept() + pass diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py new file mode 100644 index 000000000..40cbbfad7 --- /dev/null +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -0,0 +1,65 @@ +import json +import logging +from abc import ABC, abstractmethod + +import msgpack +import orjson + +from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy + + +logger = logging.getLogger(__name__) + + +class WebSocketSerializer(ABC): + def __init__(self, websocket: WebSocketProxy): + self._websocket: WebSocketProxy = websocket + + @abstractmethod + def _serialize(self, data): + raise NotImplementedError() + + @abstractmethod + def _deserialize(self, data): + raise NotImplementedError() + + async def send(self, data: bytes): + await self._websocket.send(self._serialize(data)) + + async def recv(self) -> bytes: + data = await self._websocket.recv() + + return self._deserialize(data) + + async def close(self, code: int = 1000): + await self._websocket.close(code) + +# Going to explore using MsgPack as the serialization, +# as that might be the best method for sending pandas +# dataframes over the wire + + +class JSONWebSocketSerializer(WebSocketSerializer): + def _serialize(self, data): + return json.dumps(data) + + def _deserialize(self, data): + return json.loads(data) + + +class ORJSONWebSocketSerializer(WebSocketSerializer): + ORJSON_OPTIONS = orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY + + def _serialize(self, data): + return orjson.dumps(data, option=self.ORJSON_OPTIONS) + + def _deserialize(self, data): + return orjson.loads(data, option=self.ORJSON_OPTIONS) + + +class MsgPackWebSocketSerializer(WebSocketSerializer): + def _serialize(self, data): + return msgpack.packb(data, use_bin_type=True) + + def _deserialize(self, data): + return msgpack.unpackb(data, raw=False) diff --git a/freqtrade/rpc/api_server/ws/types.py b/freqtrade/rpc/api_server/ws/types.py new file mode 100644 index 000000000..814fe6649 --- /dev/null +++ b/freqtrade/rpc/api_server/ws/types.py @@ -0,0 +1,8 @@ +from typing import Any, Dict, TypeVar + +from fastapi import WebSocket as FastAPIWebSocket +from websockets import WebSocketClientProtocol as WebSocket + + +WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket) +MessageType = Dict[str, Any] diff --git a/freqtrade/rpc/api_server/ws/utils.py b/freqtrade/rpc/api_server/ws/utils.py new file mode 100644 index 000000000..1ceecab88 --- /dev/null +++ b/freqtrade/rpc/api_server/ws/utils.py @@ -0,0 +1,12 @@ +from fastapi import WebSocket +# fastapi does not make this available through it, so import directly from starlette +from starlette.websockets import WebSocketState + + +async def is_websocket_alive(ws: WebSocket) -> bool: + if ( + ws.application_state == WebSocketState.CONNECTED and + ws.client_state == WebSocketState.CONNECTED + ): + return True + return False diff --git a/freqtrade/rpc/external_signal/__init__.py b/freqtrade/rpc/external_signal/__init__.py index c1b05b3f0..decc51551 100644 --- a/freqtrade/rpc/external_signal/__init__.py +++ b/freqtrade/rpc/external_signal/__init__.py @@ -1,5 +1,5 @@ -# flake8: noqa: F401 -from freqtrade.rpc.external_signal.controller import ExternalSignalController - - -__all__ = ('ExternalSignalController') +# # flake8: noqa: F401 +# from freqtrade.rpc.external_signal.controller import ExternalSignalController +# +# +# __all__ = ('ExternalSignalController') diff --git a/freqtrade/rpc/external_signal/channel.py b/freqtrade/rpc/external_signal/channel.py index 4ccb2d864..5b278dfed 100644 --- a/freqtrade/rpc/external_signal/channel.py +++ b/freqtrade/rpc/external_signal/channel.py @@ -1,145 +1,145 @@ -import logging -from threading import RLock -from typing import Type - -from freqtrade.rpc.external_signal.proxy import WebSocketProxy -from freqtrade.rpc.external_signal.serializer import MsgPackWebSocketSerializer, WebSocketSerializer -from freqtrade.rpc.external_signal.types import WebSocketType - - -logger = logging.getLogger(__name__) - - -class WebSocketChannel: - """ - Object to help facilitate managing a websocket connection - """ - - def __init__( - self, - websocket: WebSocketType, - serializer_cls: Type[WebSocketSerializer] = MsgPackWebSocketSerializer - ): - # The WebSocket object - self._websocket = WebSocketProxy(websocket) - # The Serializing class for the WebSocket object - self._serializer_cls = serializer_cls - - # Internal event to signify a closed websocket - self._closed = False - - # Wrap the WebSocket in the Serializing class - self._wrapped_ws = self._serializer_cls(self._websocket) - - async def send(self, data): - """ - Send data on the wrapped websocket - """ - # logger.info(f"Serialized Send - {self._wrapped_ws._serialize(data)}") - await self._wrapped_ws.send(data) - - async def recv(self): - """ - Receive data on the wrapped websocket - """ - return await self._wrapped_ws.recv() - - async def ping(self): - """ - Ping the websocket - """ - return await self._websocket.ping() - - async def close(self): - """ - Close the WebSocketChannel - """ - - self._closed = True - - def is_closed(self): - return self._closed - - -class ChannelManager: - def __init__(self): - self.channels = dict() - self._lock = RLock() # Re-entrant Lock - - async def on_connect(self, websocket: WebSocketType): - """ - Wrap websocket connection into Channel and add to list - - :param websocket: The WebSocket object to attach to the Channel - """ - if hasattr(websocket, "accept"): - try: - await websocket.accept() - except RuntimeError: - # The connection was closed before we could accept it - return - - ws_channel = WebSocketChannel(websocket) - - with self._lock: - self.channels[websocket] = ws_channel - - return ws_channel - - async def on_disconnect(self, websocket: WebSocketType): - """ - Call close on the channel if it's not, and remove from channel list - - :param websocket: The WebSocket objet attached to the Channel - """ - with self._lock: - channel = self.channels.get(websocket) - if channel: - logger.debug(f"Disconnecting channel - {channel}") - - if not channel.is_closed(): - await channel.close() - - del self.channels[websocket] - - async def disconnect_all(self): - """ - Disconnect all Channels - """ - with self._lock: - for websocket, channel in self.channels.items(): - if not channel.is_closed(): - await channel.close() - - self.channels = dict() - - async def broadcast(self, data): - """ - Broadcast data on all Channels - - :param data: The data to send - """ - with self._lock: - for websocket, channel in self.channels.items(): - try: - await channel.send(data) - except RuntimeError: - # Handle cannot send after close cases - await self.on_disconnect(websocket) - - async def send_direct(self, channel, data): - """ - Send data directly through direct_channel only - - :param direct_channel: The WebSocketChannel object to send data through - :param data: The data to send - """ - # We iterate over the channels to get reference to the websocket object - # so we can disconnect incase of failure - await channel.send(data) - - def has_channels(self): - """ - Flag for more than 0 channels - """ - return len(self.channels) > 0 +# import logging +# from threading import RLock +# from typing import Type +# +# from freqtrade.rpc.external_signal.proxy import WebSocketProxy +# from freqtrade.rpc.external_signal.serializer import MsgPackWebSocketSerializer +# from freqtrade.rpc.external_signal.types import WebSocketType +# +# +# logger = logging.getLogger(__name__) +# +# +# class WebSocketChannel: +# """ +# Object to help facilitate managing a websocket connection +# """ +# +# def __init__( +# self, +# websocket: WebSocketType, +# serializer_cls: Type[WebSocketSerializer] = MsgPackWebSocketSerializer +# ): +# # The WebSocket object +# self._websocket = WebSocketProxy(websocket) +# # The Serializing class for the WebSocket object +# self._serializer_cls = serializer_cls +# +# # Internal event to signify a closed websocket +# self._closed = False +# +# # Wrap the WebSocket in the Serializing class +# self._wrapped_ws = self._serializer_cls(self._websocket) +# +# async def send(self, data): +# """ +# Send data on the wrapped websocket +# """ +# # logger.info(f"Serialized Send - {self._wrapped_ws._serialize(data)}") +# await self._wrapped_ws.send(data) +# +# async def recv(self): +# """ +# Receive data on the wrapped websocket +# """ +# return await self._wrapped_ws.recv() +# +# async def ping(self): +# """ +# Ping the websocket +# """ +# return await self._websocket.ping() +# +# async def close(self): +# """ +# Close the WebSocketChannel +# """ +# +# self._closed = True +# +# def is_closed(self): +# return self._closed +# +# +# class ChannelManager: +# def __init__(self): +# self.channels = dict() +# self._lock = RLock() # Re-entrant Lock +# +# async def on_connect(self, websocket: WebSocketType): +# """ +# Wrap websocket connection into Channel and add to list +# +# :param websocket: The WebSocket object to attach to the Channel +# """ +# if hasattr(websocket, "accept"): +# try: +# await websocket.accept() +# except RuntimeError: +# # The connection was closed before we could accept it +# return +# +# ws_channel = WebSocketChannel(websocket) +# +# with self._lock: +# self.channels[websocket] = ws_channel +# +# return ws_channel +# +# async def on_disconnect(self, websocket: WebSocketType): +# """ +# Call close on the channel if it's not, and remove from channel list +# +# :param websocket: The WebSocket objet attached to the Channel +# """ +# with self._lock: +# channel = self.channels.get(websocket) +# if channel: +# logger.debug(f"Disconnecting channel - {channel}") +# +# if not channel.is_closed(): +# await channel.close() +# +# del self.channels[websocket] +# +# async def disconnect_all(self): +# """ +# Disconnect all Channels +# """ +# with self._lock: +# for websocket, channel in self.channels.items(): +# if not channel.is_closed(): +# await channel.close() +# +# self.channels = dict() +# +# async def broadcast(self, data): +# """ +# Broadcast data on all Channels +# +# :param data: The data to send +# """ +# with self._lock: +# for websocket, channel in self.channels.items(): +# try: +# await channel.send(data) +# except RuntimeError: +# # Handle cannot send after close cases +# await self.on_disconnect(websocket) +# +# async def send_direct(self, channel, data): +# """ +# Send data directly through direct_channel only +# +# :param direct_channel: The WebSocketChannel object to send data through +# :param data: The data to send +# """ +# # We iterate over the channels to get reference to the websocket object +# # so we can disconnect incase of failure +# await channel.send(data) +# +# def has_channels(self): +# """ +# Flag for more than 0 channels +# """ +# return len(self.channels) > 0 diff --git a/freqtrade/rpc/external_signal/controller.py b/freqtrade/rpc/external_signal/controller.py index 2b29cde6f..616ea7801 100644 --- a/freqtrade/rpc/external_signal/controller.py +++ b/freqtrade/rpc/external_signal/controller.py @@ -1,449 +1,449 @@ -""" -This module manages replicate mode communication -""" -import asyncio -import logging -import secrets -import socket -from threading import Thread -from typing import Any, Callable, Coroutine, Dict, Union - -import websockets -from fastapi import Depends -from fastapi import WebSocket as FastAPIWebSocket -from fastapi import WebSocketDisconnect, status -from janus import Queue as ThreadedQueue - -from freqtrade.enums import ExternalSignalModeType, LeaderMessageType, RPCMessageType -from freqtrade.rpc import RPC, RPCHandler -from freqtrade.rpc.external_signal.channel import ChannelManager -from freqtrade.rpc.external_signal.types import MessageType -from freqtrade.rpc.external_signal.utils import is_websocket_alive - - -logger = logging.getLogger(__name__) - - -class ExternalSignalController(RPCHandler): - """ This class handles all websocket communication """ - - def __init__( - self, - rpc: RPC, - config: Dict[str, Any], - api_server: Union[Any, None] = None - ) -> None: - """ - Init the ExternalSignalController class, and init the super class RPCHandler - :param rpc: instance of RPC Helper class - :param config: Configuration object - :param api_server: The ApiServer object - :return: None - """ - super().__init__(rpc, config) - - self.freqtrade = rpc._freqtrade - self.api_server = api_server - - if not self.api_server: - raise RuntimeError("The API server must be enabled for external signals to work") - - self._loop = None - self._running = False - self._thread = None - self._queue = None - - self._main_task = None - self._sub_tasks = None - - self._message_handlers = { - LeaderMessageType.pairlist: self._rpc._handle_pairlist_message, - LeaderMessageType.analyzed_df: self._rpc._handle_analyzed_df_message, - LeaderMessageType.default: self._rpc._handle_default_message - } - - self.channel_manager = ChannelManager() - self.external_signal_config = config.get('external_signal', {}) - - # What the config should look like - # "external_signal": { - # "enabled": true, - # "mode": "follower", - # "leaders": [ - # { - # "url": "ws://localhost:8080/signals/ws", - # "api_token": "test" - # } - # ] - # } - - # "external_signal": { - # "enabled": true, - # "mode": "leader", - # "api_token": "test" - # } - - self.mode = ExternalSignalModeType[ - self.external_signal_config.get('mode', 'leader').lower() - ] - - self.leaders_list = self.external_signal_config.get('leaders', []) - self.push_throttle_secs = self.external_signal_config.get('push_throttle_secs', 0.1) - - self.reply_timeout = self.external_signal_config.get('follower_reply_timeout', 10) - self.ping_timeout = self.external_signal_config.get('follower_ping_timeout', 2) - self.sleep_time = self.external_signal_config.get('follower_sleep_time', 5) - - # Validate external_signal_config here? - - if self.mode == ExternalSignalModeType.follower and len(self.leaders_list) == 0: - raise ValueError("You must specify at least 1 leader in follower mode.") - - # This is only used by the leader, the followers use the tokens specified - # in each of the leaders - # If you do not specify an API key in the config, one will be randomly - # generated and logged on startup - default_api_key = secrets.token_urlsafe(16) - self.secret_api_key = self.external_signal_config.get('api_token', default_api_key) - - self.start() - - def is_leader(self): - """ - Leader flag - """ - return self.enabled() and self.mode == ExternalSignalModeType.leader - - def enabled(self): - """ - Enabled flag - """ - return self.external_signal_config.get('enabled', False) - - def num_leaders(self): - """ - The number of leaders we should be connected to - """ - return len(self.leaders_list) - - def start_threaded_loop(self): - """ - Start the main internal loop in another thread to run coroutines - """ - self._loop = asyncio.new_event_loop() - - if not self._thread: - self._thread = Thread(target=self._loop.run_forever) - self._thread.start() - self._running = True - else: - raise RuntimeError("A loop is already running") - - def submit_coroutine(self, coroutine: Coroutine): - """ - Submit a coroutine to the threaded loop - """ - if not self._running: - raise RuntimeError("Cannot schedule new futures after shutdown") - - if not self._loop or not self._loop.is_running(): - raise RuntimeError("Loop must be started before any function can" - " be submitted") - - return asyncio.run_coroutine_threadsafe(coroutine, self._loop) - - def start(self): - """ - Start the controller main loop - """ - self.start_threaded_loop() - self._main_task = self.submit_coroutine(self.main()) - - async def shutdown(self): - """ - Shutdown all tasks and close up - """ - logger.info("Stopping rpc.externalsignalcontroller") - - # Flip running flag - self._running = False - - # Cancel sub tasks - for task in self._sub_tasks: - task.cancel() - - # Then disconnect all channels - await self.channel_manager.disconnect_all() - - def cleanup(self) -> None: - """ - Cleanup pending module resources. - """ - if self._thread: - if self._loop.is_running(): - self._main_task.cancel() - self._thread.join() - - async def main(self): - """ - Main coro - - Start the loop based on what mode we're in - """ - try: - if self.mode == ExternalSignalModeType.leader: - logger.info("Starting rpc.externalsignalcontroller in Leader mode") - - await self.run_leader_mode() - elif self.mode == ExternalSignalModeType.follower: - logger.info("Starting rpc.externalsignalcontroller in Follower mode") - - await self.run_follower_mode() - - except asyncio.CancelledError: - # We're cancelled - await self.shutdown() - except Exception as e: - # Log the error - logger.error(f"Exception occurred in main task: {e}") - logger.exception(e) - finally: - # This coroutine is the last thing to be ended, so it should stop the loop - self._loop.stop() - - def log_api_token(self): - """ - Log the API token - """ - logger.info("-" * 15) - logger.info(f"API_KEY: {self.secret_api_key}") - logger.info("-" * 15) - - def send_msg(self, msg: MessageType) -> None: - """ - Support RPC calls - """ - if msg["type"] == RPCMessageType.EMIT_DATA: - message = msg.get("message") - if message: - self.send_message(message) - else: - logger.error(f"Message is empty! {msg}") - - def send_message(self, msg: MessageType) -> None: - """ - Broadcast message over all channels if there are any - """ - - if self.channel_manager.has_channels(): - self._send_message(msg) - else: - logger.debug("No listening followers, skipping...") - pass - - def _send_message(self, msg: MessageType): - """ - Add data to the internal queue to be broadcasted. This func will block - if the queue is full. This is meant to be called in the main thread. - """ - if self._queue: - queue = self._queue.sync_q - queue.put(msg) # This will block if the queue is full - else: - logger.warning("Can not send data, leader loop has not started yet!") - - async def send_initial_data(self, channel): - logger.info("Sending initial data through channel") - - data = self._rpc._initial_leader_data() - - for message in data: - await channel.send(message) - - async def _handle_leader_message(self, message: MessageType): - """ - Handle message received from a Leader - """ - type = message.get("data_type", LeaderMessageType.default) - data = message.get("data") - - handler: Callable = self._message_handlers[type] - handler(type, data) - - # ---------------------------------------------------------------------- - - async def run_leader_mode(self): - """ - Main leader coroutine - - This starts all of the leader coros and registers the endpoint on - the ApiServer - """ - self.register_leader_endpoint() - self.log_api_token() - - self._sub_tasks = [ - self._loop.create_task(self._broadcast_queue_data()) - ] - - return await asyncio.gather(*self._sub_tasks) - - async def run_follower_mode(self): - """ - Main follower coroutine - - This starts all of the follower connection coros - """ - - rpc_lock = asyncio.Lock() - - self._sub_tasks = [ - self._loop.create_task(self._handle_leader_connection(leader, rpc_lock)) - for leader in self.leaders_list - ] - - return await asyncio.gather(*self._sub_tasks) - - async def _broadcast_queue_data(self): - """ - Loop over queue data and broadcast it - """ - # Instantiate the queue in this coroutine so it's attached to our loop - self._queue = ThreadedQueue() - async_queue = self._queue.async_q - - try: - while self._running: - # Get data from queue - data = await async_queue.get() - - # Broadcast it to everyone - await self.channel_manager.broadcast(data) - - # Sleep - await asyncio.sleep(self.push_throttle_secs) - - except asyncio.CancelledError: - # Silently stop - pass - - async def get_api_token( - self, - websocket: FastAPIWebSocket, - token: Union[str, None] = None - ): - """ - Extract the API key from query param. Must match the - set secret_api_key or the websocket connection will be closed. - """ - if token == self.secret_api_key: - return token - else: - logger.info("Denying websocket request...") - await websocket.close(code=status.WS_1008_POLICY_VIOLATION) - - def register_leader_endpoint(self, path: str = "/signals/ws"): - """ - Attach and start the main leader loop to the ApiServer - - :param path: The endpoint path - """ - if not self.api_server: - raise RuntimeError("The leader needs the ApiServer to be active") - - # The endpoint function for running the main leader loop - @self.api_server.app.websocket(path) - async def leader_endpoint( - websocket: FastAPIWebSocket, - api_key: str = Depends(self.get_api_token) - ): - await self.leader_endpoint_loop(websocket) - - async def leader_endpoint_loop(self, websocket: FastAPIWebSocket): - """ - The WebSocket endpoint served by the ApiServer. This handles connections, - and adding them to the channel manager. - """ - try: - if is_websocket_alive(websocket): - logger.info(f"Follower connected - {websocket.client}") - channel = await self.channel_manager.on_connect(websocket) - - # Send initial data here - # Data is being broadcasted right away as soon as startup, - # we may not have to send initial data at all. Further testing - # required. - await self.send_initial_data(channel) - - # Keep connection open until explicitly closed, and sleep - try: - while not channel.is_closed(): - request = await channel.recv() - logger.info(f"Follower request - {request}") - - except WebSocketDisconnect: - # Handle client disconnects - logger.info(f"Follower disconnected - {websocket.client}") - await self.channel_manager.on_disconnect(websocket) - except Exception as e: - logger.info(f"Follower connection failed - {websocket.client}") - logger.exception(e) - # Handle cases like - - # RuntimeError('Cannot call "send" once a closed message has been sent') - await self.channel_manager.on_disconnect(websocket) - - except Exception: - logger.error(f"Failed to serve - {websocket.client}") - await self.channel_manager.on_disconnect(websocket) - - async def _handle_leader_connection(self, leader, lock): - """ - Given a leader, connect and wait on data. If connection is lost, - it will attempt to reconnect. - """ - try: - url, token = leader["url"], leader["api_token"] - websocket_url = f"{url}?token={token}" - - logger.info(f"Attempting to connect to Leader at: {url}") - while True: - try: - async with websockets.connect(websocket_url) as ws: - channel = await self.channel_manager.on_connect(ws) - logger.info(f"Connection to Leader at {url} successful") - while True: - try: - data = await asyncio.wait_for( - channel.recv(), - timeout=self.reply_timeout - ) - except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): - # We haven't received data yet. Check the connection and continue. - try: - # ping - ping = await channel.ping() - await asyncio.wait_for(ping, timeout=self.ping_timeout) - logger.debug(f"Connection to {url} still alive...") - continue - except Exception: - logger.info( - f"Ping error {url} - retrying in {self.sleep_time}s") - asyncio.sleep(self.sleep_time) - break - - async with lock: - # Acquire lock so only 1 coro handling at a time - # as we call the RPC module in the main thread - await self._handle_leader_message(data) - - except (socket.gaierror, ConnectionRefusedError): - logger.info(f"Connection Refused - retrying connection in {self.sleep_time}s") - await asyncio.sleep(self.sleep_time) - continue - except websockets.exceptions.InvalidStatusCode as e: - logger.error(f"Connection Refused - {e}") - await asyncio.sleep(self.sleep_time) - continue - - except asyncio.CancelledError: - pass +# """ +# This module manages replicate mode communication +# """ +# import asyncio +# import logging +# import secrets +# import socket +# from threading import Thread +# from typing import Any, Callable, Coroutine, Dict, Union +# +# import websockets +# from fastapi import Depends +# from fastapi import WebSocket as FastAPIWebSocket +# from fastapi import WebSocketDisconnect, status +# from janus import Queue as ThreadedQueue +# +# from freqtrade.enums import ExternalSignalModeType, LeaderMessageType, RPCMessageType +# from freqtrade.rpc import RPC, RPCHandler +# from freqtrade.rpc.external_signal.channel import ChannelManager +# from freqtrade.rpc.external_signal.types import MessageType +# from freqtrade.rpc.external_signal.utils import is_websocket_alive +# +# +# logger = logging.getLogger(__name__) +# +# +# class ExternalSignalController(RPCHandler): +# """ This class handles all websocket communication """ +# +# def __init__( +# self, +# rpc: RPC, +# config: Dict[str, Any], +# api_server: Union[Any, None] = None +# ) -> None: +# """ +# Init the ExternalSignalController class, and init the super class RPCHandler +# :param rpc: instance of RPC Helper class +# :param config: Configuration object +# :param api_server: The ApiServer object +# :return: None +# """ +# super().__init__(rpc, config) +# +# self.freqtrade = rpc._freqtrade +# self.api_server = api_server +# +# if not self.api_server: +# raise RuntimeError("The API server must be enabled for external signals to work") +# +# self._loop = None +# self._running = False +# self._thread = None +# self._queue = None +# +# self._main_task = None +# self._sub_tasks = None +# +# self._message_handlers = { +# LeaderMessageType.pairlist: self._rpc._handle_pairlist_message, +# LeaderMessageType.analyzed_df: self._rpc._handle_analyzed_df_message, +# LeaderMessageType.default: self._rpc._handle_default_message +# } +# +# self.channel_manager = ChannelManager() +# self.external_signal_config = config.get('external_signal', {}) +# +# # What the config should look like +# # "external_signal": { +# # "enabled": true, +# # "mode": "follower", +# # "leaders": [ +# # { +# # "url": "ws://localhost:8080/signals/ws", +# # "api_token": "test" +# # } +# # ] +# # } +# +# # "external_signal": { +# # "enabled": true, +# # "mode": "leader", +# # "api_token": "test" +# # } +# +# self.mode = ExternalSignalModeType[ +# self.external_signal_config.get('mode', 'leader').lower() +# ] +# +# self.leaders_list = self.external_signal_config.get('leaders', []) +# self.push_throttle_secs = self.external_signal_config.get('push_throttle_secs', 0.1) +# +# self.reply_timeout = self.external_signal_config.get('follower_reply_timeout', 10) +# self.ping_timeout = self.external_signal_config.get('follower_ping_timeout', 2) +# self.sleep_time = self.external_signal_config.get('follower_sleep_time', 5) +# +# # Validate external_signal_config here? +# +# if self.mode == ExternalSignalModeType.follower and len(self.leaders_list) == 0: +# raise ValueError("You must specify at least 1 leader in follower mode.") +# +# # This is only used by the leader, the followers use the tokens specified +# # in each of the leaders +# # If you do not specify an API key in the config, one will be randomly +# # generated and logged on startup +# default_api_key = secrets.token_urlsafe(16) +# self.secret_api_key = self.external_signal_config.get('api_token', default_api_key) +# +# self.start() +# +# def is_leader(self): +# """ +# Leader flag +# """ +# return self.enabled() and self.mode == ExternalSignalModeType.leader +# +# def enabled(self): +# """ +# Enabled flag +# """ +# return self.external_signal_config.get('enabled', False) +# +# def num_leaders(self): +# """ +# The number of leaders we should be connected to +# """ +# return len(self.leaders_list) +# +# def start_threaded_loop(self): +# """ +# Start the main internal loop in another thread to run coroutines +# """ +# self._loop = asyncio.new_event_loop() +# +# if not self._thread: +# self._thread = Thread(target=self._loop.run_forever) +# self._thread.start() +# self._running = True +# else: +# raise RuntimeError("A loop is already running") +# +# def submit_coroutine(self, coroutine: Coroutine): +# """ +# Submit a coroutine to the threaded loop +# """ +# if not self._running: +# raise RuntimeError("Cannot schedule new futures after shutdown") +# +# if not self._loop or not self._loop.is_running(): +# raise RuntimeError("Loop must be started before any function can" +# " be submitted") +# +# return asyncio.run_coroutine_threadsafe(coroutine, self._loop) +# +# def start(self): +# """ +# Start the controller main loop +# """ +# self.start_threaded_loop() +# self._main_task = self.submit_coroutine(self.main()) +# +# async def shutdown(self): +# """ +# Shutdown all tasks and close up +# """ +# logger.info("Stopping rpc.externalsignalcontroller") +# +# # Flip running flag +# self._running = False +# +# # Cancel sub tasks +# for task in self._sub_tasks: +# task.cancel() +# +# # Then disconnect all channels +# await self.channel_manager.disconnect_all() +# +# def cleanup(self) -> None: +# """ +# Cleanup pending module resources. +# """ +# if self._thread: +# if self._loop.is_running(): +# self._main_task.cancel() +# self._thread.join() +# +# async def main(self): +# """ +# Main coro +# +# Start the loop based on what mode we're in +# """ +# try: +# if self.mode == ExternalSignalModeType.leader: +# logger.info("Starting rpc.externalsignalcontroller in Leader mode") +# +# await self.run_leader_mode() +# elif self.mode == ExternalSignalModeType.follower: +# logger.info("Starting rpc.externalsignalcontroller in Follower mode") +# +# await self.run_follower_mode() +# +# except asyncio.CancelledError: +# # We're cancelled +# await self.shutdown() +# except Exception as e: +# # Log the error +# logger.error(f"Exception occurred in main task: {e}") +# logger.exception(e) +# finally: +# # This coroutine is the last thing to be ended, so it should stop the loop +# self._loop.stop() +# +# def log_api_token(self): +# """ +# Log the API token +# """ +# logger.info("-" * 15) +# logger.info(f"API_KEY: {self.secret_api_key}") +# logger.info("-" * 15) +# +# def send_msg(self, msg: MessageType) -> None: +# """ +# Support RPC calls +# """ +# if msg["type"] == RPCMessageType.EMIT_DATA: +# message = msg.get("message") +# if message: +# self.send_message(message) +# else: +# logger.error(f"Message is empty! {msg}") +# +# def send_message(self, msg: MessageType) -> None: +# """ +# Broadcast message over all channels if there are any +# """ +# +# if self.channel_manager.has_channels(): +# self._send_message(msg) +# else: +# logger.debug("No listening followers, skipping...") +# pass +# +# def _send_message(self, msg: MessageType): +# """ +# Add data to the internal queue to be broadcasted. This func will block +# if the queue is full. This is meant to be called in the main thread. +# """ +# if self._queue: +# queue = self._queue.sync_q +# queue.put(msg) # This will block if the queue is full +# else: +# logger.warning("Can not send data, leader loop has not started yet!") +# +# async def send_initial_data(self, channel): +# logger.info("Sending initial data through channel") +# +# data = self._rpc._initial_leader_data() +# +# for message in data: +# await channel.send(message) +# +# async def _handle_leader_message(self, message: MessageType): +# """ +# Handle message received from a Leader +# """ +# type = message.get("data_type", LeaderMessageType.default) +# data = message.get("data") +# +# handler: Callable = self._message_handlers[type] +# handler(type, data) +# +# # ---------------------------------------------------------------------- +# +# async def run_leader_mode(self): +# """ +# Main leader coroutine +# +# This starts all of the leader coros and registers the endpoint on +# the ApiServer +# """ +# self.register_leader_endpoint() +# self.log_api_token() +# +# self._sub_tasks = [ +# self._loop.create_task(self._broadcast_queue_data()) +# ] +# +# return await asyncio.gather(*self._sub_tasks) +# +# async def run_follower_mode(self): +# """ +# Main follower coroutine +# +# This starts all of the follower connection coros +# """ +# +# rpc_lock = asyncio.Lock() +# +# self._sub_tasks = [ +# self._loop.create_task(self._handle_leader_connection(leader, rpc_lock)) +# for leader in self.leaders_list +# ] +# +# return await asyncio.gather(*self._sub_tasks) +# +# async def _broadcast_queue_data(self): +# """ +# Loop over queue data and broadcast it +# """ +# # Instantiate the queue in this coroutine so it's attached to our loop +# self._queue = ThreadedQueue() +# async_queue = self._queue.async_q +# +# try: +# while self._running: +# # Get data from queue +# data = await async_queue.get() +# +# # Broadcast it to everyone +# await self.channel_manager.broadcast(data) +# +# # Sleep +# await asyncio.sleep(self.push_throttle_secs) +# +# except asyncio.CancelledError: +# # Silently stop +# pass +# +# async def get_api_token( +# self, +# websocket: FastAPIWebSocket, +# token: Union[str, None] = None +# ): +# """ +# Extract the API key from query param. Must match the +# set secret_api_key or the websocket connection will be closed. +# """ +# if token == self.secret_api_key: +# return token +# else: +# logger.info("Denying websocket request...") +# await websocket.close(code=status.WS_1008_POLICY_VIOLATION) +# +# def register_leader_endpoint(self, path: str = "/signals/ws"): +# """ +# Attach and start the main leader loop to the ApiServer +# +# :param path: The endpoint path +# """ +# if not self.api_server: +# raise RuntimeError("The leader needs the ApiServer to be active") +# +# # The endpoint function for running the main leader loop +# @self.api_server.app.websocket(path) +# async def leader_endpoint( +# websocket: FastAPIWebSocket, +# api_key: str = Depends(self.get_api_token) +# ): +# await self.leader_endpoint_loop(websocket) +# +# async def leader_endpoint_loop(self, websocket: FastAPIWebSocket): +# """ +# The WebSocket endpoint served by the ApiServer. This handles connections, +# and adding them to the channel manager. +# """ +# try: +# if is_websocket_alive(websocket): +# logger.info(f"Follower connected - {websocket.client}") +# channel = await self.channel_manager.on_connect(websocket) +# +# # Send initial data here +# # Data is being broadcasted right away as soon as startup, +# # we may not have to send initial data at all. Further testing +# # required. +# await self.send_initial_data(channel) +# +# # Keep connection open until explicitly closed, and sleep +# try: +# while not channel.is_closed(): +# request = await channel.recv() +# logger.info(f"Follower request - {request}") +# +# except WebSocketDisconnect: +# # Handle client disconnects +# logger.info(f"Follower disconnected - {websocket.client}") +# await self.channel_manager.on_disconnect(websocket) +# except Exception as e: +# logger.info(f"Follower connection failed - {websocket.client}") +# logger.exception(e) +# # Handle cases like - +# # RuntimeError('Cannot call "send" once a closed message has been sent') +# await self.channel_manager.on_disconnect(websocket) +# +# except Exception: +# logger.error(f"Failed to serve - {websocket.client}") +# await self.channel_manager.on_disconnect(websocket) +# +# async def _handle_leader_connection(self, leader, lock): +# """ +# Given a leader, connect and wait on data. If connection is lost, +# it will attempt to reconnect. +# """ +# try: +# url, token = leader["url"], leader["api_token"] +# websocket_url = f"{url}?token={token}" +# +# logger.info(f"Attempting to connect to Leader at: {url}") +# while True: +# try: +# async with websockets.connect(websocket_url) as ws: +# channel = await self.channel_manager.on_connect(ws) +# logger.info(f"Connection to Leader at {url} successful") +# while True: +# try: +# data = await asyncio.wait_for( +# channel.recv(), +# timeout=self.reply_timeout +# ) +# except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): +# # We haven't received data yet. Check the connection and continue. +# try: +# # ping +# ping = await channel.ping() +# await asyncio.wait_for(ping, timeout=self.ping_timeout) +# logger.debug(f"Connection to {url} still alive...") +# continue +# except Exception: +# logger.info( +# f"Ping error {url} - retrying in {self.sleep_time}s") +# asyncio.sleep(self.sleep_time) +# break +# +# async with lock: +# # Acquire lock so only 1 coro handling at a time +# # as we call the RPC module in the main thread +# await self._handle_leader_message(data) +# +# except (socket.gaierror, ConnectionRefusedError): +# logger.info(f"Connection Refused - retrying connection in {self.sleep_time}s") +# await asyncio.sleep(self.sleep_time) +# continue +# except websockets.exceptions.InvalidStatusCode as e: +# logger.error(f"Connection Refused - {e}") +# await asyncio.sleep(self.sleep_time) +# continue +# +# except asyncio.CancelledError: +# pass diff --git a/freqtrade/rpc/external_signal/proxy.py b/freqtrade/rpc/external_signal/proxy.py index 36ff4a74e..df2a07da0 100644 --- a/freqtrade/rpc/external_signal/proxy.py +++ b/freqtrade/rpc/external_signal/proxy.py @@ -1,61 +1,61 @@ -from typing import Union - -from fastapi import WebSocket as FastAPIWebSocket -from websockets import WebSocketClientProtocol as WebSocket - -from freqtrade.rpc.external_signal.types import WebSocketType - - -class WebSocketProxy: - """ - WebSocketProxy object to bring the FastAPIWebSocket and websockets.WebSocketClientProtocol - under the same API - """ - - def __init__(self, websocket: WebSocketType): - self._websocket: Union[FastAPIWebSocket, WebSocket] = websocket - - async def send(self, data): - """ - Send data on the wrapped websocket - """ - if isinstance(data, str): - data = data.encode() - - if hasattr(self._websocket, "send_bytes"): - await self._websocket.send_bytes(data) - else: - await self._websocket.send(data) - - async def recv(self): - """ - Receive data on the wrapped websocket - """ - if hasattr(self._websocket, "receive_bytes"): - return await self._websocket.receive_bytes() - else: - return await self._websocket.recv() - - async def ping(self): - """ - Ping the websocket, not supported by FastAPI WebSockets - """ - if hasattr(self._websocket, "ping"): - return await self._websocket.ping() - return False - - async def close(self, code: int = 1000): - """ - Close the websocket connection, only supported by FastAPI WebSockets - """ - if hasattr(self._websocket, "close"): - return await self._websocket.close(code) - pass - - async def accept(self): - """ - Accept the WebSocket connection, only support by FastAPI WebSockets - """ - if hasattr(self._websocket, "accept"): - return await self._websocket.accept() - pass +# from typing import Union +# +# from fastapi import WebSocket as FastAPIWebSocket +# from websockets import WebSocketClientProtocol as WebSocket +# +# from freqtrade.rpc.external_signal.types import WebSocketType +# +# +# class WebSocketProxy: +# """ +# WebSocketProxy object to bring the FastAPIWebSocket and websockets.WebSocketClientProtocol +# under the same API +# """ +# +# def __init__(self, websocket: WebSocketType): +# self._websocket: Union[FastAPIWebSocket, WebSocket] = websocket +# +# async def send(self, data): +# """ +# Send data on the wrapped websocket +# """ +# if isinstance(data, str): +# data = data.encode() +# +# if hasattr(self._websocket, "send_bytes"): +# await self._websocket.send_bytes(data) +# else: +# await self._websocket.send(data) +# +# async def recv(self): +# """ +# Receive data on the wrapped websocket +# """ +# if hasattr(self._websocket, "receive_bytes"): +# return await self._websocket.receive_bytes() +# else: +# return await self._websocket.recv() +# +# async def ping(self): +# """ +# Ping the websocket, not supported by FastAPI WebSockets +# """ +# if hasattr(self._websocket, "ping"): +# return await self._websocket.ping() +# return False +# +# async def close(self, code: int = 1000): +# """ +# Close the websocket connection, only supported by FastAPI WebSockets +# """ +# if hasattr(self._websocket, "close"): +# return await self._websocket.close(code) +# pass +# +# async def accept(self): +# """ +# Accept the WebSocket connection, only support by FastAPI WebSockets +# """ +# if hasattr(self._websocket, "accept"): +# return await self._websocket.accept() +# pass diff --git a/freqtrade/rpc/external_signal/serializer.py b/freqtrade/rpc/external_signal/serializer.py index 2a0f53037..a23469ef4 100644 --- a/freqtrade/rpc/external_signal/serializer.py +++ b/freqtrade/rpc/external_signal/serializer.py @@ -1,65 +1,65 @@ -import json -import logging -from abc import ABC, abstractmethod - -import msgpack -import orjson - -from freqtrade.rpc.external_signal.proxy import WebSocketProxy - - -logger = logging.getLogger(__name__) - - -class WebSocketSerializer(ABC): - def __init__(self, websocket: WebSocketProxy): - self._websocket: WebSocketProxy = websocket - - @abstractmethod - def _serialize(self, data): - raise NotImplementedError() - - @abstractmethod - def _deserialize(self, data): - raise NotImplementedError() - - async def send(self, data: bytes): - await self._websocket.send(self._serialize(data)) - - async def recv(self) -> bytes: - data = await self._websocket.recv() - - return self._deserialize(data) - - async def close(self, code: int = 1000): - await self._websocket.close(code) - -# Going to explore using MsgPack as the serialization, -# as that might be the best method for sending pandas -# dataframes over the wire - - -class JSONWebSocketSerializer(WebSocketSerializer): - def _serialize(self, data): - return json.dumps(data) - - def _deserialize(self, data): - return json.loads(data) - - -class ORJSONWebSocketSerializer(WebSocketSerializer): - ORJSON_OPTIONS = orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY - - def _serialize(self, data): - return orjson.dumps(data, option=self.ORJSON_OPTIONS) - - def _deserialize(self, data): - return orjson.loads(data, option=self.ORJSON_OPTIONS) - - -class MsgPackWebSocketSerializer(WebSocketSerializer): - def _serialize(self, data): - return msgpack.packb(data, use_bin_type=True) - - def _deserialize(self, data): - return msgpack.unpackb(data, raw=False) +# import json +# import logging +# from abc import ABC, abstractmethod +# +# import msgpack +# import orjson +# +# from freqtrade.rpc.external_signal.proxy import WebSocketProxy +# +# +# logger = logging.getLogger(__name__) +# +# +# class WebSocketSerializer(ABC): +# def __init__(self, websocket: WebSocketProxy): +# self._websocket: WebSocketProxy = websocket +# +# @abstractmethod +# def _serialize(self, data): +# raise NotImplementedError() +# +# @abstractmethod +# def _deserialize(self, data): +# raise NotImplementedError() +# +# async def send(self, data: bytes): +# await self._websocket.send(self._serialize(data)) +# +# async def recv(self) -> bytes: +# data = await self._websocket.recv() +# +# return self._deserialize(data) +# +# async def close(self, code: int = 1000): +# await self._websocket.close(code) +# +# # Going to explore using MsgPack as the serialization, +# # as that might be the best method for sending pandas +# # dataframes over the wire +# +# +# class JSONWebSocketSerializer(WebSocketSerializer): +# def _serialize(self, data): +# return json.dumps(data) +# +# def _deserialize(self, data): +# return json.loads(data) +# +# +# class ORJSONWebSocketSerializer(WebSocketSerializer): +# ORJSON_OPTIONS = orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY +# +# def _serialize(self, data): +# return orjson.dumps(data, option=self.ORJSON_OPTIONS) +# +# def _deserialize(self, data): +# return orjson.loads(data, option=self.ORJSON_OPTIONS) +# +# +# class MsgPackWebSocketSerializer(WebSocketSerializer): +# def _serialize(self, data): +# return msgpack.packb(data, use_bin_type=True) +# +# def _deserialize(self, data): +# return msgpack.unpackb(data, raw=False) diff --git a/freqtrade/rpc/external_signal/types.py b/freqtrade/rpc/external_signal/types.py index 814fe6649..38e43f667 100644 --- a/freqtrade/rpc/external_signal/types.py +++ b/freqtrade/rpc/external_signal/types.py @@ -1,8 +1,8 @@ -from typing import Any, Dict, TypeVar - -from fastapi import WebSocket as FastAPIWebSocket -from websockets import WebSocketClientProtocol as WebSocket - - -WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket) -MessageType = Dict[str, Any] +# from typing import Any, Dict, TypeVar +# +# from fastapi import WebSocket as FastAPIWebSocket +# from websockets import WebSocketClientProtocol as WebSocket +# +# +# WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket) +# MessageType = Dict[str, Any] diff --git a/freqtrade/rpc/external_signal/utils.py b/freqtrade/rpc/external_signal/utils.py index e5469dce3..72c8d2ef8 100644 --- a/freqtrade/rpc/external_signal/utils.py +++ b/freqtrade/rpc/external_signal/utils.py @@ -1,22 +1,10 @@ -from pandas import DataFrame -from starlette.websockets import WebSocket, WebSocketState - -from freqtrade.enums.signaltype import SignalTagType, SignalType - - -async def is_websocket_alive(ws: WebSocket) -> bool: - if ( - ws.application_state == WebSocketState.CONNECTED and - ws.client_state == WebSocketState.CONNECTED - ): - return True - return False - - -def remove_entry_exit_signals(dataframe: DataFrame): - dataframe[SignalType.ENTER_LONG.value] = 0 - dataframe[SignalType.EXIT_LONG.value] = 0 - dataframe[SignalType.ENTER_SHORT.value] = 0 - dataframe[SignalType.EXIT_SHORT.value] = 0 - dataframe[SignalTagType.ENTER_TAG.value] = None - dataframe[SignalTagType.EXIT_TAG.value] = None +# from starlette.websockets import WebSocket, WebSocketState +# +# +# async def is_websocket_alive(ws: WebSocket) -> bool: +# if ( +# ws.application_state == WebSocketState.CONNECTED and +# ws.client_state == WebSocketState.CONNECTED +# ): +# return True +# return False diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 82d50f33c..3c7558158 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -19,13 +19,12 @@ from freqtrade.configuration.timerange import TimeRange from freqtrade.constants import CANCEL_REASON, DATETIME_PRINT_FORMAT from freqtrade.data.history import load_data from freqtrade.data.metrics import calculate_max_drawdown -from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, LeaderMessageType, - SignalDirection, State, TradingMode) +from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirection, State, + TradingMode) from freqtrade.exceptions import ExchangeError, PricingError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs from freqtrade.loggers import bufferHandler -from freqtrade.misc import (decimals_per_coin, json_to_dataframe, remove_entry_exit_signals, - shorten_date) +from freqtrade.misc import decimals_per_coin, shorten_date from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence.models import PairLock from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist @@ -1090,65 +1089,65 @@ class RPC: 'last_process_loc': last_p.astimezone(tzlocal()).strftime(DATETIME_PRINT_FORMAT), 'last_process_ts': int(last_p.timestamp()), } - - # ------------------------------ EXTERNAL SIGNALS ----------------------- - - def _initial_leader_data(self): - # We create a list of Messages to send to the follower on connect - data = [] - - # Send Pairlist data - data.append({ - "data_type": LeaderMessageType.pairlist, - "data": self._freqtrade.pairlists._whitelist - }) - - return data - - def _handle_pairlist_message(self, type, data): - """ - Handles the emitted pairlists from the Leaders - - :param type: The data_type of the data - :param data: The data - """ - pairlist = data - - logger.debug(f"Handling Pairlist message: {pairlist}") - - external_pairlist = self._freqtrade.pairlists._pairlist_handlers[0] - external_pairlist.add_pairlist_data(pairlist) - - def _handle_analyzed_df_message(self, type, data): - """ - Handles the analyzed dataframes from the Leaders - - :param type: The data_type of the data - :param data: The data - """ - key, value = data["key"], data["value"] - pair, timeframe, candle_type = key - - # Skip any pairs that we don't have in the pairlist? - # leader_pairlist = self._freqtrade.pairlists._whitelist - # if pair not in leader_pairlist: - # return - - dataframe = json_to_dataframe(value) - - if self._config.get('external_signal', {}).get('remove_signals_analyzed_df', False): - dataframe = remove_entry_exit_signals(dataframe) - - logger.debug(f"Handling analyzed dataframe for {pair}") - logger.debug(dataframe.tail()) - - # Add the dataframe to the dataprovider - dataprovider = self._freqtrade.dataprovider - dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) - - def _handle_default_message(self, type, data): - """ - Default leader message handler, just logs it. We should never have to - run this unless the leader sends us some weird message. - """ - logger.debug(f"Received message from Leader of type {type}: {data}") + # + # # ------------------------------ EXTERNAL SIGNALS ----------------------- + # + # def _initial_leader_data(self): + # # We create a list of Messages to send to the follower on connect + # data = [] + # + # # Send Pairlist data + # data.append({ + # "data_type": LeaderMessageType.pairlist, + # "data": self._freqtrade.pairlists._whitelist + # }) + # + # return data + # + # def _handle_pairlist_message(self, type, data): + # """ + # Handles the emitted pairlists from the Leaders + # + # :param type: The data_type of the data + # :param data: The data + # """ + # pairlist = data + # + # logger.debug(f"Handling Pairlist message: {pairlist}") + # + # external_pairlist = self._freqtrade.pairlists._pairlist_handlers[0] + # external_pairlist.add_pairlist_data(pairlist) + # + # def _handle_analyzed_df_message(self, type, data): + # """ + # Handles the analyzed dataframes from the Leaders + # + # :param type: The data_type of the data + # :param data: The data + # """ + # key, value = data["key"], data["value"] + # pair, timeframe, candle_type = key + # + # # Skip any pairs that we don't have in the pairlist? + # # leader_pairlist = self._freqtrade.pairlists._whitelist + # # if pair not in leader_pairlist: + # # return + # + # dataframe = json_to_dataframe(value) + # + # if self._config.get('external_signal', {}).get('remove_signals_analyzed_df', False): + # dataframe = remove_entry_exit_signals(dataframe) + # + # logger.debug(f"Handling analyzed dataframe for {pair}") + # logger.debug(dataframe.tail()) + # + # # Add the dataframe to the dataprovider + # dataprovider = self._freqtrade.dataprovider + # dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) + # + # def _handle_default_message(self, type, data): + # """ + # Default leader message handler, just logs it. We should never have to + # run this unless the leader sends us some weird message. + # """ + # logger.debug(f"Received message from Leader of type {type}: {data}") diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 11e21da6f..c5e93e3b4 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -51,14 +51,14 @@ class RPCManager: # Enable External Signals mode # For this to be enabled, the API server must also be enabled - if config.get('external_signal', {}).get('enabled', False): - logger.info('Enabling RPC.ExternalSignalController') - from freqtrade.rpc.external_signal import ExternalSignalController - external_signals = ExternalSignalController(self._rpc, config, apiserver) - self.registered_modules.append(external_signals) - - # Attach the controller to FreqTrade - freqtrade.external_signal_controller = external_signals + # if config.get('external_signal', {}).get('enabled', False): + # logger.info('Enabling RPC.ExternalSignalController') + # from freqtrade.rpc.external_signal import ExternalSignalController + # external_signals = ExternalSignalController(self._rpc, config, apiserver) + # self.registered_modules.append(external_signals) + # + # # Attach the controller to FreqTrade + # freqtrade.external_signal_controller = external_signals def cleanup(self) -> None: """ Stops all enabled rpc modules """ @@ -78,8 +78,7 @@ class RPCManager: 'status': 'stopping bot' } """ - if msg.get("type") != RPCMessageType.EMIT_DATA: - logger.info('Sending rpc message: %s', msg) + logger.info('Sending rpc message: %s', msg) if 'pair' in msg: msg.update({ 'base_currency': self._rpc._freqtrade.exchange.get_pair_base_currency(msg['pair']) @@ -138,12 +137,3 @@ class RPCManager: 'type': RPCMessageType.STARTUP, 'status': f'Using Protections: \n{prots}' }) - - def emit_data(self, data: Dict[str, Any]): - """ - Send a message via RPC with type RPCMessageType.EMIT_DATA - """ - self.send_msg({ - "type": RPCMessageType.EMIT_DATA, - "message": data - }) diff --git a/scripts/test_ws_client.py b/scripts/test_ws_client.py new file mode 100644 index 000000000..caa495a19 --- /dev/null +++ b/scripts/test_ws_client.py @@ -0,0 +1,58 @@ +import asyncio +import logging +import socket + +import websockets + + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + + +async def _client(): + try: + while True: + try: + url = "ws://localhost:8080/api/v1/message/ws?token=testtoken" + async with websockets.connect(url) as ws: + logger.info("Connection successful") + while True: + try: + data = await asyncio.wait_for( + ws.recv(), + timeout=5 + ) + logger.info(f"Data received - {data}") + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): + # We haven't received data yet. Check the connection and continue. + try: + # ping + ping = await ws.ping() + await asyncio.wait_for(ping, timeout=2) + logger.debug(f"Connection to {url} still alive...") + continue + except Exception: + logger.info( + f"Ping error {url} - retrying in 5s") + asyncio.sleep(2) + break + + except (socket.gaierror, ConnectionRefusedError): + logger.info("Connection Refused - retrying connection in 5s") + await asyncio.sleep(2) + continue + except websockets.exceptions.InvalidStatusCode as e: + logger.error(f"Connection Refused - {e}") + await asyncio.sleep(2) + continue + + except (asyncio.CancelledError, KeyboardInterrupt): + pass + + +def main(): + asyncio.run(_client()) + + +if __name__ == "__main__": + main() From 47f7c384fbea381926a3b9aad0c6c99935b5e8d2 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 29 Aug 2022 15:48:29 -0600 Subject: [PATCH 015/115] consumer subscriptions, fix serializer bug --- freqtrade/rpc/api_server/api_ws.py | 11 +++++++- freqtrade/rpc/api_server/ws/__init__.py | 0 freqtrade/rpc/api_server/ws/channel.py | 31 ++++++++++++++++++++--- freqtrade/rpc/api_server/ws/serializer.py | 2 +- scripts/test_ws_client.py | 15 ++++++++--- 5 files changed, 50 insertions(+), 9 deletions(-) create mode 100644 freqtrade/rpc/api_server/ws/__init__.py diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 464ea22b2..405beed79 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -2,6 +2,7 @@ import logging from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect +from freqtrade.enums import RPCMessageType from freqtrade.rpc.api_server.deps import get_channel_manager from freqtrade.rpc.api_server.ws.utils import is_websocket_alive @@ -34,7 +35,15 @@ async def message_endpoint( # be a list of topics to subscribe too. List[str] # Maybe allow the consumer to update the topics subscribed # during runtime? - logger.info(f"Consumer request - {request}") + + # If the request isn't a list then skip it + if not isinstance(request, list): + continue + + # Check if all topics listed are an RPCMessageType + if all([any(x.value == topic for x in RPCMessageType) for topic in request]): + logger.debug(f"{ws.client} subscribed to topics: {request}") + channel.set_subscriptions(request) except WebSocketDisconnect: # Handle client disconnects diff --git a/freqtrade/rpc/api_server/ws/__init__.py b/freqtrade/rpc/api_server/ws/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index 486e8657b..f24713a77 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -1,6 +1,6 @@ import logging from threading import RLock -from typing import Type +from typing import List, Type from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy from freqtrade.rpc.api_server.ws.serializer import ORJSONWebSocketSerializer, WebSocketSerializer @@ -25,6 +25,8 @@ class WebSocketChannel: # The Serializing class for the WebSocket object self._serializer_cls = serializer_cls + self._subscriptions: List[str] = [] + # Internal event to signify a closed websocket self._closed = False @@ -57,9 +59,28 @@ class WebSocketChannel: self._closed = True - def is_closed(self): + def is_closed(self) -> bool: + """ + Closed flag + """ return self._closed + def set_subscriptions(self, subscriptions: List[str] = []) -> None: + """ + Set which subscriptions this channel is subscribed to + + :param subscriptions: List of subscriptions, List[str] + """ + self._subscriptions = subscriptions + + def subscribed_to(self, message_type: str) -> bool: + """ + Check if this channel is subscribed to the message_type + + :param message_type: The message type to check + """ + return message_type in self._subscriptions + class ChannelManager: def __init__(self): @@ -120,10 +141,12 @@ class ChannelManager: :param data: The data to send """ with self._lock: - logger.debug(f"Broadcasting data: {data}") + message_type = data.get('type') + logger.debug(f"Broadcasting data: {message_type} - {data}") for websocket, channel in self.channels.items(): try: - await channel.send(data) + if channel.subscribed_to(message_type): + await channel.send(data) except RuntimeError: # Handle cannot send after close cases await self.on_disconnect(websocket) diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py index 40cbbfad7..ae2857f0b 100644 --- a/freqtrade/rpc/api_server/ws/serializer.py +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -54,7 +54,7 @@ class ORJSONWebSocketSerializer(WebSocketSerializer): return orjson.dumps(data, option=self.ORJSON_OPTIONS) def _deserialize(self, data): - return orjson.loads(data, option=self.ORJSON_OPTIONS) + return orjson.loads(data) class MsgPackWebSocketSerializer(WebSocketSerializer): diff --git a/scripts/test_ws_client.py b/scripts/test_ws_client.py index caa495a19..2c64ae867 100644 --- a/scripts/test_ws_client.py +++ b/scripts/test_ws_client.py @@ -4,22 +4,31 @@ import socket import websockets +from freqtrade.enums import RPCMessageType +from freqtrade.rpc.api_server.ws.channel import WebSocketChannel + logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def _client(): + subscribe_topics = [RPCMessageType.WHITELIST] try: while True: try: url = "ws://localhost:8080/api/v1/message/ws?token=testtoken" async with websockets.connect(url) as ws: + channel = WebSocketChannel(ws) + logger.info("Connection successful") + # Tell the producer we only want these topics + await channel.send(subscribe_topics) + while True: try: data = await asyncio.wait_for( - ws.recv(), + channel.recv(), timeout=5 ) logger.info(f"Data received - {data}") @@ -27,14 +36,14 @@ async def _client(): # We haven't received data yet. Check the connection and continue. try: # ping - ping = await ws.ping() + ping = await channel.ping() await asyncio.wait_for(ping, timeout=2) logger.debug(f"Connection to {url} still alive...") continue except Exception: logger.info( f"Ping error {url} - retrying in 5s") - asyncio.sleep(2) + await asyncio.sleep(2) break except (socket.gaierror, ConnectionRefusedError): From 418bd26a8097008ccb5ef747cc63ea087fadfea4 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 30 Aug 2022 11:04:16 -0600 Subject: [PATCH 016/115] minor fixes, rework consumer request, update requirements.txt --- freqtrade/enums/__init__.py | 2 +- freqtrade/enums/rpcmessagetype.py | 6 ++++++ freqtrade/rpc/api_server/api_ws.py | 23 +++++++---------------- freqtrade/rpc/api_server/webserver.py | 6 +----- freqtrade/rpc/rpc.py | 14 ++++++++++++-- freqtrade/rpc/rpc_manager.py | 2 +- freqtrade/rpc/telegram.py | 10 +++++++--- requirements-externalsignals.txt | 7 ------- requirements.txt | 5 +++++ scripts/test_ws_client.py | 11 +++++++++-- setup.py | 5 ++++- 11 files changed, 53 insertions(+), 38 deletions(-) delete mode 100644 requirements-externalsignals.txt diff --git a/freqtrade/enums/__init__.py b/freqtrade/enums/__init__.py index ffeb8cc12..406d847e6 100644 --- a/freqtrade/enums/__init__.py +++ b/freqtrade/enums/__init__.py @@ -6,7 +6,7 @@ from freqtrade.enums.exittype import ExitType from freqtrade.enums.externalsignal import ExternalSignalModeType, LeaderMessageType, WaitDataPolicy from freqtrade.enums.marginmode import MarginMode from freqtrade.enums.ordertypevalue import OrderTypeValues -from freqtrade.enums.rpcmessagetype import RPCMessageType +from freqtrade.enums.rpcmessagetype import RPCMessageType, RPCRequestType from freqtrade.enums.runmode import NON_UTIL_MODES, OPTIMIZE_MODES, TRADING_MODES, RunMode from freqtrade.enums.signaltype import SignalDirection, SignalTagType, SignalType from freqtrade.enums.state import State diff --git a/freqtrade/enums/rpcmessagetype.py b/freqtrade/enums/rpcmessagetype.py index 8e4182b33..6283fb7cc 100644 --- a/freqtrade/enums/rpcmessagetype.py +++ b/freqtrade/enums/rpcmessagetype.py @@ -21,9 +21,15 @@ class RPCMessageType(str, Enum): STRATEGY_MSG = 'strategy_msg' WHITELIST = 'whitelist' + ANALYZED_DF = 'analyzed_df' def __repr__(self): return self.value def __str__(self): return self.value + + +# Enum for parsing requests from ws consumers +class RPCRequestType(str, Enum): + SUBSCRIBE = 'subscribe' diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 405beed79..c8d1b70fa 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -2,8 +2,7 @@ import logging from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect -from freqtrade.enums import RPCMessageType -from freqtrade.rpc.api_server.deps import get_channel_manager +from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc_optional from freqtrade.rpc.api_server.ws.utils import is_websocket_alive @@ -16,7 +15,8 @@ router = APIRouter() @router.websocket("/message/ws") async def message_endpoint( ws: WebSocket, - channel_manager=Depends(get_channel_manager) + channel_manager=Depends(get_channel_manager), + rpc=Depends(get_rpc_optional) ): try: if is_websocket_alive(ws): @@ -31,19 +31,10 @@ async def message_endpoint( while not channel.is_closed(): request = await channel.recv() - # This is where we'd parse the request. For now this should only - # be a list of topics to subscribe too. List[str] - # Maybe allow the consumer to update the topics subscribed - # during runtime? - - # If the request isn't a list then skip it - if not isinstance(request, list): - continue - - # Check if all topics listed are an RPCMessageType - if all([any(x.value == topic for x in RPCMessageType) for topic in request]): - logger.debug(f"{ws.client} subscribed to topics: {request}") - channel.set_subscriptions(request) + # Process the request here. Should this be a method of RPC? + if rpc: + logger.info(f"Request: {request}") + rpc._process_consumer_request(request, channel) except WebSocketDisconnect: # Handle client disconnects diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 94cb8cd45..f4af8c8ed 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -63,11 +63,7 @@ class ApiServer(RPCHandler): ApiServer.__initialized = False return ApiServer.__instance - def __init__( - self, - config: Dict[str, Any], - standalone: bool = False, - ) -> None: + def __init__(self, config: Dict[str, Any], standalone: bool = False) -> None: ApiServer._config = config if self.__initialized and (standalone or self._standalone): return diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 3c7558158..f684c7783 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -19,8 +19,8 @@ from freqtrade.configuration.timerange import TimeRange from freqtrade.constants import CANCEL_REASON, DATETIME_PRINT_FORMAT from freqtrade.data.history import load_data from freqtrade.data.metrics import calculate_max_drawdown -from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirection, State, - TradingMode) +from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, RPCMessageType, RPCRequestType, + SignalDirection, State, TradingMode) from freqtrade.exceptions import ExchangeError, PricingError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs from freqtrade.loggers import bufferHandler @@ -1089,6 +1089,16 @@ class RPC: 'last_process_loc': last_p.astimezone(tzlocal()).strftime(DATETIME_PRINT_FORMAT), 'last_process_ts': int(last_p.timestamp()), } + + # We are passed a Channel object, we can only do sync functions on that channel object + def _process_consumer_request(self, request, channel): + # Should we ensure that request is Dict[str, Any]? + type, data = request.get('type'), request.get('data') + + if type == RPCRequestType.SUBSCRIBE: + if all([any(x.value == topic for x in RPCMessageType) for topic in data]): + logger.debug(f"{channel} subscribed to topics: {data}") + channel.set_subscriptions(data) # # # ------------------------------ EXTERNAL SIGNALS ----------------------- # diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index c5e93e3b4..b3cd5604c 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -64,7 +64,7 @@ class RPCManager: """ Stops all enabled rpc modules """ logger.info('Cleaning up rpc modules ...') while self.registered_modules: - mod = self.registered_modules.pop() + mod = self.registered_modules.pop() # popleft to cleanup API server last? logger.info('Cleaning up rpc.%s ...', mod.name) mod.cleanup() del mod diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 8ce2fa2e4..141368769 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -436,9 +436,13 @@ class Telegram(RPCHandler): # Notification disabled return - message = self.compose_message(msg, msg_type) - - self._send_msg(message, disable_notification=(noti == 'silent')) + # Would this be better than adding un-needed if statements to compose_message? + try: + message = self.compose_message(msg, msg_type) + self._send_msg(message, disable_notification=(noti == 'silent')) + except NotImplementedError: + # just skip it + return def _get_sell_emoji(self, msg): """ diff --git a/requirements-externalsignals.txt b/requirements-externalsignals.txt deleted file mode 100644 index 7920b34f6..000000000 --- a/requirements-externalsignals.txt +++ /dev/null @@ -1,7 +0,0 @@ -# Include all requirements to run the bot. --r requirements.txt - -# Required for follower -websockets -msgpack -janus diff --git a/requirements.txt b/requirements.txt index 77925f98b..4d97f500a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -50,3 +50,8 @@ python-dateutil==2.8.2 #Futures schedule==1.1.0 + +#WS Messages +websockets~=10.3 +msgpack~=1.0.4 +janus==1.0.0 diff --git a/scripts/test_ws_client.py b/scripts/test_ws_client.py index 2c64ae867..872ff3ccf 100644 --- a/scripts/test_ws_client.py +++ b/scripts/test_ws_client.py @@ -1,6 +1,7 @@ import asyncio import logging import socket +from typing import Any import websockets @@ -12,8 +13,14 @@ logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) +def compose_consumer_request(type_: str, data: Any): + return {"type": type_, "data": data} + + async def _client(): - subscribe_topics = [RPCMessageType.WHITELIST] + # Trying to recreate multiple topic issue. Wait until first whitelist message, + # then CTRL-C to get the status message. + topics = [RPCMessageType.WHITELIST, RPCMessageType.STATUS] try: while True: try: @@ -23,7 +30,7 @@ async def _client(): logger.info("Connection successful") # Tell the producer we only want these topics - await channel.send(subscribe_topics) + await channel.send(compose_consumer_request("subscribe", topics)) while True: try: diff --git a/setup.py b/setup.py index 8f04e75f7..c7b1f1c7c 100644 --- a/setup.py +++ b/setup.py @@ -79,7 +79,10 @@ setup( 'psutil', 'pyjwt', 'aiofiles', - 'schedule' + 'schedule', + 'websockets', + 'msgpack', + 'janus' ], extras_require={ 'dev': all_extra, From 346e73dd75503f9170d6f6759a517d0f421e6fc6 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 30 Aug 2022 19:21:34 -0600 Subject: [PATCH 017/115] client implementation, minor fixes --- config_examples/config_full.example.json | 13 +- freqtrade/constants.py | 26 +- freqtrade/data/dataprovider.py | 10 +- freqtrade/enums/__init__.py | 2 +- freqtrade/enums/externalmessages.py | 7 + freqtrade/enums/externalsignal.py | 18 - freqtrade/freqtradebot.py | 17 +- freqtrade/rpc/api_server/api_ws.py | 2 +- freqtrade/rpc/api_server/webserver.py | 29 +- freqtrade/rpc/api_server/ws/channel.py | 3 - freqtrade/rpc/emc.py | 229 ++++++++++ freqtrade/rpc/external_signal/__init__.py | 5 - freqtrade/rpc/external_signal/channel.py | 145 ------- freqtrade/rpc/external_signal/controller.py | 449 -------------------- freqtrade/rpc/external_signal/proxy.py | 61 --- freqtrade/rpc/external_signal/serializer.py | 65 --- freqtrade/rpc/external_signal/types.py | 8 - freqtrade/rpc/external_signal/utils.py | 10 - freqtrade/rpc/rpc.py | 62 --- freqtrade/rpc/rpc_manager.py | 4 +- freqtrade/strategy/interface.py | 43 +- scripts/test_ws_client.py | 74 ---- 22 files changed, 323 insertions(+), 959 deletions(-) create mode 100644 freqtrade/enums/externalmessages.py delete mode 100644 freqtrade/enums/externalsignal.py create mode 100644 freqtrade/rpc/emc.py delete mode 100644 freqtrade/rpc/external_signal/__init__.py delete mode 100644 freqtrade/rpc/external_signal/channel.py delete mode 100644 freqtrade/rpc/external_signal/controller.py delete mode 100644 freqtrade/rpc/external_signal/proxy.py delete mode 100644 freqtrade/rpc/external_signal/serializer.py delete mode 100644 freqtrade/rpc/external_signal/types.py delete mode 100644 freqtrade/rpc/external_signal/utils.py delete mode 100644 scripts/test_ws_client.py diff --git a/config_examples/config_full.example.json b/config_examples/config_full.example.json index 74457d2b6..ec988687f 100644 --- a/config_examples/config_full.example.json +++ b/config_examples/config_full.example.json @@ -172,7 +172,18 @@ "jwt_secret_key": "somethingrandom", "CORS_origins": [], "username": "freqtrader", - "password": "SuperSecurePassword" + "password": "SuperSecurePassword", + "ws_token": "a_secret_ws_token", + "enable_message_ws": false + }, + "external_message_consumer": { + "enabled": false, + "producers": [ + { + "url": "ws://some.freqtrade.bot/api/v1/message/ws", + "ws_token": "a_secret_ws_token" + } + ] }, "bot_name": "freqtrade", "db_url": "sqlite:///tradesv3.sqlite", diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 96f8413b0..c7f2acc84 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -61,7 +61,6 @@ USERPATH_FREQAIMODELS = 'freqaimodels' TELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent'] WEBHOOK_FORMAT_OPTIONS = ['form', 'json', 'raw'] -FOLLOWER_MODE_OPTIONS = ['follower', 'leader'] WAIT_DATA_POLICY_OPTIONS = ['none', 'first', 'all'] ENV_VAR_PREFIX = 'FREQTRADE__' @@ -246,7 +245,7 @@ CONF_SCHEMA = { 'exchange': {'$ref': '#/definitions/exchange'}, 'edge': {'$ref': '#/definitions/edge'}, 'freqai': {'$ref': '#/definitions/freqai'}, - 'external_signal': {'$ref': '#/definitions/external_signal'}, + 'external_message_consumer': {'$ref': '#/definitions/external_message_consumer'}, 'experimental': { 'type': 'object', 'properties': { @@ -404,7 +403,8 @@ CONF_SCHEMA = { }, 'username': {'type': 'string'}, 'password': {'type': 'string'}, - 'api_token': {'type': 'string'}, + 'ws_token': {'type': 'string'}, + 'enable_message_ws': {'type': 'boolean', 'default': False}, 'jwt_secret_key': {'type': 'string'}, 'CORS_origins': {'type': 'array', 'items': {'type': 'string'}}, 'verbosity': {'type': 'string', 'enum': ['error', 'info']}, @@ -489,35 +489,31 @@ CONF_SCHEMA = { }, 'required': ['process_throttle_secs', 'allowed_risk'] }, - 'external_signal': { + 'external_message_consumer': { 'type': 'object', 'properties': { 'enabled': {'type': 'boolean', 'default': False}, - 'mode': { - 'type': 'string', - 'enum': FOLLOWER_MODE_OPTIONS - }, - 'api_token': {'type': 'string', 'default': ''}, - 'leaders': { + 'producers': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'url': {'type': 'string', 'default': ''}, - 'api_token': {'type': 'string', 'default': ''}, + 'ws_token': {'type': 'string', 'default': ''}, } } }, - 'follower_reply_timeout': {'type': 'integer'}, - 'follower_sleep_time': {'type': 'integer'}, - 'follower_ping_timeout': {'type': 'integer'}, + 'reply_timeout': {'type': 'integer'}, + 'sleep_time': {'type': 'integer'}, + 'ping_timeout': {'type': 'integer'}, 'wait_data_policy': { 'type': 'string', 'enum': WAIT_DATA_POLICY_OPTIONS }, + 'wait_data_timeout': {'type': 'integer', 'default': 5}, 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False} }, - 'required': ['mode'] + 'required': ['producers'] }, "freqai": { "type": "object", diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index cd70db9a3..430ee0932 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -48,11 +48,13 @@ class DataProvider: self.__msg_cache = PeriodicCache( maxsize=1000, ttl=timeframe_to_seconds(self._config.get('timeframe', '1h'))) - self._num_sources = len(self._config.get('external_signal', {}).get('leader_list', [])) - self._wait_data_policy = self._config.get('external_signal', {}).get( + self._num_sources = len( + self._config.get('external_message_consumer', {}).get('producers', []) + ) + self._wait_data_policy = self._config.get('external_message_consumer', {}).get( 'wait_data_policy', WaitDataPolicy.all) - self._wait_data_timeout = self._config.get( - 'external_signal', {}).get('wait_data_timeout', 5) + self._wait_data_timeout = self._config.get('external_message_consumer', {}).get( + 'wait_data_timeout', 5) def _set_dataframe_max_index(self, limit_index: int): """ diff --git a/freqtrade/enums/__init__.py b/freqtrade/enums/__init__.py index 406d847e6..229d770ce 100644 --- a/freqtrade/enums/__init__.py +++ b/freqtrade/enums/__init__.py @@ -3,7 +3,7 @@ from freqtrade.enums.backteststate import BacktestState from freqtrade.enums.candletype import CandleType from freqtrade.enums.exitchecktuple import ExitCheckTuple from freqtrade.enums.exittype import ExitType -from freqtrade.enums.externalsignal import ExternalSignalModeType, LeaderMessageType, WaitDataPolicy +from freqtrade.enums.externalmessages import WaitDataPolicy from freqtrade.enums.marginmode import MarginMode from freqtrade.enums.ordertypevalue import OrderTypeValues from freqtrade.enums.rpcmessagetype import RPCMessageType, RPCRequestType diff --git a/freqtrade/enums/externalmessages.py b/freqtrade/enums/externalmessages.py new file mode 100644 index 000000000..e43899ab5 --- /dev/null +++ b/freqtrade/enums/externalmessages.py @@ -0,0 +1,7 @@ +from enum import Enum + + +class WaitDataPolicy(str, Enum): + none = "none" + one = "one" + all = "all" diff --git a/freqtrade/enums/externalsignal.py b/freqtrade/enums/externalsignal.py deleted file mode 100644 index 05dc604a2..000000000 --- a/freqtrade/enums/externalsignal.py +++ /dev/null @@ -1,18 +0,0 @@ -from enum import Enum - - -class ExternalSignalModeType(str, Enum): - leader = "leader" - follower = "follower" - - -class LeaderMessageType(str, Enum): - default = "default" - pairlist = "pairlist" - analyzed_df = "analyzed_df" - - -class WaitDataPolicy(str, Enum): - none = "none" - one = "one" - all = "all" diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index c9caaace6..c0d658c61 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -30,6 +30,7 @@ from freqtrade.plugins.pairlistmanager import PairListManager from freqtrade.plugins.protectionmanager import ProtectionManager from freqtrade.resolvers import ExchangeResolver, StrategyResolver from freqtrade.rpc import RPCManager +from freqtrade.rpc.emc import ExternalMessageConsumer from freqtrade.strategy.interface import IStrategy from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper from freqtrade.util import FtPrecise @@ -90,11 +91,17 @@ class FreqtradeBot(LoggingMixin): self.strategy.dp = self.dataprovider # Attach Wallets to strategy instance self.strategy.wallets = self.wallets + # Attach rpc to strategy instance + self.strategy.rpc = self.rpc # Initializing Edge only if enabled self.edge = Edge(self.config, self.exchange, self.strategy) if \ self.config.get('edge', {}).get('enabled', False) else None + # Init ExternalMessageConsumer if enabled + self.emc = ExternalMessageConsumer(self.rpc._rpc, self.config) if \ + self.config.get('external_message_consumer', {}).get('enabled', False) else None + self.active_pair_whitelist = self._refresh_active_whitelist() # Set initial bot state from config @@ -150,6 +157,8 @@ class FreqtradeBot(LoggingMixin): self.check_for_open_trades() self.rpc.cleanup() + if self.emc: + self.emc.shutdown() Trade.commit() self.exchange.close() @@ -192,7 +201,11 @@ class FreqtradeBot(LoggingMixin): strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)() - self.strategy.analyze(self.active_pair_whitelist) + if self.emc: + leader_pairs = self.pairlists._whitelist + self.strategy.analyze_external(self.active_pair_whitelist, leader_pairs) + else: + self.strategy.analyze(self.active_pair_whitelist) with self._exit_lock: # Check for exchange cancelations, timeouts and user requested replace @@ -255,7 +268,7 @@ class FreqtradeBot(LoggingMixin): self.pairlists.refresh_pairlist() _whitelist = self.pairlists.whitelist - self.rpc.send_msg({'type': RPCMessageType.WHITELIST, 'msg': _whitelist}) + self.rpc.send_msg({'type': RPCMessageType.WHITELIST, 'data': _whitelist}) # Calculating Edge positioning if self.edge: diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index c8d1b70fa..88bae099a 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -26,7 +26,7 @@ async def message_endpoint( # Return a channel ID, pass that instead of ws to the rest of the methods channel = await channel_manager.on_connect(ws) - # Keep connection open until explicitly closed, and sleep + # Keep connection open until explicitly closed, and process requests try: while not channel.is_closed(): request = await channel.recv() diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index f4af8c8ed..e391e66af 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -112,9 +112,6 @@ class ApiServer(RPCHandler): # Cancel the queue task self._background_task.cancel() - # Finally stop the loop - self._loop.call_soon_threadsafe(self._loop.stop) - self._thread.join() @classmethod @@ -127,7 +124,6 @@ class ApiServer(RPCHandler): def send_msg(self, msg: Dict[str, str]) -> None: if self._queue: - logger.info(f"Adding message to queue: {msg}") sync_q = self._queue.sync_q sync_q.put(msg) @@ -155,9 +151,11 @@ class ApiServer(RPCHandler): app.include_router(api_backtest, prefix="/api/v1", dependencies=[Depends(http_basic_or_jwt_token)], ) - app.include_router(ws_router, prefix="/api/v1", - dependencies=[Depends(get_ws_token)] - ) + if self._config.get('api_server', {}).get('enable_message_ws', False): + logger.info("Enabling Message WebSocket") + app.include_router(ws_router, prefix="/api/v1", + dependencies=[Depends(get_ws_token)] + ) app.include_router(router_login, prefix="/api/v1", tags=["auth"]) # UI Router MUST be last! app.include_router(router_ui, prefix='') @@ -194,17 +192,19 @@ class ApiServer(RPCHandler): try: while True: - logger.debug("Getting queue data...") + logger.debug("Getting queue messages...") # Get data from queue - data = await async_queue.get() - logger.debug(f"Found data: {data}") + message = await async_queue.get() + logger.debug(f"Found message of type: {message.get('type')}") # Broadcast it - await self._channel_manager.broadcast(data) + await self._channel_manager.broadcast(message) # Sleep, make this configurable? await asyncio.sleep(0.1) except asyncio.CancelledError: - # Silently stop - pass + # Disconnect channels and stop the loop on cancel + await self._channel_manager.disconnect_all() + self._loop.stop() + # For testing, shouldn't happen when stable except Exception as e: logger.info(f"Exception happened in background task: {e}") @@ -246,7 +246,8 @@ class ApiServer(RPCHandler): if self._standalone: self._server.run() else: - self.start_message_queue() + if self._config.get('api_server', {}).get('enable_message_ws', False): + self.start_message_queue() self._server.run_in_thread() except Exception: logger.exception("Api server failed to start.") diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index f24713a77..6bc5b9d6b 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -116,8 +116,6 @@ class ChannelManager: with self._lock: channel = self.channels.get(websocket) if channel: - logger.debug(f"Disconnecting channel - {channel}") - if not channel.is_closed(): await channel.close() @@ -142,7 +140,6 @@ class ChannelManager: """ with self._lock: message_type = data.get('type') - logger.debug(f"Broadcasting data: {message_type} - {data}") for websocket, channel in self.channels.items(): try: if channel.subscribed_to(message_type): diff --git a/freqtrade/rpc/emc.py b/freqtrade/rpc/emc.py new file mode 100644 index 000000000..48ad78266 --- /dev/null +++ b/freqtrade/rpc/emc.py @@ -0,0 +1,229 @@ +""" +ExternalMessageConsumer module + +Main purpose is to connect to external bot's message websocket to consume data +from it +""" +import asyncio +import logging +import socket +from threading import Thread +from typing import Any, Dict + +import websockets + +from freqtrade.enums import RPCMessageType, RPCRequestType +from freqtrade.misc import json_to_dataframe, remove_entry_exit_signals +from freqtrade.rpc import RPC +from freqtrade.rpc.api_server.ws.channel import WebSocketChannel + + +logger = logging.getLogger(__name__) + + +class ExternalMessageConsumer: + """ + The main controller class for consuming external messages from + other FreqTrade bot's + """ + + def __init__( + self, + rpc: RPC, + config: Dict[str, Any], + ): + self._rpc = rpc + self._config = config + + self._running = False + self._thread = None + self._loop = None + self._main_task = None + self._sub_tasks = None + + self._emc_config = self._config.get('external_message_consumer', {}) + + self.enabled = self._emc_config.get('enabled', False) + self.producers = self._emc_config.get('producers', []) + + if self.enabled and len(self.producers) < 1: + raise ValueError("You must specify at least 1 Producer to connect to.") + + self.reply_timeout = self._emc_config.get('reply_timeout', 10) + self.ping_timeout = self._emc_config.get('ping_timeout', 2) + self.sleep_time = self._emc_config.get('sleep_time', 5) + + # Setting these explicitly as they probably shouldn't be changed by a user + # Unless we somehow integrate this with the strategy to allow creating + # callbacks for the messages + self.topics = [RPCMessageType.WHITELIST, RPCMessageType.ANALYZED_DF] + + self.start() + + def start(self): + """ + Start the main internal loop in another thread to run coroutines + """ + self._loop = asyncio.new_event_loop() + + if not self._thread: + logger.info("Starting ExternalMessageConsumer") + + self._thread = Thread(target=self._loop.run_forever) + self._thread.start() + self._running = True + else: + raise RuntimeError("A loop is already running") + + self._main_task = asyncio.run_coroutine_threadsafe(self._main(), loop=self._loop) + + def shutdown(self): + """ + Shutdown the loop, thread, and tasks + """ + if self._thread and self._loop: + logger.info("Stopping ExternalMessageConsumer") + + if self._sub_tasks: + # Cancel sub tasks + for task in self._sub_tasks: + task.cancel() + + if self._main_task: + # Cancel the main task + self._main_task.cancel() + + self._thread.join() + + async def _main(self): + """ + The main task coroutine + """ + rpc_lock = asyncio.Lock() + + try: + # Create a connection to each producer + self._sub_tasks = [ + self._loop.create_task(self._handle_producer_connection(producer, rpc_lock)) + for producer in self.producers + ] + + await asyncio.gather(*self._sub_tasks) + except asyncio.CancelledError: + pass + finally: + # Stop the loop once we are done + self._loop.stop() + + async def _handle_producer_connection(self, producer, lock): + """ + Main connection loop for the consumer + """ + try: + while True: + try: + url, token = producer['url'], producer['ws_token'] + ws_url = f"{url}?token={token}" + + async with websockets.connect(ws_url) as ws: + logger.info("Connection successful") + channel = WebSocketChannel(ws) + + # Tell the producer we only want these topics + # Should always be the first thing we send + await channel.send( + self.compose_consumer_request(RPCRequestType.SUBSCRIBE, self.topics) + ) + + # Now receive data, if none is within the time limit, ping + while True: + try: + message = await asyncio.wait_for( + channel.recv(), + timeout=5 + ) + + async with lock: + # Handle the data here + # We use a lock because it will call RPC methods + self.handle_producer_message(message) + + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): + # We haven't received data yet. Check the connection and continue. + try: + # ping + ping = await channel.ping() + + await asyncio.wait_for(ping, timeout=self.ping_timeout) + logger.debug(f"Connection to {url} still alive...") + + continue + except Exception: + logger.info( + f"Ping error {url} - retrying in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + + break + except ( + socket.gaierror, + ConnectionRefusedError, + websockets.exceptions.InvalidStatusCode + ) as e: + logger.error(f"Connection Refused - {e} retrying in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + + continue + + except asyncio.CancelledError: + # Exit silently + pass + + def compose_consumer_request(self, type_: str, data: Any) -> Dict[str, Any]: + """ + Create a request for sending to a producer + + :param type_: The RPCRequestType + :param data: The data to send + :returns: Dict[str, Any] + """ + return {'type': type_, 'data': data} + + # How we do things here isn't set in stone. There seems to be some interest + # in figuring out a better way, but we shall do this for now. + def handle_producer_message(self, message: Dict[str, Any]): + """ + Handles external messages from a Producer + """ + # Should we have a default message type? + message_type = message.get('type', RPCMessageType.STATUS) + message_data = message.get('data') + + logger.debug(f"Received message of type {message_type}") + + # Handle Whitelists + if message_type == RPCMessageType.WHITELIST: + pairlist = message_data + + # Add the pairlist data to the ExternalPairlist plugin + external_pairlist = self._rpc._freqtrade.pairlists._pairlist_handlers[0] + external_pairlist.add_pairlist_data(pairlist) + + # Handle analyzed dataframes + elif message_type == RPCMessageType.ANALYZED_DF: + # This shouldn't happen + if message_data is None: + return + + key, value = message_data.get('key'), message_data.get('data') + pair, timeframe, candle_type = key + + # Convert the JSON to a pandas DataFrame + dataframe = json_to_dataframe(value) + + # If set, remove the Entry and Exit signals from the Producer + if self._emc_config.get('remove_entry_exit_signals', False): + dataframe = remove_entry_exit_signals(dataframe) + + # Add the dataframe to the dataprovider + dataprovider = self._rpc._freqtrade.dataprovider + dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) diff --git a/freqtrade/rpc/external_signal/__init__.py b/freqtrade/rpc/external_signal/__init__.py deleted file mode 100644 index decc51551..000000000 --- a/freqtrade/rpc/external_signal/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# # flake8: noqa: F401 -# from freqtrade.rpc.external_signal.controller import ExternalSignalController -# -# -# __all__ = ('ExternalSignalController') diff --git a/freqtrade/rpc/external_signal/channel.py b/freqtrade/rpc/external_signal/channel.py deleted file mode 100644 index 5b278dfed..000000000 --- a/freqtrade/rpc/external_signal/channel.py +++ /dev/null @@ -1,145 +0,0 @@ -# import logging -# from threading import RLock -# from typing import Type -# -# from freqtrade.rpc.external_signal.proxy import WebSocketProxy -# from freqtrade.rpc.external_signal.serializer import MsgPackWebSocketSerializer -# from freqtrade.rpc.external_signal.types import WebSocketType -# -# -# logger = logging.getLogger(__name__) -# -# -# class WebSocketChannel: -# """ -# Object to help facilitate managing a websocket connection -# """ -# -# def __init__( -# self, -# websocket: WebSocketType, -# serializer_cls: Type[WebSocketSerializer] = MsgPackWebSocketSerializer -# ): -# # The WebSocket object -# self._websocket = WebSocketProxy(websocket) -# # The Serializing class for the WebSocket object -# self._serializer_cls = serializer_cls -# -# # Internal event to signify a closed websocket -# self._closed = False -# -# # Wrap the WebSocket in the Serializing class -# self._wrapped_ws = self._serializer_cls(self._websocket) -# -# async def send(self, data): -# """ -# Send data on the wrapped websocket -# """ -# # logger.info(f"Serialized Send - {self._wrapped_ws._serialize(data)}") -# await self._wrapped_ws.send(data) -# -# async def recv(self): -# """ -# Receive data on the wrapped websocket -# """ -# return await self._wrapped_ws.recv() -# -# async def ping(self): -# """ -# Ping the websocket -# """ -# return await self._websocket.ping() -# -# async def close(self): -# """ -# Close the WebSocketChannel -# """ -# -# self._closed = True -# -# def is_closed(self): -# return self._closed -# -# -# class ChannelManager: -# def __init__(self): -# self.channels = dict() -# self._lock = RLock() # Re-entrant Lock -# -# async def on_connect(self, websocket: WebSocketType): -# """ -# Wrap websocket connection into Channel and add to list -# -# :param websocket: The WebSocket object to attach to the Channel -# """ -# if hasattr(websocket, "accept"): -# try: -# await websocket.accept() -# except RuntimeError: -# # The connection was closed before we could accept it -# return -# -# ws_channel = WebSocketChannel(websocket) -# -# with self._lock: -# self.channels[websocket] = ws_channel -# -# return ws_channel -# -# async def on_disconnect(self, websocket: WebSocketType): -# """ -# Call close on the channel if it's not, and remove from channel list -# -# :param websocket: The WebSocket objet attached to the Channel -# """ -# with self._lock: -# channel = self.channels.get(websocket) -# if channel: -# logger.debug(f"Disconnecting channel - {channel}") -# -# if not channel.is_closed(): -# await channel.close() -# -# del self.channels[websocket] -# -# async def disconnect_all(self): -# """ -# Disconnect all Channels -# """ -# with self._lock: -# for websocket, channel in self.channels.items(): -# if not channel.is_closed(): -# await channel.close() -# -# self.channels = dict() -# -# async def broadcast(self, data): -# """ -# Broadcast data on all Channels -# -# :param data: The data to send -# """ -# with self._lock: -# for websocket, channel in self.channels.items(): -# try: -# await channel.send(data) -# except RuntimeError: -# # Handle cannot send after close cases -# await self.on_disconnect(websocket) -# -# async def send_direct(self, channel, data): -# """ -# Send data directly through direct_channel only -# -# :param direct_channel: The WebSocketChannel object to send data through -# :param data: The data to send -# """ -# # We iterate over the channels to get reference to the websocket object -# # so we can disconnect incase of failure -# await channel.send(data) -# -# def has_channels(self): -# """ -# Flag for more than 0 channels -# """ -# return len(self.channels) > 0 diff --git a/freqtrade/rpc/external_signal/controller.py b/freqtrade/rpc/external_signal/controller.py deleted file mode 100644 index 616ea7801..000000000 --- a/freqtrade/rpc/external_signal/controller.py +++ /dev/null @@ -1,449 +0,0 @@ -# """ -# This module manages replicate mode communication -# """ -# import asyncio -# import logging -# import secrets -# import socket -# from threading import Thread -# from typing import Any, Callable, Coroutine, Dict, Union -# -# import websockets -# from fastapi import Depends -# from fastapi import WebSocket as FastAPIWebSocket -# from fastapi import WebSocketDisconnect, status -# from janus import Queue as ThreadedQueue -# -# from freqtrade.enums import ExternalSignalModeType, LeaderMessageType, RPCMessageType -# from freqtrade.rpc import RPC, RPCHandler -# from freqtrade.rpc.external_signal.channel import ChannelManager -# from freqtrade.rpc.external_signal.types import MessageType -# from freqtrade.rpc.external_signal.utils import is_websocket_alive -# -# -# logger = logging.getLogger(__name__) -# -# -# class ExternalSignalController(RPCHandler): -# """ This class handles all websocket communication """ -# -# def __init__( -# self, -# rpc: RPC, -# config: Dict[str, Any], -# api_server: Union[Any, None] = None -# ) -> None: -# """ -# Init the ExternalSignalController class, and init the super class RPCHandler -# :param rpc: instance of RPC Helper class -# :param config: Configuration object -# :param api_server: The ApiServer object -# :return: None -# """ -# super().__init__(rpc, config) -# -# self.freqtrade = rpc._freqtrade -# self.api_server = api_server -# -# if not self.api_server: -# raise RuntimeError("The API server must be enabled for external signals to work") -# -# self._loop = None -# self._running = False -# self._thread = None -# self._queue = None -# -# self._main_task = None -# self._sub_tasks = None -# -# self._message_handlers = { -# LeaderMessageType.pairlist: self._rpc._handle_pairlist_message, -# LeaderMessageType.analyzed_df: self._rpc._handle_analyzed_df_message, -# LeaderMessageType.default: self._rpc._handle_default_message -# } -# -# self.channel_manager = ChannelManager() -# self.external_signal_config = config.get('external_signal', {}) -# -# # What the config should look like -# # "external_signal": { -# # "enabled": true, -# # "mode": "follower", -# # "leaders": [ -# # { -# # "url": "ws://localhost:8080/signals/ws", -# # "api_token": "test" -# # } -# # ] -# # } -# -# # "external_signal": { -# # "enabled": true, -# # "mode": "leader", -# # "api_token": "test" -# # } -# -# self.mode = ExternalSignalModeType[ -# self.external_signal_config.get('mode', 'leader').lower() -# ] -# -# self.leaders_list = self.external_signal_config.get('leaders', []) -# self.push_throttle_secs = self.external_signal_config.get('push_throttle_secs', 0.1) -# -# self.reply_timeout = self.external_signal_config.get('follower_reply_timeout', 10) -# self.ping_timeout = self.external_signal_config.get('follower_ping_timeout', 2) -# self.sleep_time = self.external_signal_config.get('follower_sleep_time', 5) -# -# # Validate external_signal_config here? -# -# if self.mode == ExternalSignalModeType.follower and len(self.leaders_list) == 0: -# raise ValueError("You must specify at least 1 leader in follower mode.") -# -# # This is only used by the leader, the followers use the tokens specified -# # in each of the leaders -# # If you do not specify an API key in the config, one will be randomly -# # generated and logged on startup -# default_api_key = secrets.token_urlsafe(16) -# self.secret_api_key = self.external_signal_config.get('api_token', default_api_key) -# -# self.start() -# -# def is_leader(self): -# """ -# Leader flag -# """ -# return self.enabled() and self.mode == ExternalSignalModeType.leader -# -# def enabled(self): -# """ -# Enabled flag -# """ -# return self.external_signal_config.get('enabled', False) -# -# def num_leaders(self): -# """ -# The number of leaders we should be connected to -# """ -# return len(self.leaders_list) -# -# def start_threaded_loop(self): -# """ -# Start the main internal loop in another thread to run coroutines -# """ -# self._loop = asyncio.new_event_loop() -# -# if not self._thread: -# self._thread = Thread(target=self._loop.run_forever) -# self._thread.start() -# self._running = True -# else: -# raise RuntimeError("A loop is already running") -# -# def submit_coroutine(self, coroutine: Coroutine): -# """ -# Submit a coroutine to the threaded loop -# """ -# if not self._running: -# raise RuntimeError("Cannot schedule new futures after shutdown") -# -# if not self._loop or not self._loop.is_running(): -# raise RuntimeError("Loop must be started before any function can" -# " be submitted") -# -# return asyncio.run_coroutine_threadsafe(coroutine, self._loop) -# -# def start(self): -# """ -# Start the controller main loop -# """ -# self.start_threaded_loop() -# self._main_task = self.submit_coroutine(self.main()) -# -# async def shutdown(self): -# """ -# Shutdown all tasks and close up -# """ -# logger.info("Stopping rpc.externalsignalcontroller") -# -# # Flip running flag -# self._running = False -# -# # Cancel sub tasks -# for task in self._sub_tasks: -# task.cancel() -# -# # Then disconnect all channels -# await self.channel_manager.disconnect_all() -# -# def cleanup(self) -> None: -# """ -# Cleanup pending module resources. -# """ -# if self._thread: -# if self._loop.is_running(): -# self._main_task.cancel() -# self._thread.join() -# -# async def main(self): -# """ -# Main coro -# -# Start the loop based on what mode we're in -# """ -# try: -# if self.mode == ExternalSignalModeType.leader: -# logger.info("Starting rpc.externalsignalcontroller in Leader mode") -# -# await self.run_leader_mode() -# elif self.mode == ExternalSignalModeType.follower: -# logger.info("Starting rpc.externalsignalcontroller in Follower mode") -# -# await self.run_follower_mode() -# -# except asyncio.CancelledError: -# # We're cancelled -# await self.shutdown() -# except Exception as e: -# # Log the error -# logger.error(f"Exception occurred in main task: {e}") -# logger.exception(e) -# finally: -# # This coroutine is the last thing to be ended, so it should stop the loop -# self._loop.stop() -# -# def log_api_token(self): -# """ -# Log the API token -# """ -# logger.info("-" * 15) -# logger.info(f"API_KEY: {self.secret_api_key}") -# logger.info("-" * 15) -# -# def send_msg(self, msg: MessageType) -> None: -# """ -# Support RPC calls -# """ -# if msg["type"] == RPCMessageType.EMIT_DATA: -# message = msg.get("message") -# if message: -# self.send_message(message) -# else: -# logger.error(f"Message is empty! {msg}") -# -# def send_message(self, msg: MessageType) -> None: -# """ -# Broadcast message over all channels if there are any -# """ -# -# if self.channel_manager.has_channels(): -# self._send_message(msg) -# else: -# logger.debug("No listening followers, skipping...") -# pass -# -# def _send_message(self, msg: MessageType): -# """ -# Add data to the internal queue to be broadcasted. This func will block -# if the queue is full. This is meant to be called in the main thread. -# """ -# if self._queue: -# queue = self._queue.sync_q -# queue.put(msg) # This will block if the queue is full -# else: -# logger.warning("Can not send data, leader loop has not started yet!") -# -# async def send_initial_data(self, channel): -# logger.info("Sending initial data through channel") -# -# data = self._rpc._initial_leader_data() -# -# for message in data: -# await channel.send(message) -# -# async def _handle_leader_message(self, message: MessageType): -# """ -# Handle message received from a Leader -# """ -# type = message.get("data_type", LeaderMessageType.default) -# data = message.get("data") -# -# handler: Callable = self._message_handlers[type] -# handler(type, data) -# -# # ---------------------------------------------------------------------- -# -# async def run_leader_mode(self): -# """ -# Main leader coroutine -# -# This starts all of the leader coros and registers the endpoint on -# the ApiServer -# """ -# self.register_leader_endpoint() -# self.log_api_token() -# -# self._sub_tasks = [ -# self._loop.create_task(self._broadcast_queue_data()) -# ] -# -# return await asyncio.gather(*self._sub_tasks) -# -# async def run_follower_mode(self): -# """ -# Main follower coroutine -# -# This starts all of the follower connection coros -# """ -# -# rpc_lock = asyncio.Lock() -# -# self._sub_tasks = [ -# self._loop.create_task(self._handle_leader_connection(leader, rpc_lock)) -# for leader in self.leaders_list -# ] -# -# return await asyncio.gather(*self._sub_tasks) -# -# async def _broadcast_queue_data(self): -# """ -# Loop over queue data and broadcast it -# """ -# # Instantiate the queue in this coroutine so it's attached to our loop -# self._queue = ThreadedQueue() -# async_queue = self._queue.async_q -# -# try: -# while self._running: -# # Get data from queue -# data = await async_queue.get() -# -# # Broadcast it to everyone -# await self.channel_manager.broadcast(data) -# -# # Sleep -# await asyncio.sleep(self.push_throttle_secs) -# -# except asyncio.CancelledError: -# # Silently stop -# pass -# -# async def get_api_token( -# self, -# websocket: FastAPIWebSocket, -# token: Union[str, None] = None -# ): -# """ -# Extract the API key from query param. Must match the -# set secret_api_key or the websocket connection will be closed. -# """ -# if token == self.secret_api_key: -# return token -# else: -# logger.info("Denying websocket request...") -# await websocket.close(code=status.WS_1008_POLICY_VIOLATION) -# -# def register_leader_endpoint(self, path: str = "/signals/ws"): -# """ -# Attach and start the main leader loop to the ApiServer -# -# :param path: The endpoint path -# """ -# if not self.api_server: -# raise RuntimeError("The leader needs the ApiServer to be active") -# -# # The endpoint function for running the main leader loop -# @self.api_server.app.websocket(path) -# async def leader_endpoint( -# websocket: FastAPIWebSocket, -# api_key: str = Depends(self.get_api_token) -# ): -# await self.leader_endpoint_loop(websocket) -# -# async def leader_endpoint_loop(self, websocket: FastAPIWebSocket): -# """ -# The WebSocket endpoint served by the ApiServer. This handles connections, -# and adding them to the channel manager. -# """ -# try: -# if is_websocket_alive(websocket): -# logger.info(f"Follower connected - {websocket.client}") -# channel = await self.channel_manager.on_connect(websocket) -# -# # Send initial data here -# # Data is being broadcasted right away as soon as startup, -# # we may not have to send initial data at all. Further testing -# # required. -# await self.send_initial_data(channel) -# -# # Keep connection open until explicitly closed, and sleep -# try: -# while not channel.is_closed(): -# request = await channel.recv() -# logger.info(f"Follower request - {request}") -# -# except WebSocketDisconnect: -# # Handle client disconnects -# logger.info(f"Follower disconnected - {websocket.client}") -# await self.channel_manager.on_disconnect(websocket) -# except Exception as e: -# logger.info(f"Follower connection failed - {websocket.client}") -# logger.exception(e) -# # Handle cases like - -# # RuntimeError('Cannot call "send" once a closed message has been sent') -# await self.channel_manager.on_disconnect(websocket) -# -# except Exception: -# logger.error(f"Failed to serve - {websocket.client}") -# await self.channel_manager.on_disconnect(websocket) -# -# async def _handle_leader_connection(self, leader, lock): -# """ -# Given a leader, connect and wait on data. If connection is lost, -# it will attempt to reconnect. -# """ -# try: -# url, token = leader["url"], leader["api_token"] -# websocket_url = f"{url}?token={token}" -# -# logger.info(f"Attempting to connect to Leader at: {url}") -# while True: -# try: -# async with websockets.connect(websocket_url) as ws: -# channel = await self.channel_manager.on_connect(ws) -# logger.info(f"Connection to Leader at {url} successful") -# while True: -# try: -# data = await asyncio.wait_for( -# channel.recv(), -# timeout=self.reply_timeout -# ) -# except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): -# # We haven't received data yet. Check the connection and continue. -# try: -# # ping -# ping = await channel.ping() -# await asyncio.wait_for(ping, timeout=self.ping_timeout) -# logger.debug(f"Connection to {url} still alive...") -# continue -# except Exception: -# logger.info( -# f"Ping error {url} - retrying in {self.sleep_time}s") -# asyncio.sleep(self.sleep_time) -# break -# -# async with lock: -# # Acquire lock so only 1 coro handling at a time -# # as we call the RPC module in the main thread -# await self._handle_leader_message(data) -# -# except (socket.gaierror, ConnectionRefusedError): -# logger.info(f"Connection Refused - retrying connection in {self.sleep_time}s") -# await asyncio.sleep(self.sleep_time) -# continue -# except websockets.exceptions.InvalidStatusCode as e: -# logger.error(f"Connection Refused - {e}") -# await asyncio.sleep(self.sleep_time) -# continue -# -# except asyncio.CancelledError: -# pass diff --git a/freqtrade/rpc/external_signal/proxy.py b/freqtrade/rpc/external_signal/proxy.py deleted file mode 100644 index df2a07da0..000000000 --- a/freqtrade/rpc/external_signal/proxy.py +++ /dev/null @@ -1,61 +0,0 @@ -# from typing import Union -# -# from fastapi import WebSocket as FastAPIWebSocket -# from websockets import WebSocketClientProtocol as WebSocket -# -# from freqtrade.rpc.external_signal.types import WebSocketType -# -# -# class WebSocketProxy: -# """ -# WebSocketProxy object to bring the FastAPIWebSocket and websockets.WebSocketClientProtocol -# under the same API -# """ -# -# def __init__(self, websocket: WebSocketType): -# self._websocket: Union[FastAPIWebSocket, WebSocket] = websocket -# -# async def send(self, data): -# """ -# Send data on the wrapped websocket -# """ -# if isinstance(data, str): -# data = data.encode() -# -# if hasattr(self._websocket, "send_bytes"): -# await self._websocket.send_bytes(data) -# else: -# await self._websocket.send(data) -# -# async def recv(self): -# """ -# Receive data on the wrapped websocket -# """ -# if hasattr(self._websocket, "receive_bytes"): -# return await self._websocket.receive_bytes() -# else: -# return await self._websocket.recv() -# -# async def ping(self): -# """ -# Ping the websocket, not supported by FastAPI WebSockets -# """ -# if hasattr(self._websocket, "ping"): -# return await self._websocket.ping() -# return False -# -# async def close(self, code: int = 1000): -# """ -# Close the websocket connection, only supported by FastAPI WebSockets -# """ -# if hasattr(self._websocket, "close"): -# return await self._websocket.close(code) -# pass -# -# async def accept(self): -# """ -# Accept the WebSocket connection, only support by FastAPI WebSockets -# """ -# if hasattr(self._websocket, "accept"): -# return await self._websocket.accept() -# pass diff --git a/freqtrade/rpc/external_signal/serializer.py b/freqtrade/rpc/external_signal/serializer.py deleted file mode 100644 index a23469ef4..000000000 --- a/freqtrade/rpc/external_signal/serializer.py +++ /dev/null @@ -1,65 +0,0 @@ -# import json -# import logging -# from abc import ABC, abstractmethod -# -# import msgpack -# import orjson -# -# from freqtrade.rpc.external_signal.proxy import WebSocketProxy -# -# -# logger = logging.getLogger(__name__) -# -# -# class WebSocketSerializer(ABC): -# def __init__(self, websocket: WebSocketProxy): -# self._websocket: WebSocketProxy = websocket -# -# @abstractmethod -# def _serialize(self, data): -# raise NotImplementedError() -# -# @abstractmethod -# def _deserialize(self, data): -# raise NotImplementedError() -# -# async def send(self, data: bytes): -# await self._websocket.send(self._serialize(data)) -# -# async def recv(self) -> bytes: -# data = await self._websocket.recv() -# -# return self._deserialize(data) -# -# async def close(self, code: int = 1000): -# await self._websocket.close(code) -# -# # Going to explore using MsgPack as the serialization, -# # as that might be the best method for sending pandas -# # dataframes over the wire -# -# -# class JSONWebSocketSerializer(WebSocketSerializer): -# def _serialize(self, data): -# return json.dumps(data) -# -# def _deserialize(self, data): -# return json.loads(data) -# -# -# class ORJSONWebSocketSerializer(WebSocketSerializer): -# ORJSON_OPTIONS = orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY -# -# def _serialize(self, data): -# return orjson.dumps(data, option=self.ORJSON_OPTIONS) -# -# def _deserialize(self, data): -# return orjson.loads(data, option=self.ORJSON_OPTIONS) -# -# -# class MsgPackWebSocketSerializer(WebSocketSerializer): -# def _serialize(self, data): -# return msgpack.packb(data, use_bin_type=True) -# -# def _deserialize(self, data): -# return msgpack.unpackb(data, raw=False) diff --git a/freqtrade/rpc/external_signal/types.py b/freqtrade/rpc/external_signal/types.py deleted file mode 100644 index 38e43f667..000000000 --- a/freqtrade/rpc/external_signal/types.py +++ /dev/null @@ -1,8 +0,0 @@ -# from typing import Any, Dict, TypeVar -# -# from fastapi import WebSocket as FastAPIWebSocket -# from websockets import WebSocketClientProtocol as WebSocket -# -# -# WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket) -# MessageType = Dict[str, Any] diff --git a/freqtrade/rpc/external_signal/utils.py b/freqtrade/rpc/external_signal/utils.py deleted file mode 100644 index 72c8d2ef8..000000000 --- a/freqtrade/rpc/external_signal/utils.py +++ /dev/null @@ -1,10 +0,0 @@ -# from starlette.websockets import WebSocket, WebSocketState -# -# -# async def is_websocket_alive(ws: WebSocket) -> bool: -# if ( -# ws.application_state == WebSocketState.CONNECTED and -# ws.client_state == WebSocketState.CONNECTED -# ): -# return True -# return False diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index f684c7783..a41d08d55 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -1099,65 +1099,3 @@ class RPC: if all([any(x.value == topic for x in RPCMessageType) for topic in data]): logger.debug(f"{channel} subscribed to topics: {data}") channel.set_subscriptions(data) - # - # # ------------------------------ EXTERNAL SIGNALS ----------------------- - # - # def _initial_leader_data(self): - # # We create a list of Messages to send to the follower on connect - # data = [] - # - # # Send Pairlist data - # data.append({ - # "data_type": LeaderMessageType.pairlist, - # "data": self._freqtrade.pairlists._whitelist - # }) - # - # return data - # - # def _handle_pairlist_message(self, type, data): - # """ - # Handles the emitted pairlists from the Leaders - # - # :param type: The data_type of the data - # :param data: The data - # """ - # pairlist = data - # - # logger.debug(f"Handling Pairlist message: {pairlist}") - # - # external_pairlist = self._freqtrade.pairlists._pairlist_handlers[0] - # external_pairlist.add_pairlist_data(pairlist) - # - # def _handle_analyzed_df_message(self, type, data): - # """ - # Handles the analyzed dataframes from the Leaders - # - # :param type: The data_type of the data - # :param data: The data - # """ - # key, value = data["key"], data["value"] - # pair, timeframe, candle_type = key - # - # # Skip any pairs that we don't have in the pairlist? - # # leader_pairlist = self._freqtrade.pairlists._whitelist - # # if pair not in leader_pairlist: - # # return - # - # dataframe = json_to_dataframe(value) - # - # if self._config.get('external_signal', {}).get('remove_signals_analyzed_df', False): - # dataframe = remove_entry_exit_signals(dataframe) - # - # logger.debug(f"Handling analyzed dataframe for {pair}") - # logger.debug(dataframe.tail()) - # - # # Add the dataframe to the dataprovider - # dataprovider = self._freqtrade.dataprovider - # dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) - # - # def _handle_default_message(self, type, data): - # """ - # Default leader message handler, just logs it. We should never have to - # run this unless the leader sends us some weird message. - # """ - # logger.debug(f"Received message from Leader of type {type}: {data}") diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index b3cd5604c..3488a6e3c 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -78,7 +78,9 @@ class RPCManager: 'status': 'stopping bot' } """ - logger.info('Sending rpc message: %s', msg) + # Removed actually showing the message because the logs would be + # completely spammed of the json dataframe + logger.info('Sending rpc message of type: %s', msg.get('type')) if 'pair' in msg: msg.update({ 'base_currency': self._rpc._freqtrade.exchange.get_pair_base_currency(msg['pair']) diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index 22a10b4d3..7120928ff 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -5,19 +5,21 @@ This module defines the interface to apply for strategies import logging from abc import ABC, abstractmethod from datetime import datetime, timedelta, timezone -from typing import Callable, Dict, List, Optional, Tuple, Union +from typing import Dict, List, Optional, Tuple, Union import arrow from pandas import DataFrame from freqtrade.constants import ListPairsWithTimeframes from freqtrade.data.dataprovider import DataProvider -from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirection, SignalTagType, - SignalType, TradingMode) +from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, RPCMessageType, SignalDirection, + SignalTagType, SignalType, TradingMode) from freqtrade.enums.runmode import RunMode from freqtrade.exceptions import OperationalException, StrategyError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date, timeframe_to_seconds +from freqtrade.misc import dataframe_to_json, remove_entry_exit_signals from freqtrade.persistence import Order, PairLocks, Trade +from freqtrade.rpc import RPCManager from freqtrade.strategy.hyper import HyperStrategyMixin from freqtrade.strategy.informative_decorator import (InformativeData, PopulateIndicators, _create_and_merge_informative_pair, @@ -111,6 +113,7 @@ class IStrategy(ABC, HyperStrategyMixin): # and wallets - access to the current balance. dp: DataProvider wallets: Optional[Wallets] = None + rpc: RPCManager # Filled from configuration stake_currency: str # container variable for strategy source code @@ -702,8 +705,7 @@ class IStrategy(ABC, HyperStrategyMixin): self, dataframe: DataFrame, metadata: dict, - external_data: bool = False, - finish_callback: Optional[Callable] = None, + external_data: bool = False ) -> DataFrame: """ Parses the given candle (OHLCV) data and returns a populated DataFrame @@ -729,17 +731,20 @@ class IStrategy(ABC, HyperStrategyMixin): candle_type = self.config.get('candle_type_def', CandleType.SPOT) self.dp._set_cached_df(pair, self.timeframe, dataframe, candle_type=candle_type) - if finish_callback: - finish_callback(pair, dataframe, self.timeframe, candle_type) + if not external_data: + self.rpc.send_msg( + { + 'type': RPCMessageType.ANALYZED_DF, + 'data': { + 'key': (pair, self.timeframe, candle_type), + 'value': dataframe_to_json(dataframe) + } + } + ) else: logger.debug("Skipping TA Analysis for already analyzed candle") - dataframe[SignalType.ENTER_LONG.value] = 0 - dataframe[SignalType.EXIT_LONG.value] = 0 - dataframe[SignalType.ENTER_SHORT.value] = 0 - dataframe[SignalType.EXIT_SHORT.value] = 0 - dataframe[SignalTagType.ENTER_TAG.value] = None - dataframe[SignalTagType.EXIT_TAG.value] = None + dataframe = remove_entry_exit_signals(dataframe) logger.debug("Loop Analysis Launched") @@ -748,8 +753,7 @@ class IStrategy(ABC, HyperStrategyMixin): def analyze_pair( self, pair: str, - external_data: bool = False, - finish_callback: Optional[Callable] = None, + external_data: bool = False ) -> None: """ Fetch data for this pair from dataprovider and analyze. @@ -773,7 +777,7 @@ class IStrategy(ABC, HyperStrategyMixin): dataframe = strategy_safe_wrapper( self._analyze_ticker_internal, message="" - )(dataframe, {'pair': pair}, external_data, finish_callback) + )(dataframe, {'pair': pair}, external_data) self.assert_df(dataframe, df_len, df_close, df_date) except StrategyError as error: @@ -786,15 +790,14 @@ class IStrategy(ABC, HyperStrategyMixin): def analyze( self, - pairs: List[str], - finish_callback: Optional[Callable] = None + pairs: List[str] ) -> None: """ Analyze all pairs using analyze_pair(). :param pairs: List of pairs to analyze """ for pair in pairs: - self.analyze_pair(pair, finish_callback=finish_callback) + self.analyze_pair(pair) def analyze_external(self, pairs: List[str], leader_pairs: List[str]) -> None: """ @@ -808,10 +811,10 @@ class IStrategy(ABC, HyperStrategyMixin): # them normally. # List order is not preserved when doing this! # We use ^ instead of - for symmetric difference - # What do we do with these? extra_pairs = list(set(pairs) ^ set(leader_pairs)) # These would be the pairs that we have trades in, which means # we would have to analyze them normally + # Eventually maybe request data from the Leader if we don't have it? for pair in leader_pairs: # Analyze the pairs, but get the dataframe from the external data diff --git a/scripts/test_ws_client.py b/scripts/test_ws_client.py deleted file mode 100644 index 872ff3ccf..000000000 --- a/scripts/test_ws_client.py +++ /dev/null @@ -1,74 +0,0 @@ -import asyncio -import logging -import socket -from typing import Any - -import websockets - -from freqtrade.enums import RPCMessageType -from freqtrade.rpc.api_server.ws.channel import WebSocketChannel - - -logging.basicConfig(level=logging.DEBUG) -logger = logging.getLogger(__name__) - - -def compose_consumer_request(type_: str, data: Any): - return {"type": type_, "data": data} - - -async def _client(): - # Trying to recreate multiple topic issue. Wait until first whitelist message, - # then CTRL-C to get the status message. - topics = [RPCMessageType.WHITELIST, RPCMessageType.STATUS] - try: - while True: - try: - url = "ws://localhost:8080/api/v1/message/ws?token=testtoken" - async with websockets.connect(url) as ws: - channel = WebSocketChannel(ws) - - logger.info("Connection successful") - # Tell the producer we only want these topics - await channel.send(compose_consumer_request("subscribe", topics)) - - while True: - try: - data = await asyncio.wait_for( - channel.recv(), - timeout=5 - ) - logger.info(f"Data received - {data}") - except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): - # We haven't received data yet. Check the connection and continue. - try: - # ping - ping = await channel.ping() - await asyncio.wait_for(ping, timeout=2) - logger.debug(f"Connection to {url} still alive...") - continue - except Exception: - logger.info( - f"Ping error {url} - retrying in 5s") - await asyncio.sleep(2) - break - - except (socket.gaierror, ConnectionRefusedError): - logger.info("Connection Refused - retrying connection in 5s") - await asyncio.sleep(2) - continue - except websockets.exceptions.InvalidStatusCode as e: - logger.error(f"Connection Refused - {e}") - await asyncio.sleep(2) - continue - - except (asyncio.CancelledError, KeyboardInterrupt): - pass - - -def main(): - asyncio.run(_client()) - - -if __name__ == "__main__": - main() From ddc45ce2ebe57c670a6419a724cc10b7b127e7ad Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 30 Aug 2022 19:30:14 -0600 Subject: [PATCH 018/115] message handling fix, data waiting fix --- freqtrade/data/dataprovider.py | 5 ++++- freqtrade/rpc/emc.py | 25 +++++++++++++++---------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 430ee0932..2d473683c 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -168,7 +168,10 @@ class DataProvider: timeout_str = f"for {timeout} seconds" if timeout > 0 else "indefinitely" logger.debug(f"Waiting for external data on {pair} for {timeout_str}") - pair_event.wait(timeout=timeout) + if timeout > 0: + pair_event.wait(timeout=timeout) + else: + pair_event.wait() def add_pairlisthandler(self, pairlists) -> None: """ diff --git a/freqtrade/rpc/emc.py b/freqtrade/rpc/emc.py index 48ad78266..ee4d9e6b8 100644 --- a/freqtrade/rpc/emc.py +++ b/freqtrade/rpc/emc.py @@ -164,6 +164,9 @@ class ExternalMessageConsumer: await asyncio.sleep(self.sleep_time) break + except Exception as e: + logger.exception(e) + continue except ( socket.gaierror, ConnectionRefusedError, @@ -214,16 +217,18 @@ class ExternalMessageConsumer: if message_data is None: return - key, value = message_data.get('key'), message_data.get('data') - pair, timeframe, candle_type = key + key, value = message_data.get('key'), message_data.get('value') - # Convert the JSON to a pandas DataFrame - dataframe = json_to_dataframe(value) + if key and value: + pair, timeframe, candle_type = key - # If set, remove the Entry and Exit signals from the Producer - if self._emc_config.get('remove_entry_exit_signals', False): - dataframe = remove_entry_exit_signals(dataframe) + # Convert the JSON to a pandas DataFrame + dataframe = json_to_dataframe(value) - # Add the dataframe to the dataprovider - dataprovider = self._rpc._freqtrade.dataprovider - dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) + # If set, remove the Entry and Exit signals from the Producer + if self._emc_config.get('remove_entry_exit_signals', False): + dataframe = remove_entry_exit_signals(dataframe) + + # Add the dataframe to the dataprovider + dataprovider = self._rpc._freqtrade.dataprovider + dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) From 115a901773c63cb4d207e6039e9bed05f260ef7f Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 30 Aug 2022 19:34:43 -0600 Subject: [PATCH 019/115] minor fix for conditional in handle func --- freqtrade/rpc/emc.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/freqtrade/rpc/emc.py b/freqtrade/rpc/emc.py index ee4d9e6b8..42061079a 100644 --- a/freqtrade/rpc/emc.py +++ b/freqtrade/rpc/emc.py @@ -201,6 +201,10 @@ class ExternalMessageConsumer: message_type = message.get('type', RPCMessageType.STATUS) message_data = message.get('data') + # We shouldn't get empty messages + if message_data is None: + return + logger.debug(f"Received message of type {message_type}") # Handle Whitelists @@ -213,10 +217,6 @@ class ExternalMessageConsumer: # Handle analyzed dataframes elif message_type == RPCMessageType.ANALYZED_DF: - # This shouldn't happen - if message_data is None: - return - key, value = message_data.get('key'), message_data.get('value') if key and value: From 510cf4f30507ed4763d13e12a41e12ceb59a6748 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 31 Aug 2022 10:40:26 -0600 Subject: [PATCH 020/115] remove data waiting, remove explicit analyzing of external df --- freqtrade/data/dataprovider.py | 107 +++++++++---------- freqtrade/enums/__init__.py | 1 - freqtrade/enums/externalmessages.py | 7 -- freqtrade/freqtradebot.py | 16 ++- freqtrade/rpc/api_server/api_ws.py | 37 +++++-- freqtrade/rpc/emc.py | 153 +++++++++++++++------------- freqtrade/rpc/rpc.py | 14 +-- freqtrade/strategy/interface.py | 54 ++-------- 8 files changed, 182 insertions(+), 207 deletions(-) delete mode 100644 freqtrade/enums/externalmessages.py diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 2d473683c..9376c0b33 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -7,7 +7,6 @@ Common Interface for bot and strategy to access data. import logging from collections import deque from datetime import datetime, timezone -from threading import Event from typing import Any, Dict, List, Optional, Tuple from pandas import DataFrame @@ -15,9 +14,11 @@ from pandas import DataFrame from freqtrade.configuration import TimeRange from freqtrade.constants import ListPairsWithTimeframes, PairWithTimeframe from freqtrade.data.history import load_pair_history -from freqtrade.enums import CandleType, RunMode, WaitDataPolicy +from freqtrade.enums import CandleType, RPCMessageType, RunMode from freqtrade.exceptions import ExchangeError, OperationalException from freqtrade.exchange import Exchange, timeframe_to_seconds +from freqtrade.misc import dataframe_to_json +from freqtrade.rpc import RPCManager from freqtrade.util import PeriodicCache @@ -33,16 +34,18 @@ class DataProvider: self, config: dict, exchange: Optional[Exchange], + rpc: Optional[RPCManager] = None, pairlists=None ) -> None: self._config = config self._exchange = exchange self._pairlists = pairlists + self.__rpc = rpc self.__cached_pairs: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {} self.__slice_index: Optional[int] = None self.__cached_pairs_backtesting: Dict[PairWithTimeframe, DataFrame] = {} self.__external_pairs_df: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {} - self.__external_pairs_event: Dict[PairWithTimeframe, Tuple[int, Event]] = {} + self.__producer_pairs: List[str] = [] self._msg_queue: deque = deque() self.__msg_cache = PeriodicCache( @@ -51,10 +54,7 @@ class DataProvider: self._num_sources = len( self._config.get('external_message_consumer', {}).get('producers', []) ) - self._wait_data_policy = self._config.get('external_message_consumer', {}).get( - 'wait_data_policy', WaitDataPolicy.all) - self._wait_data_timeout = self._config.get('external_message_consumer', {}).get( - 'wait_data_timeout', 5) + self.external_data_enabled = self._num_sources > 0 def _set_dataframe_max_index(self, limit_index: int): """ @@ -83,6 +83,46 @@ class DataProvider: self.__cached_pairs[pair_key] = ( dataframe, datetime.now(timezone.utc)) + # For multiple producers we will want to merge the pairlists instead of overwriting + def set_producer_pairs(self, pairlist: List[str]): + """ + Set the pairs received to later be used. + This only supports 1 Producer right now. + + :param pairlist: List of pairs + """ + self.__producer_pairs = pairlist.copy() + + def get_producer_pairs(self) -> List[str]: + """ + Get the pairs cached from the producer + + :returns: List of pairs + """ + return self.__producer_pairs + + def emit_df( + self, + pair_key: PairWithTimeframe, + dataframe: DataFrame + ) -> None: + """ + Send this dataframe as an ANALYZED_DF message to RPC + + :param pair_key: PairWithTimeframe tuple + :param data: Tuple containing the DataFrame and the datetime it was cached + """ + if self.__rpc: + self.__rpc.send_msg( + { + 'type': RPCMessageType.ANALYZED_DF, + 'data': { + 'key': pair_key, + 'value': dataframe_to_json(dataframe) + } + } + ) + def add_external_df( self, pair: str, @@ -101,7 +141,6 @@ class DataProvider: # For multiple leaders, if the data already exists, we'd merge self.__external_pairs_df[pair_key] = (dataframe, datetime.now(timezone.utc)) - self._set_data_event(pair_key) def get_external_df( self, @@ -120,59 +159,11 @@ class DataProvider: pair_key = (pair, timeframe, candle_type) if pair_key not in self.__external_pairs_df: - self._wait_on_data(pair_key) - - if pair_key not in self.__external_pairs_df: - return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) + # We don't have this data yet, return empty DataFrame and datetime (01-01-1970) + return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) return self.__external_pairs_df[pair_key] - def _set_data_event(self, key: PairWithTimeframe): - """ - Depending on the WaitDataPolicy, if an event exists for this PairWithTimeframe - then set the event to release main thread from waiting. - - :param key: PairWithTimeframe - """ - pair_event = self.__external_pairs_event.get(key) - - if pair_event: - num_concat, event = pair_event - self.__external_pairs_event[key] = (num_concat + 1, event) - - if self._wait_data_policy == WaitDataPolicy.one: - logger.debug("Setting Data as policy is One") - event.set() - elif self._wait_data_policy == WaitDataPolicy.all and num_concat == self._num_sources: - logger.debug("Setting Data as policy is all, and is complete") - event.set() - - del self.__external_pairs_event[key] - - def _wait_on_data(self, key: PairWithTimeframe): - """ - Depending on the WaitDataPolicy, we will create and wait on an event until - set that determines the full amount of data is available - - :param key: PairWithTimeframe - """ - if self._wait_data_policy is not WaitDataPolicy.none: - pair, timeframe, candle_type = key - - pair_event = Event() - self.__external_pairs_event[key] = (0, pair_event) - - timeout = self._wait_data_timeout \ - if self._wait_data_policy is not WaitDataPolicy.all else 0 - - timeout_str = f"for {timeout} seconds" if timeout > 0 else "indefinitely" - logger.debug(f"Waiting for external data on {pair} for {timeout_str}") - - if timeout > 0: - pair_event.wait(timeout=timeout) - else: - pair_event.wait() - def add_pairlisthandler(self, pairlists) -> None: """ Allow adding pairlisthandler after initialization diff --git a/freqtrade/enums/__init__.py b/freqtrade/enums/__init__.py index 229d770ce..d32e04e17 100644 --- a/freqtrade/enums/__init__.py +++ b/freqtrade/enums/__init__.py @@ -3,7 +3,6 @@ from freqtrade.enums.backteststate import BacktestState from freqtrade.enums.candletype import CandleType from freqtrade.enums.exitchecktuple import ExitCheckTuple from freqtrade.enums.exittype import ExitType -from freqtrade.enums.externalmessages import WaitDataPolicy from freqtrade.enums.marginmode import MarginMode from freqtrade.enums.ordertypevalue import OrderTypeValues from freqtrade.enums.rpcmessagetype import RPCMessageType, RPCRequestType diff --git a/freqtrade/enums/externalmessages.py b/freqtrade/enums/externalmessages.py deleted file mode 100644 index e43899ab5..000000000 --- a/freqtrade/enums/externalmessages.py +++ /dev/null @@ -1,7 +0,0 @@ -from enum import Enum - - -class WaitDataPolicy(str, Enum): - none = "none" - one = "one" - all = "all" diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index c0d658c61..f7b7ad80b 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -85,21 +85,19 @@ class FreqtradeBot(LoggingMixin): # Keep this at the end of this initialization method. self.rpc: RPCManager = RPCManager(self) - self.dataprovider = DataProvider(self.config, self.exchange, self.pairlists) + self.dataprovider = DataProvider(self.config, self.exchange, self.rpc, self.pairlists) # Attach Dataprovider to strategy instance self.strategy.dp = self.dataprovider # Attach Wallets to strategy instance self.strategy.wallets = self.wallets - # Attach rpc to strategy instance - self.strategy.rpc = self.rpc # Initializing Edge only if enabled self.edge = Edge(self.config, self.exchange, self.strategy) if \ self.config.get('edge', {}).get('enabled', False) else None # Init ExternalMessageConsumer if enabled - self.emc = ExternalMessageConsumer(self.rpc._rpc, self.config) if \ + self.emc = ExternalMessageConsumer(self.config, self.dataprovider) if \ self.config.get('external_message_consumer', {}).get('enabled', False) else None self.active_pair_whitelist = self._refresh_active_whitelist() @@ -201,11 +199,11 @@ class FreqtradeBot(LoggingMixin): strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)() - if self.emc: - leader_pairs = self.pairlists._whitelist - self.strategy.analyze_external(self.active_pair_whitelist, leader_pairs) - else: - self.strategy.analyze(self.active_pair_whitelist) + # This just means we won't broadcast dataframes if we're listening to a producer + # Doesn't necessarily NEED to be this way, as maybe we'd like to broadcast + # even if we are using external dataframes in the future. + self.strategy.analyze(self.active_pair_whitelist, + external_data=self.dataprovider.external_data_enabled) with self._exit_lock: # Check for exchange cancelations, timeouts and user requested replace diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 88bae099a..d7c7239d1 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -1,22 +1,48 @@ import logging +from typing import Any, Dict from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect -from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc_optional +from freqtrade.enums import RPCMessageType, RPCRequestType +from freqtrade.rpc.api_server.deps import get_channel_manager +from freqtrade.rpc.api_server.ws.channel import WebSocketChannel from freqtrade.rpc.api_server.ws.utils import is_websocket_alive +# from typing import Any, Dict + + logger = logging.getLogger(__name__) # Private router, protected by API Key authentication router = APIRouter() +# We are passed a Channel object, we can only do sync functions on that channel object +def _process_consumer_request(request: Dict[str, Any], channel: WebSocketChannel): + type, data = request.get('type'), request.get('data') + + # If the request is empty, do nothing + if not data: + return + + # If we have a request of type SUBSCRIBE, set the topics in this channel + if type == RPCRequestType.SUBSCRIBE: + if isinstance(data, list): + logger.error(f"Improper request from channel: {channel} - {request}") + return + + # If all topics passed are a valid RPCMessageType, set subscriptions on channel + if all([any(x.value == topic for x in RPCMessageType) for topic in data]): + + logger.debug(f"{channel} subscribed to topics: {data}") + channel.set_subscriptions(data) + + @router.websocket("/message/ws") async def message_endpoint( ws: WebSocket, - channel_manager=Depends(get_channel_manager), - rpc=Depends(get_rpc_optional) + channel_manager=Depends(get_channel_manager) ): try: if is_websocket_alive(ws): @@ -32,9 +58,8 @@ async def message_endpoint( request = await channel.recv() # Process the request here. Should this be a method of RPC? - if rpc: - logger.info(f"Request: {request}") - rpc._process_consumer_request(request, channel) + logger.info(f"Request: {request}") + _process_consumer_request(request, channel) except WebSocketDisconnect: # Handle client disconnects diff --git a/freqtrade/rpc/emc.py b/freqtrade/rpc/emc.py index 42061079a..3d78bc257 100644 --- a/freqtrade/rpc/emc.py +++ b/freqtrade/rpc/emc.py @@ -12,9 +12,9 @@ from typing import Any, Dict import websockets +from freqtrade.data.dataprovider import DataProvider from freqtrade.enums import RPCMessageType, RPCRequestType from freqtrade.misc import json_to_dataframe, remove_entry_exit_signals -from freqtrade.rpc import RPC from freqtrade.rpc.api_server.ws.channel import WebSocketChannel @@ -29,11 +29,11 @@ class ExternalMessageConsumer: def __init__( self, - rpc: RPC, config: Dict[str, Any], + dataprovider: DataProvider ): - self._rpc = rpc self._config = config + self._dp = dataprovider self._running = False self._thread = None @@ -99,12 +99,12 @@ class ExternalMessageConsumer: """ The main task coroutine """ - rpc_lock = asyncio.Lock() + lock = asyncio.Lock() try: # Create a connection to each producer self._sub_tasks = [ - self._loop.create_task(self._handle_producer_connection(producer, rpc_lock)) + self._loop.create_task(self._handle_producer_connection(producer, lock)) for producer in self.producers ] @@ -115,73 +115,90 @@ class ExternalMessageConsumer: # Stop the loop once we are done self._loop.stop() - async def _handle_producer_connection(self, producer, lock): + async def _handle_producer_connection(self, producer: Dict[str, Any], lock: asyncio.Lock): """ Main connection loop for the consumer + + :param producer: Dictionary containing producer info: {'url': '', 'ws_token': ''} + :param lock: An asyncio Lock """ try: - while True: - try: - url, token = producer['url'], producer['ws_token'] - ws_url = f"{url}?token={token}" - - async with websockets.connect(ws_url) as ws: - logger.info("Connection successful") - channel = WebSocketChannel(ws) - - # Tell the producer we only want these topics - # Should always be the first thing we send - await channel.send( - self.compose_consumer_request(RPCRequestType.SUBSCRIBE, self.topics) - ) - - # Now receive data, if none is within the time limit, ping - while True: - try: - message = await asyncio.wait_for( - channel.recv(), - timeout=5 - ) - - async with lock: - # Handle the data here - # We use a lock because it will call RPC methods - self.handle_producer_message(message) - - except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): - # We haven't received data yet. Check the connection and continue. - try: - # ping - ping = await channel.ping() - - await asyncio.wait_for(ping, timeout=self.ping_timeout) - logger.debug(f"Connection to {url} still alive...") - - continue - except Exception: - logger.info( - f"Ping error {url} - retrying in {self.sleep_time}s") - await asyncio.sleep(self.sleep_time) - - break - except Exception as e: - logger.exception(e) - continue - except ( - socket.gaierror, - ConnectionRefusedError, - websockets.exceptions.InvalidStatusCode - ) as e: - logger.error(f"Connection Refused - {e} retrying in {self.sleep_time}s") - await asyncio.sleep(self.sleep_time) - - continue - + await self._create_connection(producer, lock) except asyncio.CancelledError: # Exit silently pass - def compose_consumer_request(self, type_: str, data: Any) -> Dict[str, Any]: + async def _create_connection(self, producer: Dict[str, Any], lock: asyncio.Lock): + """ + Actually creates and handles the websocket connection, pinging on timeout + and handling connection errors. + + :param producer: Dictionary containing producer info: {'url': '', 'ws_token': ''} + :param lock: An asyncio Lock + """ + while self._running: + try: + url, token = producer['url'], producer['ws_token'] + ws_url = f"{url}?token={token}" + + # This will raise InvalidURI if the url is bad + async with websockets.connect(ws_url) as ws: + logger.info("Connection successful") + channel = WebSocketChannel(ws) + + # Tell the producer we only want these topics + # Should always be the first thing we send + await channel.send( + self.compose_consumer_request(RPCRequestType.SUBSCRIBE, self.topics) + ) + + # Now receive data, if none is within the time limit, ping + while True: + try: + message = await asyncio.wait_for( + channel.recv(), + timeout=self.reply_timeout + ) + + async with lock: + # Handle the message + self.handle_producer_message(message) + + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): + # We haven't received data yet. Check the connection and continue. + try: + # ping + ping = await channel.ping() + + await asyncio.wait_for(ping, timeout=self.ping_timeout) + logger.debug(f"Connection to {url} still alive...") + + continue + except Exception: + logger.info( + f"Ping error {url} - retrying in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + + break + except Exception as e: + logger.exception(e) + continue + except ( + socket.gaierror, + ConnectionRefusedError, + websockets.exceptions.InvalidStatusCode + ) as e: + logger.error(f"Connection Refused - {e} retrying in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + + continue + + # Catch invalid ws_url, and break the loop + except websockets.exceptions.InvalidURI as e: + logger.error(f"{ws_url} is an invalid WebSocket URL - {e}") + break + + def compose_consumer_request(self, type_: RPCRequestType, data: Any) -> Dict[str, Any]: """ Create a request for sending to a producer @@ -211,9 +228,8 @@ class ExternalMessageConsumer: if message_type == RPCMessageType.WHITELIST: pairlist = message_data - # Add the pairlist data to the ExternalPairlist plugin - external_pairlist = self._rpc._freqtrade.pairlists._pairlist_handlers[0] - external_pairlist.add_pairlist_data(pairlist) + # Add the pairlist data to the DataProvider + self._dp.set_producer_pairs(pairlist) # Handle analyzed dataframes elif message_type == RPCMessageType.ANALYZED_DF: @@ -230,5 +246,4 @@ class ExternalMessageConsumer: dataframe = remove_entry_exit_signals(dataframe) # Add the dataframe to the dataprovider - dataprovider = self._rpc._freqtrade.dataprovider - dataprovider.add_external_df(pair, timeframe, dataframe, candle_type) + self._dp.add_external_df(pair, timeframe, dataframe, candle_type) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index a41d08d55..ed7f13a96 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -19,8 +19,8 @@ from freqtrade.configuration.timerange import TimeRange from freqtrade.constants import CANCEL_REASON, DATETIME_PRINT_FORMAT from freqtrade.data.history import load_data from freqtrade.data.metrics import calculate_max_drawdown -from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, RPCMessageType, RPCRequestType, - SignalDirection, State, TradingMode) +from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirection, State, + TradingMode) from freqtrade.exceptions import ExchangeError, PricingError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs from freqtrade.loggers import bufferHandler @@ -1089,13 +1089,3 @@ class RPC: 'last_process_loc': last_p.astimezone(tzlocal()).strftime(DATETIME_PRINT_FORMAT), 'last_process_ts': int(last_p.timestamp()), } - - # We are passed a Channel object, we can only do sync functions on that channel object - def _process_consumer_request(self, request, channel): - # Should we ensure that request is Dict[str, Any]? - type, data = request.get('type'), request.get('data') - - if type == RPCRequestType.SUBSCRIBE: - if all([any(x.value == topic for x in RPCMessageType) for topic in data]): - logger.debug(f"{channel} subscribed to topics: {data}") - channel.set_subscriptions(data) diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index 7120928ff..a06b6506e 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -12,14 +12,13 @@ from pandas import DataFrame from freqtrade.constants import ListPairsWithTimeframes from freqtrade.data.dataprovider import DataProvider -from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, RPCMessageType, SignalDirection, - SignalTagType, SignalType, TradingMode) +from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirection, SignalTagType, + SignalType, TradingMode) from freqtrade.enums.runmode import RunMode from freqtrade.exceptions import OperationalException, StrategyError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_next_date, timeframe_to_seconds -from freqtrade.misc import dataframe_to_json, remove_entry_exit_signals +from freqtrade.misc import remove_entry_exit_signals from freqtrade.persistence import Order, PairLocks, Trade -from freqtrade.rpc import RPCManager from freqtrade.strategy.hyper import HyperStrategyMixin from freqtrade.strategy.informative_decorator import (InformativeData, PopulateIndicators, _create_and_merge_informative_pair, @@ -113,7 +112,6 @@ class IStrategy(ABC, HyperStrategyMixin): # and wallets - access to the current balance. dp: DataProvider wallets: Optional[Wallets] = None - rpc: RPCManager # Filled from configuration stake_currency: str # container variable for strategy source code @@ -731,16 +729,8 @@ class IStrategy(ABC, HyperStrategyMixin): candle_type = self.config.get('candle_type_def', CandleType.SPOT) self.dp._set_cached_df(pair, self.timeframe, dataframe, candle_type=candle_type) - if not external_data: - self.rpc.send_msg( - { - 'type': RPCMessageType.ANALYZED_DF, - 'data': { - 'key': (pair, self.timeframe, candle_type), - 'value': dataframe_to_json(dataframe) - } - } - ) + if populate_indicators: + self.dp.emit_df((pair, self.timeframe, candle_type), dataframe) else: logger.debug("Skipping TA Analysis for already analyzed candle") @@ -763,10 +753,7 @@ class IStrategy(ABC, HyperStrategyMixin): """ candle_type = self.config.get('candle_type_def', CandleType.SPOT) - if not external_data: - dataframe = self.dp.ohlcv(pair, self.timeframe, candle_type) - else: - dataframe, _ = self.dp.get_external_df(pair, self.timeframe, candle_type) + dataframe = self.dp.ohlcv(pair, self.timeframe, candle_type) if not isinstance(dataframe, DataFrame) or dataframe.empty: logger.warning('Empty candle (OHLCV) data for pair %s', pair) @@ -790,38 +777,15 @@ class IStrategy(ABC, HyperStrategyMixin): def analyze( self, - pairs: List[str] + pairs: List[str], + external_data: bool = False ) -> None: """ Analyze all pairs using analyze_pair(). :param pairs: List of pairs to analyze """ for pair in pairs: - self.analyze_pair(pair) - - def analyze_external(self, pairs: List[str], leader_pairs: List[str]) -> None: - """ - Analyze the pre-populated dataframes from the Leader - - :param pairs: The active pair whitelist - :param leader_pairs: The list of pairs from the Leaders - """ - - # Get the extra pairs not listed in Leader pairs, and process - # them normally. - # List order is not preserved when doing this! - # We use ^ instead of - for symmetric difference - extra_pairs = list(set(pairs) ^ set(leader_pairs)) - # These would be the pairs that we have trades in, which means - # we would have to analyze them normally - # Eventually maybe request data from the Leader if we don't have it? - - for pair in leader_pairs: - # Analyze the pairs, but get the dataframe from the external data - self.analyze_pair(pair, external_data=True) - - for pair in extra_pairs: - self.analyze_pair(pair) + self.analyze_pair(pair, external_data) @ staticmethod def preserve_df(dataframe: DataFrame) -> Tuple[int, float, datetime]: From 865b34cd6f91972cb252fff97d7d3ca1248976bd Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 31 Aug 2022 11:43:02 -0600 Subject: [PATCH 021/115] add producer names --- freqtrade/constants.py | 1 + freqtrade/data/dataprovider.py | 36 ++++++++++++------- freqtrade/freqtradebot.py | 7 ++-- .../{emc.py => external_message_consumer.py} | 10 +++--- freqtrade/strategy/interface.py | 21 +++++------ tests/rpc/test_rpc_telegram.py | 7 ++-- 6 files changed, 46 insertions(+), 36 deletions(-) rename freqtrade/rpc/{emc.py => external_message_consumer.py} (95%) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index c7f2acc84..2e580acf5 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -498,6 +498,7 @@ CONF_SCHEMA = { 'items': { 'type': 'object', 'properties': { + 'name': {'type': 'string'}, 'url': {'type': 'string', 'default': ''}, 'ws_token': {'type': 'string', 'default': ''}, } diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 9376c0b33..947387f75 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -34,8 +34,8 @@ class DataProvider: self, config: dict, exchange: Optional[Exchange], - rpc: Optional[RPCManager] = None, - pairlists=None + pairlists=None, + rpc: Optional[RPCManager] = None ) -> None: self._config = config self._exchange = exchange @@ -44,8 +44,9 @@ class DataProvider: self.__cached_pairs: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {} self.__slice_index: Optional[int] = None self.__cached_pairs_backtesting: Dict[PairWithTimeframe, DataFrame] = {} - self.__external_pairs_df: Dict[PairWithTimeframe, Tuple[DataFrame, datetime]] = {} - self.__producer_pairs: List[str] = [] + self.__producer_pairs_df: Dict[str, + Dict[PairWithTimeframe, Tuple[DataFrame, datetime]]] = {} + self.__producer_pairs: Dict[str, List[str]] = {} self._msg_queue: deque = deque() self.__msg_cache = PeriodicCache( @@ -84,22 +85,22 @@ class DataProvider: dataframe, datetime.now(timezone.utc)) # For multiple producers we will want to merge the pairlists instead of overwriting - def set_producer_pairs(self, pairlist: List[str]): + def set_producer_pairs(self, pairlist: List[str], producer_name: str = "default"): """ Set the pairs received to later be used. This only supports 1 Producer right now. :param pairlist: List of pairs """ - self.__producer_pairs = pairlist.copy() + self.__producer_pairs[producer_name] = pairlist.copy() - def get_producer_pairs(self) -> List[str]: + def get_producer_pairs(self, producer_name: str = "default") -> List[str]: """ Get the pairs cached from the producer :returns: List of pairs """ - return self.__producer_pairs + return self.__producer_pairs.get(producer_name, []) def emit_df( self, @@ -129,6 +130,7 @@ class DataProvider: timeframe: str, dataframe: DataFrame, candle_type: CandleType, + producer_name: str = "default" ) -> None: """ Add the pair data to this class from an external source. @@ -139,15 +141,19 @@ class DataProvider: """ pair_key = (pair, timeframe, candle_type) + if producer_name not in self.__producer_pairs_df: + self.__producer_pairs_df[producer_name] = {} + # For multiple leaders, if the data already exists, we'd merge - self.__external_pairs_df[pair_key] = (dataframe, datetime.now(timezone.utc)) + self.__producer_pairs_df[producer_name][pair_key] = (dataframe, datetime.now(timezone.utc)) def get_external_df( self, pair: str, timeframe: str, - candle_type: CandleType - ) -> DataFrame: + candle_type: CandleType, + producer_name: str = "default" + ) -> Tuple[DataFrame, datetime]: """ Get the pair data from the external sources. Will wait if the policy is set to, and data is not available. @@ -158,11 +164,15 @@ class DataProvider: """ pair_key = (pair, timeframe, candle_type) - if pair_key not in self.__external_pairs_df: + if producer_name not in self.__producer_pairs_df: # We don't have this data yet, return empty DataFrame and datetime (01-01-1970) return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) - return self.__external_pairs_df[pair_key] + if pair_key not in self.__producer_pairs_df: + # We don't have this data yet, return empty DataFrame and datetime (01-01-1970) + return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) + + return self.__producer_pairs_df[producer_name][pair_key] def add_pairlisthandler(self, pairlists) -> None: """ diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index f7b7ad80b..19c77d403 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -30,7 +30,7 @@ from freqtrade.plugins.pairlistmanager import PairListManager from freqtrade.plugins.protectionmanager import ProtectionManager from freqtrade.resolvers import ExchangeResolver, StrategyResolver from freqtrade.rpc import RPCManager -from freqtrade.rpc.emc import ExternalMessageConsumer +from freqtrade.rpc.external_message_consumer import ExternalMessageConsumer from freqtrade.strategy.interface import IStrategy from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper from freqtrade.util import FtPrecise @@ -85,7 +85,7 @@ class FreqtradeBot(LoggingMixin): # Keep this at the end of this initialization method. self.rpc: RPCManager = RPCManager(self) - self.dataprovider = DataProvider(self.config, self.exchange, self.rpc, self.pairlists) + self.dataprovider = DataProvider(self.config, self.exchange, self.pairlists, self.rpc) # Attach Dataprovider to strategy instance self.strategy.dp = self.dataprovider @@ -202,8 +202,9 @@ class FreqtradeBot(LoggingMixin): # This just means we won't broadcast dataframes if we're listening to a producer # Doesn't necessarily NEED to be this way, as maybe we'd like to broadcast # even if we are using external dataframes in the future. + self.strategy.analyze(self.active_pair_whitelist, - external_data=self.dataprovider.external_data_enabled) + emit_df=self.dataprovider.external_data_enabled) with self._exit_lock: # Check for exchange cancelations, timeouts and user requested replace diff --git a/freqtrade/rpc/emc.py b/freqtrade/rpc/external_message_consumer.py similarity index 95% rename from freqtrade/rpc/emc.py rename to freqtrade/rpc/external_message_consumer.py index 3d78bc257..ae72089b5 100644 --- a/freqtrade/rpc/emc.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -162,7 +162,7 @@ class ExternalMessageConsumer: async with lock: # Handle the message - self.handle_producer_message(message) + self.handle_producer_message(producer, message) except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): # We haven't received data yet. Check the connection and continue. @@ -210,10 +210,11 @@ class ExternalMessageConsumer: # How we do things here isn't set in stone. There seems to be some interest # in figuring out a better way, but we shall do this for now. - def handle_producer_message(self, message: Dict[str, Any]): + def handle_producer_message(self, producer: Dict[str, Any], message: Dict[str, Any]): """ Handles external messages from a Producer """ + producer_name = producer.get('name', 'default') # Should we have a default message type? message_type = message.get('type', RPCMessageType.STATUS) message_data = message.get('data') @@ -229,7 +230,7 @@ class ExternalMessageConsumer: pairlist = message_data # Add the pairlist data to the DataProvider - self._dp.set_producer_pairs(pairlist) + self._dp.set_producer_pairs(pairlist, producer_name=producer_name) # Handle analyzed dataframes elif message_type == RPCMessageType.ANALYZED_DF: @@ -246,4 +247,5 @@ class ExternalMessageConsumer: dataframe = remove_entry_exit_signals(dataframe) # Add the dataframe to the dataprovider - self._dp.add_external_df(pair, timeframe, dataframe, candle_type) + self._dp.add_external_df(pair, timeframe, dataframe, + candle_type, producer_name=producer_name) diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index a06b6506e..34e475ed7 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -682,8 +682,7 @@ class IStrategy(ABC, HyperStrategyMixin): def analyze_ticker( self, dataframe: DataFrame, - metadata: dict, - populate_indicators: bool = True + metadata: dict ) -> DataFrame: """ Parses the given candle (OHLCV) data and returns a populated DataFrame @@ -693,8 +692,7 @@ class IStrategy(ABC, HyperStrategyMixin): :return: DataFrame of candle (OHLCV) data with indicator data and signals added """ logger.debug("TA Analysis Launched") - if populate_indicators: - dataframe = self.advise_indicators(dataframe, metadata) + dataframe = self.advise_indicators(dataframe, metadata) dataframe = self.advise_entry(dataframe, metadata) dataframe = self.advise_exit(dataframe, metadata) return dataframe @@ -703,7 +701,7 @@ class IStrategy(ABC, HyperStrategyMixin): self, dataframe: DataFrame, metadata: dict, - external_data: bool = False + emit_df: bool = False ) -> DataFrame: """ Parses the given candle (OHLCV) data and returns a populated DataFrame @@ -720,16 +718,15 @@ class IStrategy(ABC, HyperStrategyMixin): if (not self.process_only_new_candles or self._last_candle_seen_per_pair.get(pair, None) != dataframe.iloc[-1]['date']): - populate_indicators = not external_data # Defs that only make change on new candle data. - dataframe = self.analyze_ticker(dataframe, metadata, populate_indicators) + dataframe = self.analyze_ticker(dataframe, metadata) self._last_candle_seen_per_pair[pair] = dataframe.iloc[-1]['date'] candle_type = self.config.get('candle_type_def', CandleType.SPOT) self.dp._set_cached_df(pair, self.timeframe, dataframe, candle_type=candle_type) - if populate_indicators: + if emit_df: self.dp.emit_df((pair, self.timeframe, candle_type), dataframe) else: @@ -743,7 +740,7 @@ class IStrategy(ABC, HyperStrategyMixin): def analyze_pair( self, pair: str, - external_data: bool = False + emit_df: bool = False ) -> None: """ Fetch data for this pair from dataprovider and analyze. @@ -764,7 +761,7 @@ class IStrategy(ABC, HyperStrategyMixin): dataframe = strategy_safe_wrapper( self._analyze_ticker_internal, message="" - )(dataframe, {'pair': pair}, external_data) + )(dataframe, {'pair': pair}, emit_df) self.assert_df(dataframe, df_len, df_close, df_date) except StrategyError as error: @@ -778,14 +775,14 @@ class IStrategy(ABC, HyperStrategyMixin): def analyze( self, pairs: List[str], - external_data: bool = False + emit_df: bool = False ) -> None: """ Analyze all pairs using analyze_pair(). :param pairs: List of pairs to analyze """ for pair in pairs: - self.analyze_pair(pair, external_data) + self.analyze_pair(pair, emit_df) @ staticmethod def preserve_df(dataframe: DataFrame) -> Tuple[int, float, datetime]: diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index a30115bd9..c7ae7cb74 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -2138,10 +2138,9 @@ def test_send_msg_strategy_msg_notification(default_conf, mocker) -> None: def test_send_msg_unknown_type(default_conf, mocker) -> None: telegram, _, _ = get_telegram_testobject(mocker, default_conf) - with pytest.raises(NotImplementedError, match=r'Unknown message type: None'): - telegram.send_msg({ - 'type': None, - }) + telegram.send_msg({ + 'type': None, + }) @pytest.mark.parametrize('message_type,enter,enter_signal,leverage', [ From 6e8abf8674b143fcee50e38c8ecb44081f31d347 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 31 Aug 2022 11:58:58 -0600 Subject: [PATCH 022/115] add producer name to required fields in config --- freqtrade/constants.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 2e580acf5..6bacaf961 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -501,17 +501,13 @@ CONF_SCHEMA = { 'name': {'type': 'string'}, 'url': {'type': 'string', 'default': ''}, 'ws_token': {'type': 'string', 'default': ''}, - } + }, + 'required': ['name', 'url', 'ws_token'] } }, 'reply_timeout': {'type': 'integer'}, 'sleep_time': {'type': 'integer'}, 'ping_timeout': {'type': 'integer'}, - 'wait_data_policy': { - 'type': 'string', - 'enum': WAIT_DATA_POLICY_OPTIONS - }, - 'wait_data_timeout': {'type': 'integer', 'default': 5}, 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False} }, 'required': ['producers'] From c72a2c26c7c3be0f9da2582886cd8bcca87efb5b Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 31 Aug 2022 12:06:24 -0600 Subject: [PATCH 023/115] remove external pairlist --- .../plugins/pairlist/ExternalPairList.py | 103 ------------------ 1 file changed, 103 deletions(-) delete mode 100644 freqtrade/plugins/pairlist/ExternalPairList.py diff --git a/freqtrade/plugins/pairlist/ExternalPairList.py b/freqtrade/plugins/pairlist/ExternalPairList.py deleted file mode 100644 index 27a328060..000000000 --- a/freqtrade/plugins/pairlist/ExternalPairList.py +++ /dev/null @@ -1,103 +0,0 @@ -""" -External Pair List provider - -Provides pair list from Leader data -""" -import logging -from typing import Any, Dict, List - -from freqtrade.plugins.pairlist.IPairList import IPairList - - -logger = logging.getLogger(__name__) - - -class ExternalPairList(IPairList): - """ - PairList plugin for use with external signal follower mode. - Will use pairs given from leader data. - - Usage: - "pairlists": [ - { - "method": "ExternalPairList", - "number_assets": 5, # We can limit the amount of pairs to use from leader - } - ], - """ - - def __init__(self, exchange, pairlistmanager, - config: Dict[str, Any], pairlistconfig: Dict[str, Any], - pairlist_pos: int) -> None: - super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos) - - # Not sure how to enforce ExternalPairList as the only PairList - - self._num_assets = self._pairlistconfig.get('number_assets') - - self._leader_pairs: List[str] = [] - - def _clamped_pairlist(self): - """ - Return the self._leader_pairs pairlist limited to the maximum set num_assets - or the length of it. - """ - length = len(self._leader_pairs) - if self._num_assets: - return self._leader_pairs[:min(length, self._num_assets)] - else: - return self._leader_pairs - - @property - def needstickers(self) -> bool: - """ - Boolean property defining if tickers are necessary. - If no Pairlist requires tickers, an empty Dict is passed - as tickers argument to filter_pairlist - """ - return False - - def short_desc(self) -> str: - """ - Short whitelist method description - used for startup-messages - -> Please overwrite in subclasses - """ - return f"{self.name}" - - def add_pairlist_data(self, pairlist: List[str]): - """ - Add pairs from Leader - - :param pairlist: List of pairs - """ - - # If some pairs were removed on Leader, remove them here - for pair in self._leader_pairs: - if pair not in pairlist: - logger.debug(f"Leader removed pair: {pair}") - self._leader_pairs.remove(pair) - - # Only add new pairs - seen = set(self._leader_pairs) - for pair in pairlist: - if pair in seen: - continue - self._leader_pairs.append(pair) - - def gen_pairlist(self, tickers: Dict) -> List[str]: - """ - Generate the pairlist - :param tickers: Tickers (from exchange.get_tickers()). May be cached. - :return: List of pairs - """ - return self._clamped_pairlist() - - def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]: - """ - Filters and sorts pairlist and returns the whitelist again. - Called on each bot iteration - please use internal caching if necessary - :param pairlist: pairlist to filter or sort - :param tickers: Tickers (from exchange.get_tickers()). May be cached. - :return: new whitelist - """ - return self._clamped_pairlist() From 57e9078727fe03ca682fee3ee38ff1c8c93a29b1 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 31 Aug 2022 14:44:52 -0600 Subject: [PATCH 024/115] update example config --- config_examples/config_full.example.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/config_examples/config_full.example.json b/config_examples/config_full.example.json index ec988687f..d0efa5bb6 100644 --- a/config_examples/config_full.example.json +++ b/config_examples/config_full.example.json @@ -180,10 +180,15 @@ "enabled": false, "producers": [ { + "name": "default", "url": "ws://some.freqtrade.bot/api/v1/message/ws", "ws_token": "a_secret_ws_token" } - ] + ], + "reply_timeout": 10, + "ping_timeout": 5, + "sleep_time": 5, + "remove_entry_exit_signals": false }, "bot_name": "freqtrade", "db_url": "sqlite:///tradesv3.sqlite", From 00f35f48707a600fb13fd723d376502fd1e4ddd8 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 1 Sep 2022 20:06:36 -0600 Subject: [PATCH 025/115] remove old constant, add initial_data requesting, minor changes --- freqtrade/constants.py | 3 - freqtrade/data/dataprovider.py | 1 - freqtrade/enums/rpcmessagetype.py | 1 + freqtrade/freqtradebot.py | 10 +-- freqtrade/rpc/api_server/api_ws.py | 39 +++++++++--- freqtrade/rpc/api_server/webserver.py | 8 +-- freqtrade/rpc/external_message_consumer.py | 73 +++++++++++++++------- freqtrade/rpc/rpc.py | 51 ++++++++++++--- freqtrade/rpc/rpc_manager.py | 2 + freqtrade/strategy/interface.py | 4 +- 10 files changed, 136 insertions(+), 56 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 6bacaf961..63222f2ff 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -61,8 +61,6 @@ USERPATH_FREQAIMODELS = 'freqaimodels' TELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent'] WEBHOOK_FORMAT_OPTIONS = ['form', 'json', 'raw'] -WAIT_DATA_POLICY_OPTIONS = ['none', 'first', 'all'] - ENV_VAR_PREFIX = 'FREQTRADE__' NON_OPEN_EXCHANGE_STATES = ('cancelled', 'canceled', 'closed', 'expired') @@ -404,7 +402,6 @@ CONF_SCHEMA = { 'username': {'type': 'string'}, 'password': {'type': 'string'}, 'ws_token': {'type': 'string'}, - 'enable_message_ws': {'type': 'boolean', 'default': False}, 'jwt_secret_key': {'type': 'string'}, 'CORS_origins': {'type': 'array', 'items': {'type': 'string'}}, 'verbosity': {'type': 'string', 'enum': ['error', 'info']}, diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 947387f75..90302f88e 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -144,7 +144,6 @@ class DataProvider: if producer_name not in self.__producer_pairs_df: self.__producer_pairs_df[producer_name] = {} - # For multiple leaders, if the data already exists, we'd merge self.__producer_pairs_df[producer_name][pair_key] = (dataframe, datetime.now(timezone.utc)) def get_external_df( diff --git a/freqtrade/enums/rpcmessagetype.py b/freqtrade/enums/rpcmessagetype.py index 6283fb7cc..c213826ae 100644 --- a/freqtrade/enums/rpcmessagetype.py +++ b/freqtrade/enums/rpcmessagetype.py @@ -33,3 +33,4 @@ class RPCMessageType(str, Enum): # Enum for parsing requests from ws consumers class RPCRequestType(str, Enum): SUBSCRIBE = 'subscribe' + INITIAL_DATA = 'initial_data' diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 19c77d403..888994ffb 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -203,8 +203,7 @@ class FreqtradeBot(LoggingMixin): # Doesn't necessarily NEED to be this way, as maybe we'd like to broadcast # even if we are using external dataframes in the future. - self.strategy.analyze(self.active_pair_whitelist, - emit_df=self.dataprovider.external_data_enabled) + self.strategy.analyze(self.active_pair_whitelist) with self._exit_lock: # Check for exchange cancelations, timeouts and user requested replace @@ -264,11 +263,10 @@ class FreqtradeBot(LoggingMixin): pairs that have open trades. """ # Refresh whitelist + _prev_whitelist = self.pairlists.whitelist self.pairlists.refresh_pairlist() _whitelist = self.pairlists.whitelist - self.rpc.send_msg({'type': RPCMessageType.WHITELIST, 'data': _whitelist}) - # Calculating Edge positioning if self.edge: self.edge.calculate(_whitelist) @@ -279,6 +277,10 @@ class FreqtradeBot(LoggingMixin): # It ensures that candle (OHLCV) data are downloaded for open trades as well _whitelist.extend([trade.pair for trade in trades if trade.pair not in _whitelist]) + # Called last to include the included pairs + if _prev_whitelist != _whitelist: + self.rpc.send_msg({'type': RPCMessageType.WHITELIST, 'data': _whitelist}) + return _whitelist def get_free_open_trades(self) -> int: diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index d7c7239d1..52507106d 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -4,9 +4,10 @@ from typing import Any, Dict from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect from freqtrade.enums import RPCMessageType, RPCRequestType -from freqtrade.rpc.api_server.deps import get_channel_manager +from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc from freqtrade.rpc.api_server.ws.channel import WebSocketChannel from freqtrade.rpc.api_server.ws.utils import is_websocket_alive +from freqtrade.rpc.rpc import RPC # from typing import Any, Dict @@ -18,17 +19,20 @@ logger = logging.getLogger(__name__) router = APIRouter() -# We are passed a Channel object, we can only do sync functions on that channel object -def _process_consumer_request(request: Dict[str, Any], channel: WebSocketChannel): +async def _process_consumer_request( + request: Dict[str, Any], + channel: WebSocketChannel, + rpc: RPC +): type, data = request.get('type'), request.get('data') - # If the request is empty, do nothing - if not data: - return - # If we have a request of type SUBSCRIBE, set the topics in this channel if type == RPCRequestType.SUBSCRIBE: - if isinstance(data, list): + # If the request is empty, do nothing + if not data: + return + + if not isinstance(data, list): logger.error(f"Improper request from channel: {channel} - {request}") return @@ -38,11 +42,26 @@ def _process_consumer_request(request: Dict[str, Any], channel: WebSocketChannel logger.debug(f"{channel} subscribed to topics: {data}") channel.set_subscriptions(data) + elif type == RPCRequestType.INITIAL_DATA: + # Acquire the data + initial_data = rpc._ws_initial_data() + + # We now loop over it sending it in pieces + whitelist_data, analyzed_df = initial_data.get('whitelist'), initial_data.get('analyzed_df') + + if whitelist_data: + await channel.send({"type": RPCMessageType.WHITELIST, "data": whitelist_data}) + + if analyzed_df: + for pair, message in analyzed_df.items(): + await channel.send({"type": RPCMessageType.ANALYZED_DF, "data": message}) + @router.websocket("/message/ws") async def message_endpoint( ws: WebSocket, - channel_manager=Depends(get_channel_manager) + rpc: RPC = Depends(get_rpc), + channel_manager=Depends(get_channel_manager), ): try: if is_websocket_alive(ws): @@ -59,7 +78,7 @@ async def message_endpoint( # Process the request here. Should this be a method of RPC? logger.info(f"Request: {request}") - _process_consumer_request(request, channel) + await _process_consumer_request(request, channel, rpc) except WebSocketDisconnect: # Handle client disconnects diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index e391e66af..150c83890 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -151,11 +151,9 @@ class ApiServer(RPCHandler): app.include_router(api_backtest, prefix="/api/v1", dependencies=[Depends(http_basic_or_jwt_token)], ) - if self._config.get('api_server', {}).get('enable_message_ws', False): - logger.info("Enabling Message WebSocket") - app.include_router(ws_router, prefix="/api/v1", - dependencies=[Depends(get_ws_token)] - ) + app.include_router(ws_router, prefix="/api/v1", + dependencies=[Depends(get_ws_token)] + ) app.include_router(router_login, prefix="/api/v1", tags=["auth"]) # UI Router MUST be last! app.include_router(router_ui, prefix='') diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index ae72089b5..4544afc29 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -8,7 +8,7 @@ import asyncio import logging import socket from threading import Thread -from typing import Any, Dict +from typing import Any, Dict, Optional import websockets @@ -58,6 +58,11 @@ class ExternalMessageConsumer: # callbacks for the messages self.topics = [RPCMessageType.WHITELIST, RPCMessageType.ANALYZED_DF] + self._message_handlers = { + RPCMessageType.WHITELIST: self._consume_whitelist_message, + RPCMessageType.ANALYZED_DF: self._consume_analyzed_df_message, + } + self.start() def start(self): @@ -152,6 +157,11 @@ class ExternalMessageConsumer: self.compose_consumer_request(RPCRequestType.SUBSCRIBE, self.topics) ) + # Now request the initial data from this Producer + await channel.send( + self.compose_consumer_request(RPCRequestType.INITIAL_DATA) + ) + # Now receive data, if none is within the time limit, ping while True: try: @@ -198,7 +208,11 @@ class ExternalMessageConsumer: logger.error(f"{ws_url} is an invalid WebSocket URL - {e}") break - def compose_consumer_request(self, type_: RPCRequestType, data: Any) -> Dict[str, Any]: + def compose_consumer_request( + self, + type_: RPCRequestType, + data: Optional[Any] = None + ) -> Dict[str, Any]: """ Create a request for sending to a producer @@ -208,8 +222,6 @@ class ExternalMessageConsumer: """ return {'type': type_, 'data': data} - # How we do things here isn't set in stone. There seems to be some interest - # in figuring out a better way, but we shall do this for now. def handle_producer_message(self, producer: Dict[str, Any], message: Dict[str, Any]): """ Handles external messages from a Producer @@ -225,27 +237,44 @@ class ExternalMessageConsumer: logger.debug(f"Received message of type {message_type}") - # Handle Whitelists - if message_type == RPCMessageType.WHITELIST: - pairlist = message_data + message_handler = self._message_handlers.get(message_type) - # Add the pairlist data to the DataProvider - self._dp.set_producer_pairs(pairlist, producer_name=producer_name) + if not message_handler: + logger.info(f"Received unhandled message: {message_data}, ignoring...") + return - # Handle analyzed dataframes - elif message_type == RPCMessageType.ANALYZED_DF: - key, value = message_data.get('key'), message_data.get('value') + message_handler(producer_name, message_data) - if key and value: - pair, timeframe, candle_type = key + def _consume_whitelist_message(self, producer_name: str, message_data: Any): + # We expect List[str] + if not isinstance(message_data, list): + return - # Convert the JSON to a pandas DataFrame - dataframe = json_to_dataframe(value) + # Add the pairlist data to the DataProvider + self._dp.set_producer_pairs(message_data, producer_name=producer_name) - # If set, remove the Entry and Exit signals from the Producer - if self._emc_config.get('remove_entry_exit_signals', False): - dataframe = remove_entry_exit_signals(dataframe) + logger.debug(f"Consumed message from {producer_name} of type RPCMessageType.WHITELIST") - # Add the dataframe to the dataprovider - self._dp.add_external_df(pair, timeframe, dataframe, - candle_type, producer_name=producer_name) + def _consume_analyzed_df_message(self, producer_name: str, message_data: Any): + # We expect a Dict[str, Any] + if not isinstance(message_data, dict): + return + + key, value = message_data.get('key'), message_data.get('value') + + if key and value: + pair, timeframe, candle_type = key + + # Convert the JSON to a pandas DataFrame + dataframe = json_to_dataframe(value) + + # If set, remove the Entry and Exit signals from the Producer + if self._emc_config.get('remove_entry_exit_signals', False): + dataframe = remove_entry_exit_signals(dataframe) + + # Add the dataframe to the dataprovider + self._dp.add_external_df(pair, timeframe, dataframe, + candle_type, producer_name=producer_name) + + logger.debug( + f"Consumed message from {producer_name} of type RPCMessageType.ANALYZED_DF") diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index ed7f13a96..c4752c570 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -24,7 +24,7 @@ from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirecti from freqtrade.exceptions import ExchangeError, PricingError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs from freqtrade.loggers import bufferHandler -from freqtrade.misc import decimals_per_coin, shorten_date +from freqtrade.misc import dataframe_to_json, decimals_per_coin, shorten_date from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence.models import PairLock from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist @@ -1035,16 +1035,51 @@ class RPC: def _rpc_analysed_dataframe(self, pair: str, timeframe: str, limit: Optional[int]) -> Dict[str, Any]: + """ Analyzed dataframe in Dict form """ - _data, last_analyzed = self._freqtrade.dataprovider.get_analyzed_dataframe( - pair, timeframe) - _data = _data.copy() - if limit: - _data = _data.iloc[-limit:] + _data, last_analyzed = self.__rpc_analysed_dataframe_raw(pair, timeframe, limit) return self._convert_dataframe_to_dict(self._freqtrade.config['strategy'], pair, timeframe, _data, last_analyzed) - @staticmethod + def __rpc_analysed_dataframe_raw(self, pair: str, timeframe: str, + limit: Optional[int]) -> Tuple[DataFrame, datetime]: + """ Get the dataframe and last analyze from the dataprovider """ + _data, last_analyzed = self._freqtrade.dataprovider.get_analyzed_dataframe( + pair, timeframe) + _data = _data.copy() + + if limit: + _data = _data.iloc[-limit:] + return _data, last_analyzed + + def _ws_all_analysed_dataframes( + self, + pairlist: List[str], + limit: Optional[int] + ) -> Dict[str, Any]: + """ Get the analysed dataframes of each pair in the pairlist """ + timeframe = self._freqtrade.config['timeframe'] + candle_type = self._freqtrade.config.get('candle_type_def', CandleType.SPOT) + _data = {} + + for pair in pairlist: + dataframe, last_analyzed = self.__rpc_analysed_dataframe_raw(pair, timeframe, limit) + _data[pair] = { + "key": (pair, timeframe, candle_type), + "value": dataframe_to_json(dataframe) + } + + return _data + + def _ws_initial_data(self): + """ Websocket friendly initial data, whitelists and all analyzed dataframes """ + whitelist = self._freqtrade.active_pair_whitelist + # We only get the last 500 candles, should we remove the limit? + analyzed_df = self._ws_all_analysed_dataframes(whitelist, 500) + + return {"whitelist": whitelist, "analyzed_df": analyzed_df} + + @ staticmethod def _rpc_analysed_history_full(config, pair: str, timeframe: str, timerange: str, exchange) -> Dict[str, Any]: timerange_parsed = TimeRange.parse_timerange(timerange) @@ -1075,7 +1110,7 @@ class RPC: self._freqtrade.strategy.plot_config['subplots'] = {} return self._freqtrade.strategy.plot_config - @staticmethod + @ staticmethod def _rpc_sysinfo() -> Dict[str, Any]: return { "cpu_pct": psutil.cpu_percent(interval=1, percpu=True), diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 3488a6e3c..d6374566c 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -81,6 +81,8 @@ class RPCManager: # Removed actually showing the message because the logs would be # completely spammed of the json dataframe logger.info('Sending rpc message of type: %s', msg.get('type')) + # Log actual message in debug? + # logger.debug(msg) if 'pair' in msg: msg.update({ 'base_currency': self._rpc._freqtrade.exchange.get_pair_base_currency(msg['pair']) diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index 34e475ed7..7fcae870a 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -725,9 +725,7 @@ class IStrategy(ABC, HyperStrategyMixin): candle_type = self.config.get('candle_type_def', CandleType.SPOT) self.dp._set_cached_df(pair, self.timeframe, dataframe, candle_type=candle_type) - - if emit_df: - self.dp.emit_df((pair, self.timeframe, candle_type), dataframe) + self.dp.emit_df((pair, self.timeframe, candle_type), dataframe) else: logger.debug("Skipping TA Analysis for already analyzed candle") From dccde88c83c4e8dfa7c8b70a6c4a7f9459ce177c Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 1 Sep 2022 23:15:03 -0600 Subject: [PATCH 026/115] fix dataframe serializing --- freqtrade/data/dataprovider.py | 3 +- freqtrade/misc.py | 3 +- freqtrade/rpc/api_server/ws/channel.py | 4 +-- freqtrade/rpc/api_server/ws/serializer.py | 37 +++++++++++++++------- freqtrade/rpc/external_message_consumer.py | 9 +++--- freqtrade/rpc/rpc.py | 7 ++-- 6 files changed, 37 insertions(+), 26 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 90302f88e..ef3067f38 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -17,7 +17,6 @@ from freqtrade.data.history import load_pair_history from freqtrade.enums import CandleType, RPCMessageType, RunMode from freqtrade.exceptions import ExchangeError, OperationalException from freqtrade.exchange import Exchange, timeframe_to_seconds -from freqtrade.misc import dataframe_to_json from freqtrade.rpc import RPCManager from freqtrade.util import PeriodicCache @@ -119,7 +118,7 @@ class DataProvider: 'type': RPCMessageType.ANALYZED_DF, 'data': { 'key': pair_key, - 'value': dataframe_to_json(dataframe) + 'value': dataframe } } ) diff --git a/freqtrade/misc.py b/freqtrade/misc.py index ceace4ed8..6a93b6f26 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -269,7 +269,8 @@ def json_to_dataframe(data: str) -> pandas.DataFrame: :returns: A pandas DataFrame from the JSON string """ dataframe = pandas.read_json(data) - dataframe['date'] = pandas.to_datetime(dataframe['date'], unit='ms', utc=True) + if 'date' in dataframe.columns: + dataframe['date'] = pandas.to_datetime(dataframe['date'], unit='ms', utc=True) return dataframe diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index 6bc5b9d6b..b47fe7550 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -3,7 +3,7 @@ from threading import RLock from typing import List, Type from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy -from freqtrade.rpc.api_server.ws.serializer import ORJSONWebSocketSerializer, WebSocketSerializer +from freqtrade.rpc.api_server.ws.serializer import RapidJSONWebSocketSerializer, WebSocketSerializer from freqtrade.rpc.api_server.ws.types import WebSocketType @@ -18,7 +18,7 @@ class WebSocketChannel: def __init__( self, websocket: WebSocketType, - serializer_cls: Type[WebSocketSerializer] = ORJSONWebSocketSerializer + serializer_cls: Type[WebSocketSerializer] = RapidJSONWebSocketSerializer ): # The WebSocket object self._websocket = WebSocketProxy(websocket) diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py index ae2857f0b..c11ca9a99 100644 --- a/freqtrade/rpc/api_server/ws/serializer.py +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -3,8 +3,10 @@ import logging from abc import ABC, abstractmethod import msgpack -import orjson +import rapidjson +from pandas import DataFrame +from freqtrade.misc import dataframe_to_json, json_to_dataframe from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy @@ -34,27 +36,23 @@ class WebSocketSerializer(ABC): async def close(self, code: int = 1000): await self._websocket.close(code) -# Going to explore using MsgPack as the serialization, -# as that might be the best method for sending pandas -# dataframes over the wire - class JSONWebSocketSerializer(WebSocketSerializer): def _serialize(self, data): - return json.dumps(data) + return json.dumps(data, default=_json_default) def _deserialize(self, data): - return json.loads(data) + return json.loads(data, object_hook=_json_object_hook) -class ORJSONWebSocketSerializer(WebSocketSerializer): - ORJSON_OPTIONS = orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY +# ORJSON does not support .loads(object_hook=x) parameter, so we must use RapidJSON +class RapidJSONWebSocketSerializer(WebSocketSerializer): def _serialize(self, data): - return orjson.dumps(data, option=self.ORJSON_OPTIONS) + return rapidjson.dumps(data, default=_json_default) def _deserialize(self, data): - return orjson.loads(data) + return rapidjson.loads(data, object_hook=_json_object_hook) class MsgPackWebSocketSerializer(WebSocketSerializer): @@ -63,3 +61,20 @@ class MsgPackWebSocketSerializer(WebSocketSerializer): def _deserialize(self, data): return msgpack.unpackb(data, raw=False) + + +# Support serializing pandas DataFrames +def _json_default(z): + if isinstance(z, DataFrame): + return { + '__type__': 'dataframe', + '__value__': dataframe_to_json(z) + } + raise TypeError + + +# Support deserializing JSON to pandas DataFrames +def _json_object_hook(z): + if z.get('__type__') == 'dataframe': + return json_to_dataframe(z.get('__value__')) + return z diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 4544afc29..4c7f6570d 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -10,11 +10,12 @@ import socket from threading import Thread from typing import Any, Dict, Optional +import pandas import websockets from freqtrade.data.dataprovider import DataProvider from freqtrade.enums import RPCMessageType, RPCRequestType -from freqtrade.misc import json_to_dataframe, remove_entry_exit_signals +from freqtrade.misc import remove_entry_exit_signals from freqtrade.rpc.api_server.ws.channel import WebSocketChannel @@ -262,11 +263,9 @@ class ExternalMessageConsumer: key, value = message_data.get('key'), message_data.get('value') - if key and value: + if key and isinstance(value, pandas.DataFrame): pair, timeframe, candle_type = key - - # Convert the JSON to a pandas DataFrame - dataframe = json_to_dataframe(value) + dataframe = value # If set, remove the Entry and Exit signals from the Producer if self._emc_config.get('remove_entry_exit_signals', False): diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index c4752c570..96b43f36b 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -24,7 +24,7 @@ from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirecti from freqtrade.exceptions import ExchangeError, PricingError from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs from freqtrade.loggers import bufferHandler -from freqtrade.misc import dataframe_to_json, decimals_per_coin, shorten_date +from freqtrade.misc import decimals_per_coin, shorten_date from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence.models import PairLock from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist @@ -1064,10 +1064,7 @@ class RPC: for pair in pairlist: dataframe, last_analyzed = self.__rpc_analysed_dataframe_raw(pair, timeframe, limit) - _data[pair] = { - "key": (pair, timeframe, candle_type), - "value": dataframe_to_json(dataframe) - } + _data[pair] = {"key": (pair, timeframe, candle_type), "value": dataframe} return _data From eb4cd6ba82b8d348b02a37d65c1567f0678f056d Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 1 Sep 2022 23:52:13 -0600 Subject: [PATCH 027/115] split initial data into separate requests --- freqtrade/enums/rpcmessagetype.py | 4 +++- freqtrade/rpc/api_server/api_ws.py | 22 +++++++++---------- freqtrade/rpc/external_message_consumer.py | 25 +++++++++++++--------- freqtrade/rpc/rpc.py | 11 +++++----- 4 files changed, 35 insertions(+), 27 deletions(-) diff --git a/freqtrade/enums/rpcmessagetype.py b/freqtrade/enums/rpcmessagetype.py index c213826ae..929f6d083 100644 --- a/freqtrade/enums/rpcmessagetype.py +++ b/freqtrade/enums/rpcmessagetype.py @@ -33,4 +33,6 @@ class RPCMessageType(str, Enum): # Enum for parsing requests from ws consumers class RPCRequestType(str, Enum): SUBSCRIBE = 'subscribe' - INITIAL_DATA = 'initial_data' + + WHITELIST = 'whitelist' + ANALYZED_DF = 'analyzed_df' diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 52507106d..cf5b6cde0 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -33,7 +33,7 @@ async def _process_consumer_request( return if not isinstance(data, list): - logger.error(f"Improper request from channel: {channel} - {request}") + logger.error(f"Improper subscribe request from channel: {channel} - {request}") return # If all topics passed are a valid RPCMessageType, set subscriptions on channel @@ -42,19 +42,19 @@ async def _process_consumer_request( logger.debug(f"{channel} subscribed to topics: {data}") channel.set_subscriptions(data) - elif type == RPCRequestType.INITIAL_DATA: - # Acquire the data - initial_data = rpc._ws_initial_data() + elif type == RPCRequestType.WHITELIST: + # They requested the whitelist + whitelist = rpc._ws_request_whitelist() - # We now loop over it sending it in pieces - whitelist_data, analyzed_df = initial_data.get('whitelist'), initial_data.get('analyzed_df') + await channel.send({"type": RPCMessageType.WHITELIST, "data": whitelist}) - if whitelist_data: - await channel.send({"type": RPCMessageType.WHITELIST, "data": whitelist_data}) + elif type == RPCRequestType.ANALYZED_DF: + # They requested the full historical analyzed dataframes + analyzed_df = rpc._ws_request_analyzed_df() - if analyzed_df: - for pair, message in analyzed_df.items(): - await channel.send({"type": RPCMessageType.ANALYZED_DF, "data": message}) + # For every dataframe, send as a separate message + for _, message in analyzed_df.items(): + await channel.send({"type": RPCMessageType.ANALYZED_DF, "data": message}) @router.websocket("/message/ws") diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 4c7f6570d..c925624f8 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -158,10 +158,12 @@ class ExternalMessageConsumer: self.compose_consumer_request(RPCRequestType.SUBSCRIBE, self.topics) ) - # Now request the initial data from this Producer - await channel.send( - self.compose_consumer_request(RPCRequestType.INITIAL_DATA) - ) + # Now request the initial data from this Producer for every topic + # we've subscribed to + for topic in self.topics: + # without .upper() we get KeyError + request_type = RPCRequestType[topic.upper()] + await channel.send(self.compose_consumer_request(request_type)) # Now receive data, if none is within the time limit, ping while True: @@ -191,9 +193,12 @@ class ExternalMessageConsumer: await asyncio.sleep(self.sleep_time) break - except Exception as e: - logger.exception(e) - continue + + # Catch invalid ws_url, and break the loop + except websockets.exceptions.InvalidURI as e: + logger.error(f"{ws_url} is an invalid WebSocket URL - {e}") + break + except ( socket.gaierror, ConnectionRefusedError, @@ -204,9 +209,9 @@ class ExternalMessageConsumer: continue - # Catch invalid ws_url, and break the loop - except websockets.exceptions.InvalidURI as e: - logger.error(f"{ws_url} is an invalid WebSocket URL - {e}") + except Exception as e: + # An unforseen error has occurred, log and stop + logger.exception(e) break def compose_consumer_request( diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 96b43f36b..378677e44 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -1068,13 +1068,14 @@ class RPC: return _data - def _ws_initial_data(self): - """ Websocket friendly initial data, whitelists and all analyzed dataframes """ + def _ws_request_analyzed_df(self): + """ Historical Analyzed Dataframes for WebSocket """ whitelist = self._freqtrade.active_pair_whitelist - # We only get the last 500 candles, should we remove the limit? - analyzed_df = self._ws_all_analysed_dataframes(whitelist, 500) + return self._ws_all_analysed_dataframes(whitelist, 500) - return {"whitelist": whitelist, "analyzed_df": analyzed_df} + def _ws_request_whitelist(self): + """ Whitelist data for WebSocket """ + return self._freqtrade.active_pair_whitelist @ staticmethod def _rpc_analysed_history_full(config, pair: str, timeframe: str, From 5b0b802f311f0999412482a1722e87afe306892d Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 2 Sep 2022 00:05:36 -0600 Subject: [PATCH 028/115] hybrid json ws serializer --- freqtrade/rpc/api_server/ws/channel.py | 5 +++-- freqtrade/rpc/api_server/ws/serializer.py | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index b47fe7550..8891d3296 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -3,7 +3,8 @@ from threading import RLock from typing import List, Type from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy -from freqtrade.rpc.api_server.ws.serializer import RapidJSONWebSocketSerializer, WebSocketSerializer +from freqtrade.rpc.api_server.ws.serializer import (HybridJSONWebSocketSerializer, + WebSocketSerializer) from freqtrade.rpc.api_server.ws.types import WebSocketType @@ -18,7 +19,7 @@ class WebSocketChannel: def __init__( self, websocket: WebSocketType, - serializer_cls: Type[WebSocketSerializer] = RapidJSONWebSocketSerializer + serializer_cls: Type[WebSocketSerializer] = HybridJSONWebSocketSerializer ): # The WebSocket object self._websocket = WebSocketProxy(websocket) diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py index c11ca9a99..109708cc9 100644 --- a/freqtrade/rpc/api_server/ws/serializer.py +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -3,6 +3,7 @@ import logging from abc import ABC, abstractmethod import msgpack +import orjson import rapidjson from pandas import DataFrame @@ -55,6 +56,14 @@ class RapidJSONWebSocketSerializer(WebSocketSerializer): return rapidjson.loads(data, object_hook=_json_object_hook) +class HybridJSONWebSocketSerializer(WebSocketSerializer): + def _serialize(self, data): + return orjson.dumps(data, default=_json_default) + + def _deserialize(self, data): + return rapidjson.loads(data, object_hook=_json_object_hook) + + class MsgPackWebSocketSerializer(WebSocketSerializer): def _serialize(self, data): return msgpack.packb(data, use_bin_type=True) From cf917ad2f5b983f11ca1032a7f3f9b4742c88ca0 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 2 Sep 2022 15:05:16 -0600 Subject: [PATCH 029/115] initial candle request limit, better error reporting, split up _handle_producer_connection --- freqtrade/constants.py | 8 +- freqtrade/rpc/api_server/api_ws.py | 27 ++++-- freqtrade/rpc/api_server/ws/channel.py | 14 ++- freqtrade/rpc/api_server/ws/proxy.py | 10 +- freqtrade/rpc/external_message_consumer.py | 106 ++++++++++++++------- freqtrade/rpc/rpc.py | 4 +- 6 files changed, 119 insertions(+), 50 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 63222f2ff..352e48148 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -505,7 +505,13 @@ CONF_SCHEMA = { 'reply_timeout': {'type': 'integer'}, 'sleep_time': {'type': 'integer'}, 'ping_timeout': {'type': 'integer'}, - 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False} + 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False}, + 'initial_candle_limit': { + 'type': 'integer', + 'minimum': 100, + 'maximum': 1500, + 'default': 500 + } }, 'required': ['producers'] }, diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index cf5b6cde0..95cfd031a 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -26,6 +26,8 @@ async def _process_consumer_request( ): type, data = request.get('type'), request.get('data') + logger.debug(f"Request of type {type} from {channel}") + # If we have a request of type SUBSCRIBE, set the topics in this channel if type == RPCRequestType.SUBSCRIBE: # If the request is empty, do nothing @@ -49,8 +51,16 @@ async def _process_consumer_request( await channel.send({"type": RPCMessageType.WHITELIST, "data": whitelist}) elif type == RPCRequestType.ANALYZED_DF: + limit = None + + if data: + # Limit the amount of candles per dataframe to 'limit' or 1500 + limit = max(data.get('limit', 500), 1500) + # They requested the full historical analyzed dataframes - analyzed_df = rpc._ws_request_analyzed_df() + analyzed_df = rpc._ws_request_analyzed_df(limit) + + logger.debug(f"ANALYZED_DF RESULT: {analyzed_df}") # For every dataframe, send as a separate message for _, message in analyzed_df.items(): @@ -65,32 +75,33 @@ async def message_endpoint( ): try: if is_websocket_alive(ws): - logger.info(f"Consumer connected - {ws.client}") - # TODO: # Return a channel ID, pass that instead of ws to the rest of the methods channel = await channel_manager.on_connect(ws) + logger.info(f"Consumer connected - {channel}") + # Keep connection open until explicitly closed, and process requests try: while not channel.is_closed(): request = await channel.recv() - # Process the request here. Should this be a method of RPC? - logger.info(f"Request: {request}") + # Process the request here await _process_consumer_request(request, channel, rpc) except WebSocketDisconnect: # Handle client disconnects - logger.info(f"Consumer disconnected - {ws.client}") + logger.info(f"Consumer disconnected - {channel}") await channel_manager.on_disconnect(ws) except Exception as e: - logger.info(f"Consumer connection failed - {ws.client}") + logger.info(f"Consumer connection failed - {channel}") logger.exception(e) # Handle cases like - # RuntimeError('Cannot call "send" once a closed message has been sent') await channel_manager.on_disconnect(ws) - except Exception: + except Exception as e: logger.error(f"Failed to serve - {ws.client}") + # Log tracebacks to keep track of what errors are happening + logger.exception(e) await channel_manager.on_disconnect(ws) diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index 8891d3296..1f0cd9c7a 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -1,6 +1,7 @@ import logging from threading import RLock -from typing import List, Type +from typing import List, Optional, Type +from uuid import uuid4 from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy from freqtrade.rpc.api_server.ws.serializer import (HybridJSONWebSocketSerializer, @@ -19,8 +20,12 @@ class WebSocketChannel: def __init__( self, websocket: WebSocketType, + channel_id: Optional[str] = None, serializer_cls: Type[WebSocketSerializer] = HybridJSONWebSocketSerializer ): + + self.channel_id = channel_id if channel_id else uuid4().hex[:8] + # The WebSocket object self._websocket = WebSocketProxy(websocket) # The Serializing class for the WebSocket object @@ -34,6 +39,13 @@ class WebSocketChannel: # Wrap the WebSocket in the Serializing class self._wrapped_ws = self._serializer_cls(self._websocket) + def __repr__(self): + return f"WebSocketChannel({self.channel_id}, {self.remote_addr})" + + @property + def remote_addr(self): + return self._websocket.remote_addr + async def send(self, data): """ Send data on the wrapped websocket diff --git a/freqtrade/rpc/api_server/ws/proxy.py b/freqtrade/rpc/api_server/ws/proxy.py index 6acc1d363..73d1481b9 100644 --- a/freqtrade/rpc/api_server/ws/proxy.py +++ b/freqtrade/rpc/api_server/ws/proxy.py @@ -1,4 +1,4 @@ -from typing import Union +from typing import Any, Tuple, Union from fastapi import WebSocket as FastAPIWebSocket from websockets import WebSocketClientProtocol as WebSocket @@ -15,6 +15,14 @@ class WebSocketProxy: def __init__(self, websocket: WebSocketType): self._websocket: Union[FastAPIWebSocket, WebSocket] = websocket + @property + def remote_addr(self) -> Tuple[Any, ...]: + if hasattr(self._websocket, "remote_address"): + return self._websocket.remote_address + elif hasattr(self._websocket, "client"): + return tuple(self._websocket.client) + return ("unknown", 0) + async def send(self, data): """ Send data on the wrapped websocket diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index c925624f8..3b39b02c8 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -8,7 +8,7 @@ import asyncio import logging import socket from threading import Thread -from typing import Any, Dict, Optional +from typing import Any, Dict, List, Optional import pandas import websockets @@ -54,11 +54,25 @@ class ExternalMessageConsumer: self.ping_timeout = self._emc_config.get('ping_timeout', 2) self.sleep_time = self._emc_config.get('sleep_time', 5) + self.initial_candle_limit = self._emc_config.get('initial_candle_limit', 500) + # Setting these explicitly as they probably shouldn't be changed by a user # Unless we somehow integrate this with the strategy to allow creating # callbacks for the messages self.topics = [RPCMessageType.WHITELIST, RPCMessageType.ANALYZED_DF] + # Allow setting data for each initial request + self._initial_requests: List[Dict[str, Any]] = [ + { + "type": RPCRequestType.WHITELIST, + "data": None + }, + { + "type": RPCRequestType.ANALYZED_DF, + "data": {"limit": self.initial_candle_limit} + } + ] + self._message_handlers = { RPCMessageType.WHITELIST: self._consume_whitelist_message, RPCMessageType.ANALYZED_DF: self._consume_analyzed_df_message, @@ -145,12 +159,14 @@ class ExternalMessageConsumer: while self._running: try: url, token = producer['url'], producer['ws_token'] + name = producer["name"] ws_url = f"{url}?token={token}" # This will raise InvalidURI if the url is bad async with websockets.connect(ws_url) as ws: - logger.info("Connection successful") - channel = WebSocketChannel(ws) + channel = WebSocketChannel(ws, channel_id=name) + + logger.info(f"Producer connection success - {channel}") # Tell the producer we only want these topics # Should always be the first thing we send @@ -158,41 +174,16 @@ class ExternalMessageConsumer: self.compose_consumer_request(RPCRequestType.SUBSCRIBE, self.topics) ) - # Now request the initial data from this Producer for every topic - # we've subscribed to - for topic in self.topics: - # without .upper() we get KeyError - request_type = RPCRequestType[topic.upper()] - await channel.send(self.compose_consumer_request(request_type)) + # Now request the initial data from this Producer + for request in self._initial_requests: + request_type = request.get('type', 'none') # Default to string + request_data = request.get('data') + await channel.send( + self.compose_consumer_request(request_type, request_data) + ) # Now receive data, if none is within the time limit, ping - while True: - try: - message = await asyncio.wait_for( - channel.recv(), - timeout=self.reply_timeout - ) - - async with lock: - # Handle the message - self.handle_producer_message(producer, message) - - except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): - # We haven't received data yet. Check the connection and continue. - try: - # ping - ping = await channel.ping() - - await asyncio.wait_for(ping, timeout=self.ping_timeout) - logger.debug(f"Connection to {url} still alive...") - - continue - except Exception: - logger.info( - f"Ping error {url} - retrying in {self.sleep_time}s") - await asyncio.sleep(self.sleep_time) - - break + await self._receive_messages(channel, producer, lock) # Catch invalid ws_url, and break the loop except websockets.exceptions.InvalidURI as e: @@ -214,6 +205,47 @@ class ExternalMessageConsumer: logger.exception(e) break + async def _receive_messages( + self, + channel: WebSocketChannel, + producer: Dict[str, Any], + lock: asyncio.Lock + ): + """ + Loop to handle receiving messages from a Producer + + :param channel: The WebSocketChannel object for the WebSocket + :param producer: Dictionary containing producer info + :param lock: An asyncio Lock + """ + while True: + try: + message = await asyncio.wait_for( + channel.recv(), + timeout=self.reply_timeout + ) + + async with lock: + # Handle the message + self.handle_producer_message(producer, message) + + except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): + # We haven't received data yet. Check the connection and continue. + try: + # ping + ping = await channel.ping() + + await asyncio.wait_for(ping, timeout=self.ping_timeout) + logger.debug(f"Connection to {channel} still alive...") + + continue + except Exception: + logger.info( + f"Ping error {channel} - retrying in {self.sleep_time}s") + await asyncio.sleep(self.sleep_time) + + break + def compose_consumer_request( self, type_: RPCRequestType, @@ -241,7 +273,7 @@ class ExternalMessageConsumer: if message_data is None: return - logger.debug(f"Received message of type {message_type}") + logger.debug(f"Received message of type {message_type} from `{producer_name}`") message_handler = self._message_handlers.get(message_type) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 378677e44..7b29665eb 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -1068,10 +1068,10 @@ class RPC: return _data - def _ws_request_analyzed_df(self): + def _ws_request_analyzed_df(self, limit: Optional[int]): """ Historical Analyzed Dataframes for WebSocket """ whitelist = self._freqtrade.active_pair_whitelist - return self._ws_all_analysed_dataframes(whitelist, 500) + return self._ws_all_analysed_dataframes(whitelist, limit) def _ws_request_whitelist(self): """ Whitelist data for WebSocket """ From 05cbcf834ce8cec8b858c89725cc5086bad7c970 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 2 Sep 2022 16:01:33 -0600 Subject: [PATCH 030/115] minor logging changes --- freqtrade/rpc/external_message_consumer.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 3b39b02c8..d3b82cadf 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -54,6 +54,7 @@ class ExternalMessageConsumer: self.ping_timeout = self._emc_config.get('ping_timeout', 2) self.sleep_time = self._emc_config.get('sleep_time', 5) + # The amount of candles per dataframe on the initial request self.initial_candle_limit = self._emc_config.get('initial_candle_limit', 500) # Setting these explicitly as they probably shouldn't be changed by a user @@ -73,6 +74,7 @@ class ExternalMessageConsumer: } ] + # Specify which function to use for which RPCMessageType self._message_handlers = { RPCMessageType.WHITELIST: self._consume_whitelist_message, RPCMessageType.ANALYZED_DF: self._consume_analyzed_df_message, @@ -139,7 +141,7 @@ class ExternalMessageConsumer: """ Main connection loop for the consumer - :param producer: Dictionary containing producer info: {'url': '', 'ws_token': ''} + :param producer: Dictionary containing producer info :param lock: An asyncio Lock """ try: @@ -153,7 +155,7 @@ class ExternalMessageConsumer: Actually creates and handles the websocket connection, pinging on timeout and handling connection errors. - :param producer: Dictionary containing producer info: {'url': '', 'ws_token': ''} + :param producer: Dictionary containing producer info :param lock: An asyncio Lock """ while self._running: @@ -176,10 +178,8 @@ class ExternalMessageConsumer: # Now request the initial data from this Producer for request in self._initial_requests: - request_type = request.get('type', 'none') # Default to string - request_data = request.get('data') await channel.send( - self.compose_consumer_request(request_type, request_data) + self.compose_consumer_request(request['type'], request['data']) ) # Now receive data, if none is within the time limit, ping @@ -218,7 +218,7 @@ class ExternalMessageConsumer: :param producer: Dictionary containing producer info :param lock: An asyncio Lock """ - while True: + while self._running: try: message = await asyncio.wait_for( channel.recv(), @@ -273,7 +273,7 @@ class ExternalMessageConsumer: if message_data is None: return - logger.debug(f"Received message of type {message_type} from `{producer_name}`") + logger.info(f"Received message of type {message_type} from `{producer_name}`") message_handler = self._message_handlers.get(message_type) From 160186885404b4b15be4251a80b4ac054d930954 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sun, 4 Sep 2022 09:42:43 -0600 Subject: [PATCH 031/115] dataprovider fix, updated config example --- config_examples/config_full.example.json | 3 +-- freqtrade/data/dataprovider.py | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/config_examples/config_full.example.json b/config_examples/config_full.example.json index d0efa5bb6..2ebad4924 100644 --- a/config_examples/config_full.example.json +++ b/config_examples/config_full.example.json @@ -173,8 +173,7 @@ "CORS_origins": [], "username": "freqtrader", "password": "SuperSecurePassword", - "ws_token": "a_secret_ws_token", - "enable_message_ws": false + "ws_token": "a_secret_ws_token" }, "external_message_consumer": { "enabled": false, diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index ef3067f38..af0f2a70a 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -166,7 +166,7 @@ class DataProvider: # We don't have this data yet, return empty DataFrame and datetime (01-01-1970) return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) - if pair_key not in self.__producer_pairs_df: + if pair_key not in self.__producer_pairs_df[producer_name]: # We don't have this data yet, return empty DataFrame and datetime (01-01-1970) return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) From 07f806a314ec6e963a33b79782e8b658782b235d Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sun, 4 Sep 2022 10:22:10 -0600 Subject: [PATCH 032/115] minor improvements, fixes, old config+constant removal --- .gitignore | 2 -- config_examples/config_full.example.json | 5 +++- freqtrade/constants.py | 3 +- freqtrade/data/dataprovider.py | 33 +++++++++++++++------- freqtrade/freqtradebot.py | 4 --- freqtrade/rpc/api_server/api_auth.py | 1 + freqtrade/rpc/api_server/api_ws.py | 15 +++++++--- freqtrade/rpc/api_server/webserver.py | 5 ++-- freqtrade/rpc/external_message_consumer.py | 6 ++-- freqtrade/strategy/interface.py | 15 ++++------ 10 files changed, 51 insertions(+), 38 deletions(-) diff --git a/.gitignore b/.gitignore index 6a47a7f81..e400c01f5 100644 --- a/.gitignore +++ b/.gitignore @@ -113,5 +113,3 @@ target/ !config_examples/config_full.example.json !config_examples/config_kraken.example.json !config_examples/config_freqai.example.json -!config_examples/config_leader.example.json -!config_examples/config_follower.example.json diff --git a/config_examples/config_full.example.json b/config_examples/config_full.example.json index 2ebad4924..99d695406 100644 --- a/config_examples/config_full.example.json +++ b/config_examples/config_full.example.json @@ -175,12 +175,15 @@ "password": "SuperSecurePassword", "ws_token": "a_secret_ws_token" }, + // The ExternalMessageConsumer config should only be enabled on an instance + // that listens to outside data from another instance. This should not be enabled + // in your producer of data. "external_message_consumer": { "enabled": false, "producers": [ { "name": "default", - "url": "ws://some.freqtrade.bot/api/v1/message/ws", + "url": "ws://localhost:8081/api/v1/message/ws", "ws_token": "a_secret_ws_token" } ], diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 352e48148..bc00d7cfc 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -33,8 +33,7 @@ HYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss', AVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'AgeFilter', 'OffsetFilter', 'PerformanceFilter', 'PrecisionFilter', 'PriceFilter', 'RangeStabilityFilter', - 'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter', - 'ExternalPairList'] + 'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter'] AVAILABLE_PROTECTIONS = ['CooldownPeriod', 'LowProfitPairs', 'MaxDrawdown', 'StoplossGuard'] AVAILABLE_DATAHANDLERS = ['json', 'jsongz', 'hdf5'] BACKTEST_BREAKDOWNS = ['day', 'week', 'month'] diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index af0f2a70a..32152f2f5 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -48,8 +48,11 @@ class DataProvider: self.__producer_pairs: Dict[str, List[str]] = {} self._msg_queue: deque = deque() + self._default_candle_type = self._config.get('candle_type_def', CandleType.SPOT) + self._default_timeframe = self._config.get('timeframe', '1h') + self.__msg_cache = PeriodicCache( - maxsize=1000, ttl=timeframe_to_seconds(self._config.get('timeframe', '1h'))) + maxsize=1000, ttl=timeframe_to_seconds(self._default_timeframe)) self._num_sources = len( self._config.get('external_message_consumer', {}).get('producers', []) @@ -84,7 +87,7 @@ class DataProvider: dataframe, datetime.now(timezone.utc)) # For multiple producers we will want to merge the pairlists instead of overwriting - def set_producer_pairs(self, pairlist: List[str], producer_name: str = "default"): + def _set_producer_pairs(self, pairlist: List[str], producer_name: str = "default"): """ Set the pairs received to later be used. This only supports 1 Producer right now. @@ -101,7 +104,7 @@ class DataProvider: """ return self.__producer_pairs.get(producer_name, []) - def emit_df( + def _emit_df( self, pair_key: PairWithTimeframe, dataframe: DataFrame @@ -123,12 +126,12 @@ class DataProvider: } ) - def add_external_df( + def _add_external_df( self, pair: str, - timeframe: str, dataframe: DataFrame, - candle_type: CandleType, + timeframe: Optional[str] = None, + candle_type: Optional[CandleType] = None, producer_name: str = "default" ) -> None: """ @@ -138,18 +141,22 @@ class DataProvider: :param timeframe: Timeframe to get data for :param candle_type: Any of the enum CandleType (must match trading mode!) """ - pair_key = (pair, timeframe, candle_type) + _timeframe = self._default_timeframe if not timeframe else timeframe + _candle_type = self._default_candle_type if not candle_type else candle_type + + pair_key = (pair, _timeframe, _candle_type) if producer_name not in self.__producer_pairs_df: self.__producer_pairs_df[producer_name] = {} self.__producer_pairs_df[producer_name][pair_key] = (dataframe, datetime.now(timezone.utc)) + logger.debug(f"External DataFrame for {pair_key} from {producer_name} added.") def get_external_df( self, pair: str, - timeframe: str, - candle_type: CandleType, + timeframe: Optional[str] = None, + candle_type: Optional[CandleType] = None, producer_name: str = "default" ) -> Tuple[DataFrame, datetime]: """ @@ -160,16 +167,22 @@ class DataProvider: :param timeframe: Timeframe to get data for :param candle_type: Any of the enum CandleType (must match trading mode!) """ - pair_key = (pair, timeframe, candle_type) + _timeframe = self._default_timeframe if not timeframe else timeframe + _candle_type = self._default_candle_type if not candle_type else candle_type + pair_key = (pair, _timeframe, _candle_type) + + # If we have no data from this Producer yet if producer_name not in self.__producer_pairs_df: # We don't have this data yet, return empty DataFrame and datetime (01-01-1970) return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) + # If we do have data from that Producer, but no data on this pair_key if pair_key not in self.__producer_pairs_df[producer_name]: # We don't have this data yet, return empty DataFrame and datetime (01-01-1970) return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) + # We have it, return this data return self.__producer_pairs_df[producer_name][pair_key] def add_pairlisthandler(self, pairlists) -> None: diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 888994ffb..ce01fc872 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -199,10 +199,6 @@ class FreqtradeBot(LoggingMixin): strategy_safe_wrapper(self.strategy.bot_loop_start, supress_error=True)() - # This just means we won't broadcast dataframes if we're listening to a producer - # Doesn't necessarily NEED to be this way, as maybe we'd like to broadcast - # even if we are using external dataframes in the future. - self.strategy.analyze(self.active_pair_whitelist) with self._exit_lock: diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index fd90918e1..6655dbf86 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -50,6 +50,7 @@ def get_user_from_token(token, secret_key: str, token_type: str = "access"): # This should be reimplemented to better realign with the existing tools provided # by FastAPI regarding API Tokens +# https://github.com/tiangolo/fastapi/blob/master/fastapi/security/api_key.py async def get_ws_token( ws: WebSocket, token: Union[str, None] = None, diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 95cfd031a..d11d1acfe 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -2,23 +2,30 @@ import logging from typing import Any, Dict from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect +# fastapi does not make this available through it, so import directly from starlette +from starlette.websockets import WebSocketState from freqtrade.enums import RPCMessageType, RPCRequestType from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc from freqtrade.rpc.api_server.ws.channel import WebSocketChannel -from freqtrade.rpc.api_server.ws.utils import is_websocket_alive from freqtrade.rpc.rpc import RPC -# from typing import Any, Dict - - logger = logging.getLogger(__name__) # Private router, protected by API Key authentication router = APIRouter() +async def is_websocket_alive(ws: WebSocket) -> bool: + if ( + ws.application_state == WebSocketState.CONNECTED and + ws.client_state == WebSocketState.CONNECTED + ): + return True + return False + + async def _process_consumer_request( request: Dict[str, Any], channel: WebSocketChannel, diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 150c83890..ad93e77a7 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -205,7 +205,7 @@ class ApiServer(RPCHandler): # For testing, shouldn't happen when stable except Exception as e: - logger.info(f"Exception happened in background task: {e}") + logger.exception(f"Exception happened in background task: {e}") def start_api(self): """ @@ -244,8 +244,7 @@ class ApiServer(RPCHandler): if self._standalone: self._server.run() else: - if self._config.get('api_server', {}).get('enable_message_ws', False): - self.start_message_queue() + self.start_message_queue() self._server.run_in_thread() except Exception: logger.exception("Api server failed to start.") diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index d3b82cadf..7f2ac01fb 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -289,7 +289,7 @@ class ExternalMessageConsumer: return # Add the pairlist data to the DataProvider - self._dp.set_producer_pairs(message_data, producer_name=producer_name) + self._dp._set_producer_pairs(message_data, producer_name=producer_name) logger.debug(f"Consumed message from {producer_name} of type RPCMessageType.WHITELIST") @@ -309,8 +309,8 @@ class ExternalMessageConsumer: dataframe = remove_entry_exit_signals(dataframe) # Add the dataframe to the dataprovider - self._dp.add_external_df(pair, timeframe, dataframe, - candle_type, producer_name=producer_name) + self._dp._add_external_df(pair, dataframe, timeframe, + candle_type, producer_name=producer_name) logger.debug( f"Consumed message from {producer_name} of type RPCMessageType.ANALYZED_DF") diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index 7fcae870a..73948a37a 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -700,8 +700,7 @@ class IStrategy(ABC, HyperStrategyMixin): def _analyze_ticker_internal( self, dataframe: DataFrame, - metadata: dict, - emit_df: bool = False + metadata: dict ) -> DataFrame: """ Parses the given candle (OHLCV) data and returns a populated DataFrame @@ -725,7 +724,7 @@ class IStrategy(ABC, HyperStrategyMixin): candle_type = self.config.get('candle_type_def', CandleType.SPOT) self.dp._set_cached_df(pair, self.timeframe, dataframe, candle_type=candle_type) - self.dp.emit_df((pair, self.timeframe, candle_type), dataframe) + self.dp._emit_df((pair, self.timeframe, candle_type), dataframe) else: logger.debug("Skipping TA Analysis for already analyzed candle") @@ -737,8 +736,7 @@ class IStrategy(ABC, HyperStrategyMixin): def analyze_pair( self, - pair: str, - emit_df: bool = False + pair: str ) -> None: """ Fetch data for this pair from dataprovider and analyze. @@ -759,7 +757,7 @@ class IStrategy(ABC, HyperStrategyMixin): dataframe = strategy_safe_wrapper( self._analyze_ticker_internal, message="" - )(dataframe, {'pair': pair}, emit_df) + )(dataframe, {'pair': pair}) self.assert_df(dataframe, df_len, df_close, df_date) except StrategyError as error: @@ -772,15 +770,14 @@ class IStrategy(ABC, HyperStrategyMixin): def analyze( self, - pairs: List[str], - emit_df: bool = False + pairs: List[str] ) -> None: """ Analyze all pairs using analyze_pair(). :param pairs: List of pairs to analyze """ for pair in pairs: - self.analyze_pair(pair, emit_df) + self.analyze_pair(pair) @ staticmethod def preserve_df(dataframe: DataFrame) -> Tuple[int, float, datetime]: From 8a08f8ff8d1d53a13bd7ba47a2fd09426aa9cacf Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sun, 4 Sep 2022 10:27:34 -0600 Subject: [PATCH 033/115] revert rpc manager --- freqtrade/rpc/rpc_manager.py | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index d6374566c..3ba2f9d4d 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -49,17 +49,6 @@ class RPCManager: apiserver.add_rpc_handler(self._rpc) self.registered_modules.append(apiserver) - # Enable External Signals mode - # For this to be enabled, the API server must also be enabled - # if config.get('external_signal', {}).get('enabled', False): - # logger.info('Enabling RPC.ExternalSignalController') - # from freqtrade.rpc.external_signal import ExternalSignalController - # external_signals = ExternalSignalController(self._rpc, config, apiserver) - # self.registered_modules.append(external_signals) - # - # # Attach the controller to FreqTrade - # freqtrade.external_signal_controller = external_signals - def cleanup(self) -> None: """ Stops all enabled rpc modules """ logger.info('Cleaning up rpc modules ...') @@ -78,11 +67,8 @@ class RPCManager: 'status': 'stopping bot' } """ - # Removed actually showing the message because the logs would be - # completely spammed of the json dataframe - logger.info('Sending rpc message of type: %s', msg.get('type')) - # Log actual message in debug? - # logger.debug(msg) + if msg.get('type') is not RPCMessageType.ANALYZED_DF: + logger.info('Sending rpc message: %s', msg) if 'pair' in msg: msg.update({ 'base_currency': self._rpc._freqtrade.exchange.get_pair_base_currency(msg['pair']) From 8f261d8edff162e26ad42876b2a4ce88beb08d45 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 5 Sep 2022 13:47:17 -0600 Subject: [PATCH 034/115] change from bytes to text in websocket, remove old logs --- freqtrade/rpc/api_server/api_ws.py | 2 -- freqtrade/rpc/api_server/ws/channel.py | 3 --- freqtrade/rpc/api_server/ws/proxy.py | 15 +++++++++------ freqtrade/rpc/api_server/ws/serializer.py | 2 ++ 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index d11d1acfe..aaa526401 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -67,8 +67,6 @@ async def _process_consumer_request( # They requested the full historical analyzed dataframes analyzed_df = rpc._ws_request_analyzed_df(limit) - logger.debug(f"ANALYZED_DF RESULT: {analyzed_df}") - # For every dataframe, send as a separate message for _, message in analyzed_df.items(): await channel.send({"type": RPCMessageType.ANALYZED_DF, "data": message}) diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index 1f0cd9c7a..952b3b9f5 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -50,7 +50,6 @@ class WebSocketChannel: """ Send data on the wrapped websocket """ - # logger.info(f"Serialized Send - {self._wrapped_ws._serialize(data)}") await self._wrapped_ws.send(data) async def recv(self): @@ -168,8 +167,6 @@ class ChannelManager: :param direct_channel: The WebSocketChannel object to send data through :param data: The data to send """ - # We iterate over the channels to get reference to the websocket object - # so we can disconnect incase of failure await channel.send(data) def has_channels(self): diff --git a/freqtrade/rpc/api_server/ws/proxy.py b/freqtrade/rpc/api_server/ws/proxy.py index 73d1481b9..ea977a228 100644 --- a/freqtrade/rpc/api_server/ws/proxy.py +++ b/freqtrade/rpc/api_server/ws/proxy.py @@ -27,11 +27,14 @@ class WebSocketProxy: """ Send data on the wrapped websocket """ - if isinstance(data, str): - data = data.encode() - if hasattr(self._websocket, "send_bytes"): - await self._websocket.send_bytes(data) + if not isinstance(data, str): + # We use HybridJSONWebSocketSerializer, which when serialized returns + # bytes because of ORJSON, so we explicitly decode into a string + data = str(data, "utf-8") + + if hasattr(self._websocket, "send_text"): + await self._websocket.send_text(data) else: await self._websocket.send(data) @@ -39,8 +42,8 @@ class WebSocketProxy: """ Receive data on the wrapped websocket """ - if hasattr(self._websocket, "receive_bytes"): - return await self._websocket.receive_bytes() + if hasattr(self._websocket, "receive_text"): + return await self._websocket.receive_text() else: return await self._websocket.recv() diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py index 109708cc9..8ff617f45 100644 --- a/freqtrade/rpc/api_server/ws/serializer.py +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -58,9 +58,11 @@ class RapidJSONWebSocketSerializer(WebSocketSerializer): class HybridJSONWebSocketSerializer(WebSocketSerializer): def _serialize(self, data): + # ORJSON returns bytes return orjson.dumps(data, default=_json_default) def _deserialize(self, data): + # RapidJSON expects strings return rapidjson.loads(data, object_hook=_json_object_hook) From b949ea301c5828612f094c1c5040a67adcd3a47e Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 5 Sep 2022 19:29:07 -0600 Subject: [PATCH 035/115] fix failed apiserver tests --- freqtrade/rpc/api_server/webserver.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index ad93e77a7..6ad3f143e 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -114,6 +114,10 @@ class ApiServer(RPCHandler): self._thread.join() + self._thread = None + self._loop = None + self._background_task = None + @classmethod def shutdown(cls): cls.__initialized = False @@ -169,15 +173,15 @@ class ApiServer(RPCHandler): app.add_exception_handler(RPCException, self.handle_rpc_exception) def start_message_queue(self): + if self._thread: + return + # Create a new loop, as it'll be just for the background thread self._loop = asyncio.new_event_loop() # Start the thread - if not self._thread: - self._thread = Thread(target=self._loop.run_forever) - self._thread.start() - else: - raise RuntimeError("Threaded loop is already running") + self._thread = Thread(target=self._loop.run_forever) + self._thread.start() # Finally, submit the coro to the thread self._background_task = asyncio.run_coroutine_threadsafe( From a0d774fdc4e3be40e4ca138782f38f0db37a88fb Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 5 Sep 2022 20:23:00 -0600 Subject: [PATCH 036/115] change default initial candle limit to 1500 --- freqtrade/constants.py | 3 +-- freqtrade/rpc/external_message_consumer.py | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 03030d930..2279acc13 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -508,9 +508,8 @@ CONF_SCHEMA = { 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False}, 'initial_candle_limit': { 'type': 'integer', - 'minimum': 100, 'maximum': 1500, - 'default': 500 + 'default': 1500 } }, 'required': ['producers'] diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 7f2ac01fb..f0b177647 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -55,7 +55,7 @@ class ExternalMessageConsumer: self.sleep_time = self._emc_config.get('sleep_time', 5) # The amount of candles per dataframe on the initial request - self.initial_candle_limit = self._emc_config.get('initial_candle_limit', 500) + self.initial_candle_limit = self._emc_config.get('initial_candle_limit', 1500) # Setting these explicitly as they probably shouldn't be changed by a user # Unless we somehow integrate this with the strategy to allow creating From d526dfb171a25b99059f21f23c40965ef7ab3837 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 6 Sep 2022 07:03:31 +0200 Subject: [PATCH 037/115] Revert some more changes in rpc_manager --- freqtrade/rpc/rpc_manager.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 3ba2f9d4d..fa2178b1a 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -20,7 +20,6 @@ class RPCManager: def __init__(self, freqtrade) -> None: """ Initializes all enabled rpc modules """ self.registered_modules: List[RPCHandler] = [] - self._freqtrade = freqtrade self._rpc = RPC(freqtrade) config = freqtrade.config # Enable telegram @@ -53,7 +52,7 @@ class RPCManager: """ Stops all enabled rpc modules """ logger.info('Cleaning up rpc modules ...') while self.registered_modules: - mod = self.registered_modules.pop() # popleft to cleanup API server last? + mod = self.registered_modules.pop() logger.info('Cleaning up rpc.%s ...', mod.name) mod.cleanup() del mod From 38f14349e9a70e582e0e1e2acecbbf18ab921385 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 5 Sep 2022 23:25:25 -0600 Subject: [PATCH 038/115] move bytes decoding to serializer --- freqtrade/rpc/api_server/ws/proxy.py | 6 ------ freqtrade/rpc/api_server/ws/serializer.py | 7 +++---- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/freqtrade/rpc/api_server/ws/proxy.py b/freqtrade/rpc/api_server/ws/proxy.py index ea977a228..e43ce6441 100644 --- a/freqtrade/rpc/api_server/ws/proxy.py +++ b/freqtrade/rpc/api_server/ws/proxy.py @@ -27,12 +27,6 @@ class WebSocketProxy: """ Send data on the wrapped websocket """ - - if not isinstance(data, str): - # We use HybridJSONWebSocketSerializer, which when serialized returns - # bytes because of ORJSON, so we explicitly decode into a string - data = str(data, "utf-8") - if hasattr(self._websocket, "send_text"): await self._websocket.send_text(data) else: diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py index 8ff617f45..c0c24bb28 100644 --- a/freqtrade/rpc/api_server/ws/serializer.py +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -57,11 +57,10 @@ class RapidJSONWebSocketSerializer(WebSocketSerializer): class HybridJSONWebSocketSerializer(WebSocketSerializer): - def _serialize(self, data): - # ORJSON returns bytes - return orjson.dumps(data, default=_json_default) + def _serialize(self, data) -> str: + return str(orjson.dumps(data, default=_json_default), "utf-8") - def _deserialize(self, data): + def _deserialize(self, data: str): # RapidJSON expects strings return rapidjson.loads(data, object_hook=_json_object_hook) From 3535aa7724c4a202007841a1efa18c70fe728ab5 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 6 Sep 2022 12:12:05 -0600 Subject: [PATCH 039/115] add last_analyzed to emitted dataframe --- freqtrade/data/dataprovider.py | 10 ++++++++-- freqtrade/rpc/external_message_consumer.py | 21 +++++++++++++-------- freqtrade/rpc/rpc.py | 3 ++- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 76e184296..44296ab40 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -121,7 +121,7 @@ class DataProvider: 'type': RPCMessageType.ANALYZED_DF, 'data': { 'key': pair_key, - 'value': dataframe + 'value': (dataframe, datetime.now(timezone.utc)) } } ) @@ -130,6 +130,7 @@ class DataProvider: self, pair: str, dataframe: DataFrame, + last_analyzed: Optional[str] = None, timeframe: Optional[str] = None, candle_type: Optional[CandleType] = None, producer_name: str = "default" @@ -149,7 +150,12 @@ class DataProvider: if producer_name not in self.__producer_pairs_df: self.__producer_pairs_df[producer_name] = {} - self.__producer_pairs_df[producer_name][pair_key] = (dataframe, datetime.now(timezone.utc)) + if not last_analyzed: + _last_analyzed = datetime.now(timezone.utc) + else: + _last_analyzed = datetime.fromisoformat(last_analyzed) + + self.__producer_pairs_df[producer_name][pair_key] = (dataframe, _last_analyzed) logger.debug(f"External DataFrame for {pair_key} from {producer_name} added.") def get_external_df( diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index f0b177647..28628c1f6 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -10,7 +10,6 @@ import socket from threading import Thread from typing import Any, Dict, List, Optional -import pandas import websockets from freqtrade.data.dataprovider import DataProvider @@ -225,9 +224,12 @@ class ExternalMessageConsumer: timeout=self.reply_timeout ) - async with lock: - # Handle the message - self.handle_producer_message(producer, message) + try: + async with lock: + # Handle the message + self.handle_producer_message(producer, message) + except Exception as e: + logger.exception(f"Error handling producer message: {e}") except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed): # We haven't received data yet. Check the connection and continue. @@ -300,17 +302,20 @@ class ExternalMessageConsumer: key, value = message_data.get('key'), message_data.get('value') - if key and isinstance(value, pandas.DataFrame): + if key and value: pair, timeframe, candle_type = key - dataframe = value + dataframe, last_analyzed = value # If set, remove the Entry and Exit signals from the Producer if self._emc_config.get('remove_entry_exit_signals', False): dataframe = remove_entry_exit_signals(dataframe) # Add the dataframe to the dataprovider - self._dp._add_external_df(pair, dataframe, timeframe, - candle_type, producer_name=producer_name) + self._dp._add_external_df(pair, dataframe, + last_analyzed=last_analyzed, + timeframe=timeframe, + candle_type=candle_type, + producer_name=producer_name) logger.debug( f"Consumed message from {producer_name} of type RPCMessageType.ANALYZED_DF") diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 3757c58c2..98dad278f 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -1064,7 +1064,8 @@ class RPC: for pair in pairlist: dataframe, last_analyzed = self.__rpc_analysed_dataframe_raw(pair, timeframe, limit) - _data[pair] = {"key": (pair, timeframe, candle_type), "value": dataframe} + _data[pair] = {"key": (pair, timeframe, candle_type), + "value": (dataframe, last_analyzed)} return _data From b1c02674492993571c1cbc10144277eb29fda7a9 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 6 Sep 2022 12:40:58 -0600 Subject: [PATCH 040/115] mypy fixes --- freqtrade/rpc/api_server/ws/channel.py | 4 +++- freqtrade/rpc/api_server/ws/proxy.py | 10 ++++++---- freqtrade/rpc/api_server/ws/types.py | 2 +- freqtrade/rpc/external_message_consumer.py | 7 ++++++- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index 952b3b9f5..cffe3092d 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -3,6 +3,8 @@ from threading import RLock from typing import List, Optional, Type from uuid import uuid4 +from fastapi import WebSocket as FastAPIWebSocket + from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy from freqtrade.rpc.api_server.ws.serializer import (HybridJSONWebSocketSerializer, WebSocketSerializer) @@ -105,7 +107,7 @@ class ChannelManager: :param websocket: The WebSocket object to attach to the Channel """ - if hasattr(websocket, "accept"): + if isinstance(websocket, FastAPIWebSocket): try: await websocket.accept() except RuntimeError: diff --git a/freqtrade/rpc/api_server/ws/proxy.py b/freqtrade/rpc/api_server/ws/proxy.py index e43ce6441..da3e04887 100644 --- a/freqtrade/rpc/api_server/ws/proxy.py +++ b/freqtrade/rpc/api_server/ws/proxy.py @@ -1,7 +1,7 @@ from typing import Any, Tuple, Union from fastapi import WebSocket as FastAPIWebSocket -from websockets import WebSocketClientProtocol as WebSocket +from websockets.client import WebSocketClientProtocol as WebSocket from freqtrade.rpc.api_server.ws.types import WebSocketType @@ -17,10 +17,12 @@ class WebSocketProxy: @property def remote_addr(self) -> Tuple[Any, ...]: - if hasattr(self._websocket, "remote_address"): + if isinstance(self._websocket, WebSocket): return self._websocket.remote_address - elif hasattr(self._websocket, "client"): - return tuple(self._websocket.client) + elif isinstance(self._websocket, FastAPIWebSocket): + if self._websocket.client: + client, port = self._websocket.client.host, self._websocket.client.port + return (client, port) return ("unknown", 0) async def send(self, data): diff --git a/freqtrade/rpc/api_server/ws/types.py b/freqtrade/rpc/api_server/ws/types.py index 814fe6649..9855f9e06 100644 --- a/freqtrade/rpc/api_server/ws/types.py +++ b/freqtrade/rpc/api_server/ws/types.py @@ -1,7 +1,7 @@ from typing import Any, Dict, TypeVar from fastapi import WebSocket as FastAPIWebSocket -from websockets import WebSocketClientProtocol as WebSocket +from websockets.client import WebSocketClientProtocol as WebSocket WebSocketType = TypeVar("WebSocketType", FastAPIWebSocket, WebSocket) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 28628c1f6..c1ad0512e 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -8,7 +8,7 @@ import asyncio import logging import socket from threading import Thread -from typing import Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional import websockets @@ -18,6 +18,11 @@ from freqtrade.misc import remove_entry_exit_signals from freqtrade.rpc.api_server.ws.channel import WebSocketChannel +if TYPE_CHECKING: + import websockets.connect + import websockets.exceptions + + logger = logging.getLogger(__name__) From 5934495dda06c4c62950c8eebe77fb431d394eb9 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 7 Sep 2022 15:08:01 -0600 Subject: [PATCH 041/115] add websocket request/message schemas --- freqtrade/data/dataprovider.py | 10 +- freqtrade/rpc/api_server/api_ws.py | 40 ++++++-- freqtrade/rpc/api_server/ws/schema.py | 78 +++++++++++++++ freqtrade/rpc/external_message_consumer.py | 111 +++++++++------------ freqtrade/rpc/rpc.py | 8 +- 5 files changed, 165 insertions(+), 82 deletions(-) create mode 100644 freqtrade/rpc/api_server/ws/schema.py diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 44296ab40..4b5494e97 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -121,7 +121,8 @@ class DataProvider: 'type': RPCMessageType.ANALYZED_DF, 'data': { 'key': pair_key, - 'value': (dataframe, datetime.now(timezone.utc)) + 'df': dataframe, + 'la': datetime.now(timezone.utc) } } ) @@ -130,7 +131,7 @@ class DataProvider: self, pair: str, dataframe: DataFrame, - last_analyzed: Optional[str] = None, + last_analyzed: Optional[datetime] = None, timeframe: Optional[str] = None, candle_type: Optional[CandleType] = None, producer_name: str = "default" @@ -150,10 +151,7 @@ class DataProvider: if producer_name not in self.__producer_pairs_df: self.__producer_pairs_df[producer_name] = {} - if not last_analyzed: - _last_analyzed = datetime.now(timezone.utc) - else: - _last_analyzed = datetime.fromisoformat(last_analyzed) + _last_analyzed = datetime.now(timezone.utc) if not last_analyzed else last_analyzed self.__producer_pairs_df[producer_name][pair_key] = (dataframe, _last_analyzed) logger.debug(f"External DataFrame for {pair_key} from {producer_name} added.") diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index aaa526401..64c1cebb5 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -8,6 +8,8 @@ from starlette.websockets import WebSocketState from freqtrade.enums import RPCMessageType, RPCRequestType from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc from freqtrade.rpc.api_server.ws.channel import WebSocketChannel +from freqtrade.rpc.api_server.ws.schema import (ValidationError, WSAnalyzedDFMessage, + WSRequestSchema, WSWhitelistMessage) from freqtrade.rpc.rpc import RPC @@ -18,6 +20,9 @@ router = APIRouter() async def is_websocket_alive(ws: WebSocket) -> bool: + """ + Check if a FastAPI Websocket is still open + """ if ( ws.application_state == WebSocketState.CONNECTED and ws.client_state == WebSocketState.CONNECTED @@ -31,7 +36,17 @@ async def _process_consumer_request( channel: WebSocketChannel, rpc: RPC ): - type, data = request.get('type'), request.get('data') + """ + Validate and handle a request from a websocket consumer + """ + # Validate the request, makes sure it matches the schema + try: + websocket_request = WSRequestSchema.parse_obj(request) + except ValidationError as e: + logger.error(f"Invalid request from {channel}: {e}") + return + + type, data = websocket_request.type, websocket_request.data logger.debug(f"Request of type {type} from {channel}") @@ -41,35 +56,35 @@ async def _process_consumer_request( if not data: return - if not isinstance(data, list): - logger.error(f"Improper subscribe request from channel: {channel} - {request}") - return - # If all topics passed are a valid RPCMessageType, set subscriptions on channel if all([any(x.value == topic for x in RPCMessageType) for topic in data]): - - logger.debug(f"{channel} subscribed to topics: {data}") channel.set_subscriptions(data) + # We don't send a response for subscriptions + elif type == RPCRequestType.WHITELIST: - # They requested the whitelist + # Get whitelist whitelist = rpc._ws_request_whitelist() - await channel.send({"type": RPCMessageType.WHITELIST, "data": whitelist}) + # Format response + response = WSWhitelistMessage(data=whitelist) + # Send it back + await channel.send(response.dict(exclude_none=True)) elif type == RPCRequestType.ANALYZED_DF: limit = None if data: # Limit the amount of candles per dataframe to 'limit' or 1500 - limit = max(data.get('limit', 500), 1500) + limit = max(data.get('limit', 1500), 1500) # They requested the full historical analyzed dataframes analyzed_df = rpc._ws_request_analyzed_df(limit) # For every dataframe, send as a separate message for _, message in analyzed_df.items(): - await channel.send({"type": RPCMessageType.ANALYZED_DF, "data": message}) + response = WSAnalyzedDFMessage(data=message) + await channel.send(response.dict(exclude_none=True)) @router.websocket("/message/ws") @@ -78,6 +93,9 @@ async def message_endpoint( rpc: RPC = Depends(get_rpc), channel_manager=Depends(get_channel_manager), ): + """ + Message WebSocket endpoint, facilitates sending RPC messages + """ try: if is_websocket_alive(ws): # TODO: diff --git a/freqtrade/rpc/api_server/ws/schema.py b/freqtrade/rpc/api_server/ws/schema.py new file mode 100644 index 000000000..3221911de --- /dev/null +++ b/freqtrade/rpc/api_server/ws/schema.py @@ -0,0 +1,78 @@ +from datetime import datetime +from typing import Any, Dict, List, Optional + +from pandas import DataFrame +from pydantic import BaseModel, ValidationError + +from freqtrade.constants import PairWithTimeframe +from freqtrade.enums.rpcmessagetype import RPCMessageType, RPCRequestType + + +__all__ = ('WSRequestSchema', 'WSMessageSchema', 'ValidationError') + + +class BaseArbitraryModel(BaseModel): + class Config: + arbitrary_types_allowed = True + + +class WSRequestSchema(BaseArbitraryModel): + type: RPCRequestType + data: Optional[Any] = None + + +class WSMessageSchema(BaseArbitraryModel): + type: RPCMessageType + data: Optional[Any] = None + + class Config: + extra = 'allow' + + +# ------------------------------ REQUEST SCHEMAS ---------------------------- + + +class WSSubscribeRequest(WSRequestSchema): + type: RPCRequestType = RPCRequestType.SUBSCRIBE + data: List[RPCMessageType] + + +class WSWhitelistRequest(WSRequestSchema): + type: RPCRequestType = RPCRequestType.WHITELIST + data: None = None + + +class WSAnalyzedDFRequest(WSRequestSchema): + type: RPCRequestType = RPCRequestType.ANALYZED_DF + data: Dict[str, Any] = {"limit": 1500} + + +# ------------------------------ MESSAGE SCHEMAS ---------------------------- + +class WSWhitelistMessage(WSMessageSchema): + type: RPCMessageType = RPCMessageType.WHITELIST + data: List[str] + + +class WSAnalyzedDFMessage(WSMessageSchema): + class AnalyzedDFData(BaseArbitraryModel): + key: PairWithTimeframe + df: DataFrame + la: datetime + + type: RPCMessageType = RPCMessageType.ANALYZED_DF + data: AnalyzedDFData + +# -------------------------------------------------------------------------- + + +if __name__ == "__main__": + message = WSAnalyzedDFMessage( + data={ + "key": ("1", "5m", "spot"), + "df": DataFrame(), + "la": datetime.now() + } + ) + + print(message) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index c1ad0512e..d1e970826 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -8,14 +8,18 @@ import asyncio import logging import socket from threading import Thread -from typing import TYPE_CHECKING, Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List import websockets from freqtrade.data.dataprovider import DataProvider -from freqtrade.enums import RPCMessageType, RPCRequestType +from freqtrade.enums import RPCMessageType from freqtrade.misc import remove_entry_exit_signals from freqtrade.rpc.api_server.ws.channel import WebSocketChannel +from freqtrade.rpc.api_server.ws.schema import (ValidationError, WSAnalyzedDFMessage, + WSAnalyzedDFRequest, WSMessageSchema, + WSRequestSchema, WSSubscribeRequest, + WSWhitelistMessage, WSWhitelistRequest) if TYPE_CHECKING: @@ -67,15 +71,10 @@ class ExternalMessageConsumer: self.topics = [RPCMessageType.WHITELIST, RPCMessageType.ANALYZED_DF] # Allow setting data for each initial request - self._initial_requests: List[Dict[str, Any]] = [ - { - "type": RPCRequestType.WHITELIST, - "data": None - }, - { - "type": RPCRequestType.ANALYZED_DF, - "data": {"limit": self.initial_candle_limit} - } + self._initial_requests: List[WSRequestSchema] = [ + WSSubscribeRequest(data=self.topics), + WSWhitelistRequest(), + WSAnalyzedDFRequest() ] # Specify which function to use for which RPCMessageType @@ -174,16 +173,10 @@ class ExternalMessageConsumer: logger.info(f"Producer connection success - {channel}") - # Tell the producer we only want these topics - # Should always be the first thing we send - await channel.send( - self.compose_consumer_request(RPCRequestType.SUBSCRIBE, self.topics) - ) - # Now request the initial data from this Producer for request in self._initial_requests: await channel.send( - self.compose_consumer_request(request['type'], request['data']) + request.dict(exclude_none=True) ) # Now receive data, if none is within the time limit, ping @@ -253,74 +246,66 @@ class ExternalMessageConsumer: break - def compose_consumer_request( - self, - type_: RPCRequestType, - data: Optional[Any] = None - ) -> Dict[str, Any]: - """ - Create a request for sending to a producer - - :param type_: The RPCRequestType - :param data: The data to send - :returns: Dict[str, Any] - """ - return {'type': type_, 'data': data} - def handle_producer_message(self, producer: Dict[str, Any], message: Dict[str, Any]): """ Handles external messages from a Producer """ producer_name = producer.get('name', 'default') - # Should we have a default message type? - message_type = message.get('type', RPCMessageType.STATUS) - message_data = message.get('data') + + try: + producer_message = WSMessageSchema.parse_obj(message) + except ValidationError as e: + logger.error(f"Invalid message from {producer_name}: {e}") + return # We shouldn't get empty messages - if message_data is None: + if producer_message.data is None: return - logger.info(f"Received message of type {message_type} from `{producer_name}`") + logger.info(f"Received message of type {producer_message.type} from `{producer_name}`") - message_handler = self._message_handlers.get(message_type) + message_handler = self._message_handlers.get(producer_message.type) if not message_handler: - logger.info(f"Received unhandled message: {message_data}, ignoring...") + logger.info(f"Received unhandled message: {producer_message.data}, ignoring...") return - message_handler(producer_name, message_data) + message_handler(producer_name, producer_message) - def _consume_whitelist_message(self, producer_name: str, message_data: Any): - # We expect List[str] - if not isinstance(message_data, list): + def _consume_whitelist_message(self, producer_name: str, message: Any): + try: + # Validate the message + message = WSWhitelistMessage.parse_obj(message) + except ValidationError: return # Add the pairlist data to the DataProvider - self._dp._set_producer_pairs(message_data, producer_name=producer_name) + self._dp._set_producer_pairs(message.data, producer_name=producer_name) - logger.debug(f"Consumed message from {producer_name} of type RPCMessageType.WHITELIST") + logger.debug(f"Consumed message from {producer_name} of type `RPCMessageType.WHITELIST`") - def _consume_analyzed_df_message(self, producer_name: str, message_data: Any): - # We expect a Dict[str, Any] - if not isinstance(message_data, dict): + def _consume_analyzed_df_message(self, producer_name: str, message: Any): + try: + message = WSAnalyzedDFMessage.parse_obj(message) + except ValidationError: return - key, value = message_data.get('key'), message_data.get('value') + key = message.data.key + df = message.data.df + la = message.data.la - if key and value: - pair, timeframe, candle_type = key - dataframe, last_analyzed = value + pair, timeframe, candle_type = key - # If set, remove the Entry and Exit signals from the Producer - if self._emc_config.get('remove_entry_exit_signals', False): - dataframe = remove_entry_exit_signals(dataframe) + # If set, remove the Entry and Exit signals from the Producer + if self._emc_config.get('remove_entry_exit_signals', False): + df = remove_entry_exit_signals(df) - # Add the dataframe to the dataprovider - self._dp._add_external_df(pair, dataframe, - last_analyzed=last_analyzed, - timeframe=timeframe, - candle_type=candle_type, - producer_name=producer_name) + # Add the dataframe to the dataprovider + self._dp._add_external_df(pair, df, + last_analyzed=la, + timeframe=timeframe, + candle_type=candle_type, + producer_name=producer_name) - logger.debug( - f"Consumed message from {producer_name} of type RPCMessageType.ANALYZED_DF") + logger.debug( + f"Consumed message from {producer_name} of type RPCMessageType.ANALYZED_DF") diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index df90b982e..9821bc001 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -1068,8 +1068,12 @@ class RPC: for pair in pairlist: dataframe, last_analyzed = self.__rpc_analysed_dataframe_raw(pair, timeframe, limit) - _data[pair] = {"key": (pair, timeframe, candle_type), - "value": (dataframe, last_analyzed)} + + _data[pair] = { + "key": (pair, timeframe, candle_type), + "df": dataframe, + "la": last_analyzed + } return _data From a50923f7963a58bddd76284cf470979eb7db0695 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 7 Sep 2022 17:14:26 -0600 Subject: [PATCH 042/115] add producers attribute to dataprovider --- freqtrade/data/dataprovider.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 4b5494e97..8ca638046 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -54,10 +54,8 @@ class DataProvider: self.__msg_cache = PeriodicCache( maxsize=1000, ttl=timeframe_to_seconds(self._default_timeframe)) - self._num_sources = len( - self._config.get('external_message_consumer', {}).get('producers', []) - ) - self.external_data_enabled = self._num_sources > 0 + self.producers = self._config.get('external_message_consumer', {}).get('producers', []) + self.external_data_enabled = len(self.producers) > 0 def _set_dataframe_max_index(self, limit_index: int): """ From 045c3f0f3ae7f27fc8702ec12680060d9c896d09 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 8 Sep 2022 07:01:37 +0200 Subject: [PATCH 043/115] Reduce diff by avoiding unnecessary changes --- freqtrade/misc.py | 2 +- freqtrade/strategy/interface.py | 34 ++++++++------------------------- tests/rpc/test_rpc_apiserver.py | 1 - 3 files changed, 9 insertions(+), 28 deletions(-) diff --git a/freqtrade/misc.py b/freqtrade/misc.py index 6a93b6f26..b2aca5fd6 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -14,7 +14,7 @@ import pandas import rapidjson from freqtrade.constants import DECIMAL_PER_COIN_FALLBACK, DECIMALS_PER_COIN -from freqtrade.enums.signaltype import SignalTagType, SignalType +from freqtrade.enums import SignalTagType, SignalType logger = logging.getLogger(__name__) diff --git a/freqtrade/strategy/interface.py b/freqtrade/strategy/interface.py index 93a582e80..0a9a155ea 100644 --- a/freqtrade/strategy/interface.py +++ b/freqtrade/strategy/interface.py @@ -698,11 +698,7 @@ class IStrategy(ABC, HyperStrategyMixin): lock_time = timeframe_to_next_date(self.timeframe, candle_date) return PairLocks.is_pair_locked(pair, lock_time, side=side) - def analyze_ticker( - self, - dataframe: DataFrame, - metadata: dict - ) -> DataFrame: + def analyze_ticker(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Parses the given candle (OHLCV) data and returns a populated DataFrame add several TA indicators and entry order signal to it @@ -716,11 +712,7 @@ class IStrategy(ABC, HyperStrategyMixin): dataframe = self.advise_exit(dataframe, metadata) return dataframe - def _analyze_ticker_internal( - self, - dataframe: DataFrame, - metadata: dict - ) -> DataFrame: + def _analyze_ticker_internal(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Parses the given candle (OHLCV) data and returns a populated DataFrame add several TA indicators and buy signal to it @@ -753,20 +745,16 @@ class IStrategy(ABC, HyperStrategyMixin): return dataframe - def analyze_pair( - self, - pair: str - ) -> None: + def analyze_pair(self, pair: str) -> None: """ Fetch data for this pair from dataprovider and analyze. Stores the dataframe into the dataprovider. The analyzed dataframe is then accessible via `dp.get_analyzed_dataframe()`. :param pair: Pair to analyze. """ - candle_type = self.config.get('candle_type_def', CandleType.SPOT) - - dataframe = self.dp.ohlcv(pair, self.timeframe, candle_type) - + dataframe = self.dp.ohlcv( + pair, self.timeframe, candle_type=self.config.get('candle_type_def', CandleType.SPOT) + ) if not isinstance(dataframe, DataFrame) or dataframe.empty: logger.warning('Empty candle (OHLCV) data for pair %s', pair) return @@ -787,10 +775,7 @@ class IStrategy(ABC, HyperStrategyMixin): logger.warning('Empty dataframe for pair %s', pair) return - def analyze( - self, - pairs: List[str] - ) -> None: + def analyze(self, pairs: List[str]) -> None: """ Analyze all pairs using analyze_pair(). :param pairs: List of pairs to analyze @@ -798,7 +783,7 @@ class IStrategy(ABC, HyperStrategyMixin): for pair in pairs: self.analyze_pair(pair) - @ staticmethod + @staticmethod def preserve_df(dataframe: DataFrame) -> Tuple[int, float, datetime]: """ keep some data for dataframes """ return len(dataframe), dataframe["close"].iloc[-1], dataframe["date"].iloc[-1] @@ -1219,9 +1204,6 @@ class IStrategy(ABC, HyperStrategyMixin): dataframe = _create_and_merge_informative_pair( self, dataframe, metadata, inf_data, populate_fn) - # If in follower mode, get analyzed dataframe from leader df's in dp - # otherise run populate_indicators - return self.populate_indicators(dataframe, metadata) def advise_entry(self, dataframe: DataFrame, metadata: dict) -> DataFrame: diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 146303701..5dfa77d8b 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -406,7 +406,6 @@ def test_api_cleanup(default_conf, mocker, caplog): apiserver = ApiServer(default_conf) apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf))) - apiserver.start_api() apiserver.cleanup() assert apiserver._server.cleanup.call_count == 1 From 83770d20fac8d2acd8cf5d8567cc9d85a2b75ad1 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 10:10:32 -0600 Subject: [PATCH 044/115] fix existing freqtradebot tests --- tests/test_freqtradebot.py | 42 +++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index aff0504b3..837a4315f 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -1317,9 +1317,9 @@ def test_create_stoploss_order_invalid_order( assert create_order_mock.call_args[1]['amount'] == trade.amount # Rpc is sending first buy, then sell - assert rpc_mock.call_count == 2 - assert rpc_mock.call_args_list[1][0][0]['sell_reason'] == ExitType.EMERGENCY_EXIT.value - assert rpc_mock.call_args_list[1][0][0]['order_type'] == 'market' + assert rpc_mock.call_count == 3 + assert rpc_mock.call_args_list[2][0][0]['sell_reason'] == ExitType.EMERGENCY_EXIT.value + assert rpc_mock.call_args_list[2][0][0]['order_type'] == 'market' @pytest.mark.parametrize("is_short", [False, True]) @@ -2434,7 +2434,7 @@ def test_manage_open_orders_entry_usercustom( # Trade should be closed since the function returns true freqtrade.manage_open_orders() assert cancel_order_wr_mock.call_count == 1 - assert rpc_mock.call_count == 1 + assert rpc_mock.call_count == 2 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() nb_trades = len(trades) assert nb_trades == 0 @@ -2473,7 +2473,7 @@ def test_manage_open_orders_entry( # check it does cancel buy orders over the time limit freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 1 - assert rpc_mock.call_count == 1 + assert rpc_mock.call_count == 2 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() nb_trades = len(trades) assert nb_trades == 0 @@ -2603,7 +2603,7 @@ def test_check_handle_cancelled_buy( # check it does cancel buy orders over the time limit freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 - assert rpc_mock.call_count == 1 + assert rpc_mock.call_count == 2 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() assert len(trades) == 0 assert log_has_re( @@ -2634,7 +2634,7 @@ def test_manage_open_orders_buy_exception( # check it does cancel buy orders over the time limit freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 - assert rpc_mock.call_count == 0 + assert rpc_mock.call_count == 1 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() nb_trades = len(trades) assert nb_trades == 1 @@ -2681,7 +2681,7 @@ def test_manage_open_orders_exit_usercustom( # Return false - No impact freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 - assert rpc_mock.call_count == 0 + assert rpc_mock.call_count == 1 assert open_trade_usdt.is_open is False assert freqtrade.strategy.check_exit_timeout.call_count == 1 assert freqtrade.strategy.check_entry_timeout.call_count == 0 @@ -2691,7 +2691,7 @@ def test_manage_open_orders_exit_usercustom( # Return Error - No impact freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 - assert rpc_mock.call_count == 0 + assert rpc_mock.call_count == 1 assert open_trade_usdt.is_open is False assert freqtrade.strategy.check_exit_timeout.call_count == 1 assert freqtrade.strategy.check_entry_timeout.call_count == 0 @@ -2701,7 +2701,7 @@ def test_manage_open_orders_exit_usercustom( freqtrade.strategy.check_entry_timeout = MagicMock(return_value=True) freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 1 - assert rpc_mock.call_count == 1 + assert rpc_mock.call_count == 2 assert open_trade_usdt.is_open is True assert freqtrade.strategy.check_exit_timeout.call_count == 1 assert freqtrade.strategy.check_entry_timeout.call_count == 0 @@ -2761,7 +2761,7 @@ def test_manage_open_orders_exit( # check it does cancel sell orders over the time limit freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 1 - assert rpc_mock.call_count == 1 + assert rpc_mock.call_count == 2 assert open_trade_usdt.is_open is True # Custom user sell-timeout is never called assert freqtrade.strategy.check_exit_timeout.call_count == 0 @@ -2800,7 +2800,7 @@ def test_check_handle_cancelled_exit( # check it does cancel sell orders over the time limit freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 - assert rpc_mock.call_count == 1 + assert rpc_mock.call_count == 2 assert open_trade_usdt.is_open is True exit_name = 'Buy' if is_short else 'Sell' assert log_has_re(f"{exit_name} order cancelled on exchange for Trade.*", caplog) @@ -2838,7 +2838,7 @@ def test_manage_open_orders_partial( # note this is for a partially-complete buy order freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 1 - assert rpc_mock.call_count == 2 + assert rpc_mock.call_count == 3 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() assert len(trades) == 1 assert trades[0].amount == 23.0 @@ -2885,7 +2885,7 @@ def test_manage_open_orders_partial_fee( assert log_has_re(r"Applying fee on amount for Trade.*", caplog) assert cancel_order_mock.call_count == 1 - assert rpc_mock.call_count == 2 + assert rpc_mock.call_count == 3 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() assert len(trades) == 1 # Verify that trade has been updated @@ -2935,7 +2935,7 @@ def test_manage_open_orders_partial_except( assert log_has_re(r"Could not update trade amount: .*", caplog) assert cancel_order_mock.call_count == 1 - assert rpc_mock.call_count == 2 + assert rpc_mock.call_count == 3 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() assert len(trades) == 1 # Verify that trade has been updated @@ -3150,7 +3150,7 @@ def test_handle_cancel_exit_limit(mocker, default_conf_usdt, fee) -> None: reason = CANCEL_REASON['TIMEOUT'] assert freqtrade.handle_cancel_exit(trade, order, reason) assert cancel_order_mock.call_count == 1 - assert send_msg_mock.call_count == 1 + assert send_msg_mock.call_count == 2 assert trade.close_rate is None assert trade.exit_reason is None @@ -3583,7 +3583,7 @@ def test_execute_trade_exit_with_stoploss_on_exchange( trade.is_short = is_short assert trade assert cancel_order.call_count == 1 - assert rpc_mock.call_count == 3 + assert rpc_mock.call_count == 4 @pytest.mark.parametrize("is_short", [False, True]) @@ -3653,10 +3653,10 @@ def test_may_execute_trade_exit_after_stoploss_on_exchange_hit( assert trade.stoploss_order_id is None assert trade.is_open is False assert trade.exit_reason == ExitType.STOPLOSS_ON_EXCHANGE.value - assert rpc_mock.call_count == 3 - assert rpc_mock.call_args_list[0][0][0]['type'] == RPCMessageType.ENTRY - assert rpc_mock.call_args_list[1][0][0]['type'] == RPCMessageType.ENTRY_FILL - assert rpc_mock.call_args_list[2][0][0]['type'] == RPCMessageType.EXIT_FILL + assert rpc_mock.call_count == 4 + assert rpc_mock.call_args_list[1][0][0]['type'] == RPCMessageType.ENTRY + assert rpc_mock.call_args_list[2][0][0]['type'] == RPCMessageType.ENTRY_FILL + assert rpc_mock.call_args_list[3][0][0]['type'] == RPCMessageType.EXIT_FILL @pytest.mark.parametrize( From 4fac12544385caee6a9a64858bbb445b72ea6989 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 10:14:30 -0600 Subject: [PATCH 045/115] fix apiserver cleanup issues in tests --- tests/rpc/test_rpc_apiserver.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 5dfa77d8b..0efcc00c1 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -54,6 +54,7 @@ def botclient(default_conf, mocker): apiserver.add_rpc_handler(rpc) yield ftbot, TestClient(apiserver.app) # Cleanup ... ? + apiserver.cleanup() finally: ApiServer.shutdown() @@ -261,6 +262,7 @@ def test_api__init__(default_conf, mocker): with pytest.raises(OperationalException, match="RPC Handler already attached."): apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf))) + apiserver.cleanup() ApiServer.shutdown() @@ -388,6 +390,7 @@ def test_api_run(default_conf, mocker, caplog): MagicMock(side_effect=Exception)) apiserver.start_api() assert log_has("Api server failed to start.", caplog) + apiserver.cleanup() ApiServer.shutdown() From 9b752475dbf0c1d6de6e245781ffdb789c54d3b8 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 10:20:03 -0600 Subject: [PATCH 046/115] re-add fix to freqtradebot test --- tests/test_freqtradebot.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index 6f9ed407c..8b95792e5 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -3655,11 +3655,11 @@ def test_may_execute_trade_exit_after_stoploss_on_exchange_hit( assert trade.stoploss_order_id is None assert trade.is_open is False assert trade.exit_reason == ExitType.STOPLOSS_ON_EXCHANGE.value - assert rpc_mock.call_count == 3 - assert rpc_mock.call_args_list[0][0][0]['type'] == RPCMessageType.ENTRY - assert rpc_mock.call_args_list[0][0][0]['amount'] > 20 - assert rpc_mock.call_args_list[1][0][0]['type'] == RPCMessageType.ENTRY_FILL - assert rpc_mock.call_args_list[2][0][0]['type'] == RPCMessageType.EXIT_FILL + assert rpc_mock.call_count == 4 + assert rpc_mock.call_args_list[1][0][0]['type'] == RPCMessageType.ENTRY + assert rpc_mock.call_args_list[1][0][0]['amount'] > 20 + assert rpc_mock.call_args_list[2][0][0]['type'] == RPCMessageType.ENTRY_FILL + assert rpc_mock.call_args_list[3][0][0]['type'] == RPCMessageType.EXIT_FILL @pytest.mark.parametrize( From df3c1261464f8f72063f019ea865759c74b5a18b Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 10:34:37 -0600 Subject: [PATCH 047/115] fix mypy error --- freqtrade/rpc/api_server/api_ws.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 64c1cebb5..8a3fcfba2 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -9,7 +9,8 @@ from freqtrade.enums import RPCMessageType, RPCRequestType from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc from freqtrade.rpc.api_server.ws.channel import WebSocketChannel from freqtrade.rpc.api_server.ws.schema import (ValidationError, WSAnalyzedDFMessage, - WSRequestSchema, WSWhitelistMessage) + WSMessageSchema, WSRequestSchema, + WSWhitelistMessage) from freqtrade.rpc.rpc import RPC @@ -47,6 +48,7 @@ async def _process_consumer_request( return type, data = websocket_request.type, websocket_request.data + response: WSMessageSchema logger.debug(f"Request of type {type} from {channel}") @@ -61,6 +63,7 @@ async def _process_consumer_request( channel.set_subscriptions(data) # We don't send a response for subscriptions + return elif type == RPCRequestType.WHITELIST: # Get whitelist @@ -70,6 +73,7 @@ async def _process_consumer_request( response = WSWhitelistMessage(data=whitelist) # Send it back await channel.send(response.dict(exclude_none=True)) + return elif type == RPCRequestType.ANALYZED_DF: limit = None @@ -86,6 +90,8 @@ async def _process_consumer_request( response = WSAnalyzedDFMessage(data=message) await channel.send(response.dict(exclude_none=True)) + return + @router.websocket("/message/ws") async def message_endpoint( From 379b1cbc9001f38189afc1bd963bcc6f55601ed3 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 10:37:41 -0600 Subject: [PATCH 048/115] remove unnecessary returns --- freqtrade/rpc/api_server/api_ws.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 8a3fcfba2..45cc20e4d 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -73,7 +73,6 @@ async def _process_consumer_request( response = WSWhitelistMessage(data=whitelist) # Send it back await channel.send(response.dict(exclude_none=True)) - return elif type == RPCRequestType.ANALYZED_DF: limit = None @@ -90,8 +89,6 @@ async def _process_consumer_request( response = WSAnalyzedDFMessage(data=message) await channel.send(response.dict(exclude_none=True)) - return - @router.websocket("/message/ws") async def message_endpoint( From b3b0c918d98326df8361e5f03302c7ecbd54be65 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 10:44:03 -0600 Subject: [PATCH 049/115] cleanup old code --- freqtrade/rpc/api_server/ws/schema.py | 12 ------------ freqtrade/rpc/api_server/ws/serializer.py | 10 ---------- freqtrade/rpc/api_server/ws/utils.py | 12 ------------ 3 files changed, 34 deletions(-) delete mode 100644 freqtrade/rpc/api_server/ws/utils.py diff --git a/freqtrade/rpc/api_server/ws/schema.py b/freqtrade/rpc/api_server/ws/schema.py index 3221911de..0baa8d233 100644 --- a/freqtrade/rpc/api_server/ws/schema.py +++ b/freqtrade/rpc/api_server/ws/schema.py @@ -64,15 +64,3 @@ class WSAnalyzedDFMessage(WSMessageSchema): data: AnalyzedDFData # -------------------------------------------------------------------------- - - -if __name__ == "__main__": - message = WSAnalyzedDFMessage( - data={ - "key": ("1", "5m", "spot"), - "df": DataFrame(), - "la": datetime.now() - } - ) - - print(message) diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py index c0c24bb28..d1ddd84f0 100644 --- a/freqtrade/rpc/api_server/ws/serializer.py +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -46,16 +46,6 @@ class JSONWebSocketSerializer(WebSocketSerializer): return json.loads(data, object_hook=_json_object_hook) -# ORJSON does not support .loads(object_hook=x) parameter, so we must use RapidJSON - -class RapidJSONWebSocketSerializer(WebSocketSerializer): - def _serialize(self, data): - return rapidjson.dumps(data, default=_json_default) - - def _deserialize(self, data): - return rapidjson.loads(data, object_hook=_json_object_hook) - - class HybridJSONWebSocketSerializer(WebSocketSerializer): def _serialize(self, data) -> str: return str(orjson.dumps(data, default=_json_default), "utf-8") diff --git a/freqtrade/rpc/api_server/ws/utils.py b/freqtrade/rpc/api_server/ws/utils.py deleted file mode 100644 index 1ceecab88..000000000 --- a/freqtrade/rpc/api_server/ws/utils.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import WebSocket -# fastapi does not make this available through it, so import directly from starlette -from starlette.websockets import WebSocketState - - -async def is_websocket_alive(ws: WebSocket) -> bool: - if ( - ws.application_state == WebSocketState.CONNECTED and - ws.client_state == WebSocketState.CONNECTED - ): - return True - return False From fac6626459ed8faa8da1f790cd89421f8c026ba4 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 10:54:31 -0600 Subject: [PATCH 050/115] update default timeouts --- config_examples/config_full.example.json | 4 ++-- freqtrade/rpc/external_message_consumer.py | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/config_examples/config_full.example.json b/config_examples/config_full.example.json index 9788a0fa9..37c604c72 100644 --- a/config_examples/config_full.example.json +++ b/config_examples/config_full.example.json @@ -187,9 +187,9 @@ "ws_token": "a_secret_ws_token" } ], - "reply_timeout": 10, + "reply_timeout": 30, "ping_timeout": 5, - "sleep_time": 5, + "sleep_time": 10, "remove_entry_exit_signals": false }, "bot_name": "freqtrade", diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index d1e970826..525f4282c 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -58,9 +58,9 @@ class ExternalMessageConsumer: if self.enabled and len(self.producers) < 1: raise ValueError("You must specify at least 1 Producer to connect to.") - self.reply_timeout = self._emc_config.get('reply_timeout', 10) - self.ping_timeout = self._emc_config.get('ping_timeout', 2) - self.sleep_time = self._emc_config.get('sleep_time', 5) + self.reply_timeout = self._emc_config.get('reply_timeout', 30) + self.ping_timeout = self._emc_config.get('ping_timeout', 5) + self.sleep_time = self._emc_config.get('sleep_time', 10) # The amount of candles per dataframe on the initial request self.initial_candle_limit = self._emc_config.get('initial_candle_limit', 1500) From b9e7af1ce235cae8be27309da01df8ae70144100 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 11:25:30 -0600 Subject: [PATCH 051/115] fix ws token auth --- freqtrade/rpc/api_server/api_auth.py | 2 +- freqtrade/rpc/api_server/api_ws.py | 5 +++++ freqtrade/rpc/api_server/webserver.py | 7 ++----- tests/rpc/test_rpc_apiserver.py | 21 ++++++++++++++++++++- 4 files changed, 28 insertions(+), 7 deletions(-) diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index 6655dbf86..0d1378b6d 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -62,7 +62,7 @@ async def get_ws_token( # Just return the token if it matches return token else: - logger.debug("Denying websocket request") + logger.info("Denying websocket request") # If it doesn't match, close the websocket connection await ws.close(code=status.WS_1008_POLICY_VIOLATION) diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 45cc20e4d..384bd4115 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect from starlette.websockets import WebSocketState from freqtrade.enums import RPCMessageType, RPCRequestType +from freqtrade.rpc.api_server.api_auth import get_ws_token from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc from freqtrade.rpc.api_server.ws.channel import WebSocketChannel from freqtrade.rpc.api_server.ws.schema import (ValidationError, WSAnalyzedDFMessage, @@ -95,6 +96,7 @@ async def message_endpoint( ws: WebSocket, rpc: RPC = Depends(get_rpc), channel_manager=Depends(get_channel_manager), + token: str = Depends(get_ws_token) ): """ Message WebSocket endpoint, facilitates sending RPC messages @@ -105,6 +107,9 @@ async def message_endpoint( # Return a channel ID, pass that instead of ws to the rest of the methods channel = await channel_manager.on_connect(ws) + if not channel: + return + logger.info(f"Consumer connected - {channel}") # Keep connection open until explicitly closed, and process requests diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 6ad3f143e..73e80dd48 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -139,8 +139,7 @@ class ApiServer(RPCHandler): ) def configure_app(self, app: FastAPI, config): - from freqtrade.rpc.api_server.api_auth import (get_ws_token, http_basic_or_jwt_token, - router_login) + from freqtrade.rpc.api_server.api_auth import http_basic_or_jwt_token, router_login from freqtrade.rpc.api_server.api_backtest import router as api_backtest from freqtrade.rpc.api_server.api_v1 import router as api_v1 from freqtrade.rpc.api_server.api_v1 import router_public as api_v1_public @@ -155,9 +154,7 @@ class ApiServer(RPCHandler): app.include_router(api_backtest, prefix="/api/v1", dependencies=[Depends(http_basic_or_jwt_token)], ) - app.include_router(ws_router, prefix="/api/v1", - dependencies=[Depends(get_ws_token)] - ) + app.include_router(ws_router, prefix="/api/v1") app.include_router(router_login, prefix="/api/v1", tags=["auth"]) # UI Router MUST be last! app.include_router(router_ui, prefix='') diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 0efcc00c1..ccfe31424 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -10,7 +10,7 @@ from unittest.mock import ANY, MagicMock, PropertyMock import pandas as pd import pytest import uvicorn -from fastapi import FastAPI +from fastapi import FastAPI, WebSocketDisconnect from fastapi.exceptions import HTTPException from fastapi.testclient import TestClient from requests.auth import _basic_auth_str @@ -31,6 +31,7 @@ from tests.conftest import (CURRENT_TEST_STRATEGY, create_mock_trades, get_mock_ BASE_URI = "/api/v1" _TEST_USER = "FreqTrader" _TEST_PASS = "SuperSecurePassword1!" +_TEST_WS_TOKEN = "secret_Ws_t0ken" @pytest.fixture @@ -44,6 +45,7 @@ def botclient(default_conf, mocker): "CORS_origins": ['http://example.com'], "username": _TEST_USER, "password": _TEST_PASS, + "ws_token": _TEST_WS_TOKEN }}) ftbot = get_patched_freqtradebot(mocker, default_conf) @@ -155,6 +157,23 @@ def test_api_auth(): get_user_from_token(b'not_a_token', 'secret1234') +def test_api_ws_auth(botclient): + ftbot, client = botclient + + bad_token = "bad-ws_token" + url = f"/api/v1/message/ws?token={bad_token}" + + with pytest.raises(WebSocketDisconnect): + with client.websocket_connect(url) as websocket: + websocket.receive() + + good_token = _TEST_WS_TOKEN + url = f"/api/v1/message/ws?token={good_token}" + + with client.websocket_connect(url) as websocket: + websocket.send(1) + + def test_api_unauthorized(botclient): ftbot, client = botclient rc = client.get(f"{BASE_URI}/ping") From 2b9c8550b0e6bddc85187958a2cb2816e95c4c2e Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 13:58:28 -0600 Subject: [PATCH 052/115] moved ws_schemas, first ws tests --- freqtrade/rpc/api_server/api_ws.py | 19 ++++++++------- .../{ws/schema.py => ws_schemas.py} | 5 +--- freqtrade/rpc/external_message_consumer.py | 9 +++---- tests/rpc/test_rpc_apiserver.py | 24 +++++++++++++++++-- 4 files changed, 38 insertions(+), 19 deletions(-) rename freqtrade/rpc/api_server/{ws/schema.py => ws_schemas.py} (92%) diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 384bd4115..f6eb59f87 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -2,6 +2,7 @@ import logging from typing import Any, Dict from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect +from pydantic import ValidationError # fastapi does not make this available through it, so import directly from starlette from starlette.websockets import WebSocketState @@ -9,9 +10,8 @@ from freqtrade.enums import RPCMessageType, RPCRequestType from freqtrade.rpc.api_server.api_auth import get_ws_token from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc from freqtrade.rpc.api_server.ws.channel import WebSocketChannel -from freqtrade.rpc.api_server.ws.schema import (ValidationError, WSAnalyzedDFMessage, - WSMessageSchema, WSRequestSchema, - WSWhitelistMessage) +from freqtrade.rpc.api_server.ws_schemas import (WSAnalyzedDFMessage, WSMessageSchema, + WSRequestSchema, WSWhitelistMessage) from freqtrade.rpc.rpc import RPC @@ -102,13 +102,11 @@ async def message_endpoint( Message WebSocket endpoint, facilitates sending RPC messages """ try: - if is_websocket_alive(ws): - # TODO: - # Return a channel ID, pass that instead of ws to the rest of the methods - channel = await channel_manager.on_connect(ws) + # TODO: + # Return a channel ID, pass that instead of ws to the rest of the methods + channel = await channel_manager.on_connect(ws) - if not channel: - return + if await is_websocket_alive(ws): logger.info(f"Consumer connected - {channel}") @@ -131,6 +129,9 @@ async def message_endpoint( # RuntimeError('Cannot call "send" once a closed message has been sent') await channel_manager.on_disconnect(ws) + else: + ws.close() + except Exception as e: logger.error(f"Failed to serve - {ws.client}") # Log tracebacks to keep track of what errors are happening diff --git a/freqtrade/rpc/api_server/ws/schema.py b/freqtrade/rpc/api_server/ws_schemas.py similarity index 92% rename from freqtrade/rpc/api_server/ws/schema.py rename to freqtrade/rpc/api_server/ws_schemas.py index 0baa8d233..255226d84 100644 --- a/freqtrade/rpc/api_server/ws/schema.py +++ b/freqtrade/rpc/api_server/ws_schemas.py @@ -2,15 +2,12 @@ from datetime import datetime from typing import Any, Dict, List, Optional from pandas import DataFrame -from pydantic import BaseModel, ValidationError +from pydantic import BaseModel from freqtrade.constants import PairWithTimeframe from freqtrade.enums.rpcmessagetype import RPCMessageType, RPCRequestType -__all__ = ('WSRequestSchema', 'WSMessageSchema', 'ValidationError') - - class BaseArbitraryModel(BaseModel): class Config: arbitrary_types_allowed = True diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 525f4282c..abeedb0a4 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -11,15 +11,16 @@ from threading import Thread from typing import TYPE_CHECKING, Any, Dict, List import websockets +from pydantic import ValidationError from freqtrade.data.dataprovider import DataProvider from freqtrade.enums import RPCMessageType from freqtrade.misc import remove_entry_exit_signals from freqtrade.rpc.api_server.ws.channel import WebSocketChannel -from freqtrade.rpc.api_server.ws.schema import (ValidationError, WSAnalyzedDFMessage, - WSAnalyzedDFRequest, WSMessageSchema, - WSRequestSchema, WSSubscribeRequest, - WSWhitelistMessage, WSWhitelistRequest) +from freqtrade.rpc.api_server.ws_schemas import (WSAnalyzedDFMessage, WSAnalyzedDFRequest, + WSMessageSchema, WSRequestSchema, + WSSubscribeRequest, WSWhitelistMessage, + WSWhitelistRequest) if TYPE_CHECKING: diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index ccfe31424..de093b66f 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -56,8 +56,8 @@ def botclient(default_conf, mocker): apiserver.add_rpc_handler(rpc) yield ftbot, TestClient(apiserver.app) # Cleanup ... ? - apiserver.cleanup() finally: + apiserver.cleanup() ApiServer.shutdown() @@ -171,7 +171,7 @@ def test_api_ws_auth(botclient): url = f"/api/v1/message/ws?token={good_token}" with client.websocket_connect(url) as websocket: - websocket.send(1) + pass def test_api_unauthorized(botclient): @@ -1685,3 +1685,23 @@ def test_health(botclient): ret = rc.json() assert ret['last_process_ts'] == 0 assert ret['last_process'] == '1970-01-01T00:00:00+00:00' + + +def test_api_ws_subscribe(botclient, mocker): + ftbot, client = botclient + ws_url = f"/api/v1/message/ws?token={_TEST_WS_TOKEN}" + + sub_mock = mocker.patch( + 'freqtrade.rpc.api_server.ws.channel.WebSocketChannel.set_subscriptions', MagicMock()) + + with client.websocket_connect(ws_url) as ws: + ws.send_json({'type': 'subscribe', 'data': ['whitelist']}) + + # Check call count is now 1 as we sent a valid subscribe request + assert sub_mock.call_count == 1 + + with client.websocket_connect(ws_url) as ws: + ws.send_json({'type': 'subscribe', 'data': 'whitelist'}) + + # Call count hasn't changed as the subscribe request was invalid + assert sub_mock.call_count == 1 From c9d4f666c5fa95e4671ea0a4258abf9ff69b7386 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 14:00:22 -0600 Subject: [PATCH 053/115] minor apiserver test change --- tests/rpc/test_rpc_apiserver.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index de093b66f..6a37e7cdd 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -51,13 +51,15 @@ def botclient(default_conf, mocker): ftbot = get_patched_freqtradebot(mocker, default_conf) rpc = RPC(ftbot) mocker.patch('freqtrade.rpc.api_server.ApiServer.start_api', MagicMock()) + apiserver = None try: apiserver = ApiServer(default_conf) apiserver.add_rpc_handler(rpc) yield ftbot, TestClient(apiserver.app) # Cleanup ... ? finally: - apiserver.cleanup() + if apiserver: + apiserver.cleanup() ApiServer.shutdown() From 75cf8dbfe428eb2e3874638cf8ae262bda2768bf Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 15:11:36 -0600 Subject: [PATCH 054/115] missed await --- freqtrade/rpc/api_server/api_ws.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index f6eb59f87..16d5ef9a7 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -130,7 +130,7 @@ async def message_endpoint( await channel_manager.on_disconnect(ws) else: - ws.close() + await ws.close() except Exception as e: logger.error(f"Failed to serve - {ws.client}") From 1466d2d26f5cb90fdc1e6343c8fb604f2a0ca657 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 16:27:09 -0600 Subject: [PATCH 055/115] initial message ws docs --- docs/rest-api.md | 71 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/docs/rest-api.md b/docs/rest-api.md index cc82aadda..5dc7637e5 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -31,7 +31,8 @@ Sample configuration: "jwt_secret_key": "somethingrandom", "CORS_origins": [], "username": "Freqtrader", - "password": "SuperSecret1!" + "password": "SuperSecret1!", + "ws_token": "sercet_Ws_t0ken" }, ``` @@ -66,7 +67,7 @@ secrets.token_hex() !!! Danger "Password selection" Please make sure to select a very strong, unique password to protect your bot from unauthorized access. - Also change `jwt_secret_key` to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!). + Also change `jwt_secret_key` to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!). ### Configuration with docker @@ -274,7 +275,7 @@ reload_config Reload configuration. show_config - + Returns part of the configuration, relevant for trading operations. start @@ -322,6 +323,70 @@ whitelist ``` +### Message WebSocket + +The API Server makes available a websocket endpoint for subscribing to RPC messages +from the FreqTrade Bot. This can be used to consume real-time data from your bot, such as entry/exit fill messages, whitelist changes, populated indicators for pairs, and more. + +Assuming your rest API is set to `127.0.0.1` on port `8080`, the endpoint is available at `http://localhost:8080/api/v1/message/ws`. + +To access the websocket endpoint, the `ws_token` is required as a query parameter in the endpoint URL. This is set in your rest API config section. To generate a safe `ws_token` you can run the following code: + +``` python +>>> import secrets +>>> secrets.token_urlsafe(16) +'zs9XYCbTPKvux46UJckflw' +``` + +You could then connect to the endpoint at `http://localhost:8080/api/v1/message/ws?token=zs9XYCbTPKvux46UJckflw`. + +!!! warning "Warning" + + Please do not use the above example token. To make sure you are secure, generate a completely new token. + + +#### Using the WebSocket + +Once connected to the WebSocket, the bot will broadcast RPC messages to anyone who is subscribed to them. To subscribe to a message, you must first subscribe to the message types. This can be done by sending a JSON request through the WebSocket: + +``` json +{ + "type": "subscribe", + "data": ["whitelist", "analyzed_df"] // A list of string message types +} +``` + +#### Message types + +| Message Type | Description | +|--------------|-------------| +| whitelist | The list of pairs in the bot's whitelist. +| analyzed_df | The dataframe and last_analyzed datetime for a pair. +| entry | Trade has signaled an entry +| entry_fill | Trade enter has filled +| entry_cancel | Trade enter has been canceled +| exit | Trade has signaled an exit +| exit_fill | Trade exit has filled +| exit_cancel | Trade exit has been canceled +| protection_trigger | A protection has triggered for a pair +| protection_trigger_global | A protection has triggered for a pair +| status | A bot's status change +| startup | Startup messages +| warning | Any warnings + +Now anytime those types of RPC messages are sent in the bot, you will receive them through the WebSocket as long as the connection is active. They typically take the same form as the request: + +``` json +{ + "type": "analyzed_df", + "data": { + "key": ["NEO/BTC", "5m", "spot"], + "df": {}, // The dataframe + "la": "2022-09-08 22:14:41.457786+00:00" + } +} +``` + ### OpenAPI interface To enable the builtin openAPI interface (Swagger UI), specify `"enable_openapi": true` in the api_server configuration. From 46cd0ce9948e6d753a4a19b26ff8797d86bcca2c Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 8 Sep 2022 16:30:31 -0600 Subject: [PATCH 056/115] fix sentence in docs --- docs/rest-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/rest-api.md b/docs/rest-api.md index 5dc7637e5..f4ac2c350 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -347,7 +347,7 @@ You could then connect to the endpoint at `http://localhost:8080/api/v1/message/ #### Using the WebSocket -Once connected to the WebSocket, the bot will broadcast RPC messages to anyone who is subscribed to them. To subscribe to a message, you must first subscribe to the message types. This can be done by sending a JSON request through the WebSocket: +Once connected to the WebSocket, the bot will broadcast RPC messages to anyone who is subscribed to them. To subscribe to a list of messages, you must send a JSON request through the WebSocket like the one below. The `data` key must be a list of message type strings. ``` json { From e256ebd7271bf138a381108cb237ab574947d025 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 9 Sep 2022 07:13:05 +0200 Subject: [PATCH 057/115] Add ws_token to auto-generated config --- freqtrade/commands/build_config_commands.py | 1 + freqtrade/enums/rpcmessagetype.py | 1 - freqtrade/rpc/rpc.py | 4 ++-- freqtrade/templates/base_config.json.j2 | 1 + 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/freqtrade/commands/build_config_commands.py b/freqtrade/commands/build_config_commands.py index 01cfa800a..1abd26328 100644 --- a/freqtrade/commands/build_config_commands.py +++ b/freqtrade/commands/build_config_commands.py @@ -211,6 +211,7 @@ def ask_user_config() -> Dict[str, Any]: ) # Force JWT token to be a random string answers['api_server_jwt_key'] = secrets.token_hex() + answers['api_server_ws_token'] = secrets.token_urlsafe(25) return answers diff --git a/freqtrade/enums/rpcmessagetype.py b/freqtrade/enums/rpcmessagetype.py index 929f6d083..fae121a09 100644 --- a/freqtrade/enums/rpcmessagetype.py +++ b/freqtrade/enums/rpcmessagetype.py @@ -1,7 +1,6 @@ from enum import Enum -# We need to inherit from str so we can use as a str class RPCMessageType(str, Enum): STATUS = 'status' WARNING = 'warning' diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 9821bc001..943c1c667 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -1086,7 +1086,7 @@ class RPC: """ Whitelist data for WebSocket """ return self._freqtrade.active_pair_whitelist - @ staticmethod + @staticmethod def _rpc_analysed_history_full(config, pair: str, timeframe: str, timerange: str, exchange) -> Dict[str, Any]: timerange_parsed = TimeRange.parse_timerange(timerange) @@ -1117,7 +1117,7 @@ class RPC: self._freqtrade.strategy.plot_config['subplots'] = {} return self._freqtrade.strategy.plot_config - @ staticmethod + @staticmethod def _rpc_sysinfo() -> Dict[str, Any]: return { "cpu_pct": psutil.cpu_percent(interval=1, percpu=True), diff --git a/freqtrade/templates/base_config.json.j2 b/freqtrade/templates/base_config.json.j2 index 681af84c6..299734a50 100644 --- a/freqtrade/templates/base_config.json.j2 +++ b/freqtrade/templates/base_config.json.j2 @@ -67,6 +67,7 @@ "verbosity": "error", "enable_openapi": false, "jwt_secret_key": "{{ api_server_jwt_key }}", + "ws_token": "{{ api_server_ws_token }}", "CORS_origins": [], "username": "{{ api_server_username }}", "password": "{{ api_server_password }}" From 426f8f37e9f45a8dc7df3bce11b1a0b3ace6c5b3 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 9 Sep 2022 10:45:49 -0600 Subject: [PATCH 058/115] change var names --- freqtrade/constants.py | 2 +- freqtrade/rpc/api_server/webserver.py | 52 +++++++++++----------- freqtrade/rpc/external_message_consumer.py | 8 ++-- 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 2279acc13..e77940b3c 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -502,7 +502,7 @@ CONF_SCHEMA = { 'required': ['name', 'url', 'ws_token'] } }, - 'reply_timeout': {'type': 'integer'}, + 'wait_timeout': {'type': 'integer'}, 'sleep_time': {'type': 'integer'}, 'ping_timeout': {'type': 'integer'}, 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False}, diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 73e80dd48..557857ecc 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -49,9 +49,9 @@ class ApiServer(RPCHandler): # Exchange - only available in webserver mode. _exchange = None # websocket message queue stuff - _channel_manager = None - _thread = None - _loop = None + _ws_channel_manager = None + _ws_thread = None + _ws_loop = None def __new__(cls, *args, **kwargs): """ @@ -69,14 +69,14 @@ class ApiServer(RPCHandler): return self._standalone: bool = standalone self._server = None - self._queue = None - self._background_task = None + self._ws_queue = None + self._ws_background_task = None ApiServer.__initialized = True api_config = self._config['api_server'] - ApiServer._channel_manager = ChannelManager() + ApiServer._ws_channel_manager = ChannelManager() self.app = FastAPI(title="Freqtrade API", docs_url='/docs' if api_config.get('enable_openapi', False) else None, @@ -105,18 +105,18 @@ class ApiServer(RPCHandler): logger.info("Stopping API Server") self._server.cleanup() - if self._thread and self._loop: + if self._ws_thread and self._ws_loop: logger.info("Stopping API Server background tasks") - if self._background_task: + if self._ws_background_task: # Cancel the queue task - self._background_task.cancel() + self._ws_background_task.cancel() - self._thread.join() + self._ws_thread.join() - self._thread = None - self._loop = None - self._background_task = None + self._ws_thread = None + self._ws_loop = None + self._ws_background_task = None @classmethod def shutdown(cls): @@ -127,8 +127,8 @@ class ApiServer(RPCHandler): cls._rpc = None def send_msg(self, msg: Dict[str, str]) -> None: - if self._queue: - sync_q = self._queue.sync_q + if self._ws_queue: + sync_q = self._ws_queue.sync_q sync_q.put(msg) def handle_rpc_exception(self, request, exc): @@ -170,24 +170,24 @@ class ApiServer(RPCHandler): app.add_exception_handler(RPCException, self.handle_rpc_exception) def start_message_queue(self): - if self._thread: + if self._ws_thread: return # Create a new loop, as it'll be just for the background thread - self._loop = asyncio.new_event_loop() + self._ws_loop = asyncio.new_event_loop() # Start the thread - self._thread = Thread(target=self._loop.run_forever) - self._thread.start() + self._ws_thread = Thread(target=self._ws_loop.run_forever) + self._ws_thread.start() # Finally, submit the coro to the thread - self._background_task = asyncio.run_coroutine_threadsafe( - self._broadcast_queue_data(), loop=self._loop) + self._ws_background_task = asyncio.run_coroutine_threadsafe( + self._broadcast_queue_data(), loop=self._ws_loop) async def _broadcast_queue_data(self): # Instantiate the queue in this coroutine so it's attached to our loop - self._queue = ThreadedQueue() - async_queue = self._queue.async_q + self._ws_queue = ThreadedQueue() + async_queue = self._ws_queue.async_q try: while True: @@ -196,13 +196,13 @@ class ApiServer(RPCHandler): message = await async_queue.get() logger.debug(f"Found message of type: {message.get('type')}") # Broadcast it - await self._channel_manager.broadcast(message) + await self._ws_channel_manager.broadcast(message) # Sleep, make this configurable? await asyncio.sleep(0.1) except asyncio.CancelledError: # Disconnect channels and stop the loop on cancel - await self._channel_manager.disconnect_all() - self._loop.stop() + await self._ws_channel_manager.disconnect_all() + self._ws_loop.stop() # For testing, shouldn't happen when stable except Exception as e: diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index abeedb0a4..1c2a27617 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -59,9 +59,9 @@ class ExternalMessageConsumer: if self.enabled and len(self.producers) < 1: raise ValueError("You must specify at least 1 Producer to connect to.") - self.reply_timeout = self._emc_config.get('reply_timeout', 30) - self.ping_timeout = self._emc_config.get('ping_timeout', 5) - self.sleep_time = self._emc_config.get('sleep_time', 10) + self.wait_timeout = self._emc_config.get('wait_timeout', 300) # in seconds + self.ping_timeout = self._emc_config.get('ping_timeout', 10) # in seconds + self.sleep_time = self._emc_config.get('sleep_time', 10) # in seconds # The amount of candles per dataframe on the initial request self.initial_candle_limit = self._emc_config.get('initial_candle_limit', 1500) @@ -220,7 +220,7 @@ class ExternalMessageConsumer: try: message = await asyncio.wait_for( channel.recv(), - timeout=self.reply_timeout + timeout=self.wait_timeout ) try: From 445ab1beeed411531dbe2ba27cba7c026c83949a Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 9 Sep 2022 10:56:54 -0600 Subject: [PATCH 059/115] update docs --- docs/rest-api.md | 48 ++++++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/docs/rest-api.md b/docs/rest-api.md index f4ac2c350..485fca6b5 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -330,15 +330,36 @@ from the FreqTrade Bot. This can be used to consume real-time data from your bot Assuming your rest API is set to `127.0.0.1` on port `8080`, the endpoint is available at `http://localhost:8080/api/v1/message/ws`. -To access the websocket endpoint, the `ws_token` is required as a query parameter in the endpoint URL. This is set in your rest API config section. To generate a safe `ws_token` you can run the following code: +To access the websocket endpoint, the `ws_token` is required as a query parameter in the endpoint URL. + + + To generate a safe `ws_token` you can run the following code: ``` python >>> import secrets ->>> secrets.token_urlsafe(16) -'zs9XYCbTPKvux46UJckflw' +>>> secrets.token_urlsafe(25) +'hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q' ``` -You could then connect to the endpoint at `http://localhost:8080/api/v1/message/ws?token=zs9XYCbTPKvux46UJckflw`. + +You would then add that token under `ws_token` in your `api_server` config. Like so: + +``` json +"api_server": { + "enabled": true, + "listen_ip_address": "127.0.0.1", + "listen_port": 8080, + "verbosity": "error", + "enable_openapi": false, + "jwt_secret_key": "somethingrandom", + "CORS_origins": [], + "username": "Freqtrader", + "password": "SuperSecret1!", + "ws_token": "hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q" // <----- +}, +``` + +You could then connect to the endpoint at `http://localhost:8080/api/v1/message/ws?token=hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q`. !!! warning "Warning" @@ -355,24 +376,7 @@ Once connected to the WebSocket, the bot will broadcast RPC messages to anyone w "data": ["whitelist", "analyzed_df"] // A list of string message types } ``` - -#### Message types - -| Message Type | Description | -|--------------|-------------| -| whitelist | The list of pairs in the bot's whitelist. -| analyzed_df | The dataframe and last_analyzed datetime for a pair. -| entry | Trade has signaled an entry -| entry_fill | Trade enter has filled -| entry_cancel | Trade enter has been canceled -| exit | Trade has signaled an exit -| exit_fill | Trade exit has filled -| exit_cancel | Trade exit has been canceled -| protection_trigger | A protection has triggered for a pair -| protection_trigger_global | A protection has triggered for a pair -| status | A bot's status change -| startup | Startup messages -| warning | Any warnings +For a list of message types, please refer to the RPCMessageType enum in `freqtrade/enums/rpcmessagetype.py` Now anytime those types of RPC messages are sent in the bot, you will receive them through the WebSocket as long as the connection is active. They typically take the same form as the request: From ad9659769331c718098f2ee8acc17c0fbf3ebca0 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 9 Sep 2022 10:59:38 -0600 Subject: [PATCH 060/115] wording --- docs/rest-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/rest-api.md b/docs/rest-api.md index 485fca6b5..704f38f00 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -359,7 +359,7 @@ You would then add that token under `ws_token` in your `api_server` config. Like }, ``` -You could then connect to the endpoint at `http://localhost:8080/api/v1/message/ws?token=hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q`. +You can now connect to the endpoint at `http://localhost:8080/api/v1/message/ws?token=hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q`. !!! warning "Warning" From 09679cc79814d7921280846f1291d169ffe23b97 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 9 Sep 2022 11:27:20 -0600 Subject: [PATCH 061/115] fix dependency --- freqtrade/rpc/api_server/deps.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server/deps.py b/freqtrade/rpc/api_server/deps.py index 360771d77..abd3db036 100644 --- a/freqtrade/rpc/api_server/deps.py +++ b/freqtrade/rpc/api_server/deps.py @@ -42,7 +42,7 @@ def get_exchange(config=Depends(get_config)): def get_channel_manager(): - return ApiServer._channel_manager + return ApiServer._ws_channel_manager def is_webserver_mode(config=Depends(get_config)): From 6cbc03a96a6ca4234ec1ef06153927894ae38f35 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 9 Sep 2022 11:38:42 -0600 Subject: [PATCH 062/115] support jwt token in place of ws token --- freqtrade/rpc/api_server/api_auth.py | 32 ++++++++++++++++++++-------- freqtrade/rpc/api_server/api_ws.py | 4 ++++ tests/rpc/test_rpc_apiserver.py | 12 ++++++----- 3 files changed, 34 insertions(+), 14 deletions(-) diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index 0d1378b6d..a2b722f0a 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -4,7 +4,7 @@ from datetime import datetime, timedelta from typing import Any, Dict, Union import jwt -from fastapi import APIRouter, Depends, HTTPException, WebSocket, status +from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, status from fastapi.security import OAuth2PasswordBearer from fastapi.security.http import HTTPBasic, HTTPBasicCredentials @@ -29,7 +29,8 @@ httpbasic = HTTPBasic(auto_error=False) oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False) -def get_user_from_token(token, secret_key: str, token_type: str = "access"): +def get_user_from_token(token, secret_key: str, token_type: str = "access", + raise_on_error: bool = True) -> Union[bool, str]: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", @@ -39,12 +40,21 @@ def get_user_from_token(token, secret_key: str, token_type: str = "access"): payload = jwt.decode(token, secret_key, algorithms=[ALGORITHM]) username: str = payload.get("identity", {}).get('u') if username is None: - raise credentials_exception + if raise_on_error: + raise credentials_exception + else: + return False if payload.get("type") != token_type: - raise credentials_exception + if raise_on_error: + raise credentials_exception + else: + return False except jwt.PyJWTError: - raise credentials_exception + if raise_on_error: + raise credentials_exception + else: + return False return username @@ -53,14 +63,18 @@ def get_user_from_token(token, secret_key: str, token_type: str = "access"): # https://github.com/tiangolo/fastapi/blob/master/fastapi/security/api_key.py async def get_ws_token( ws: WebSocket, - token: Union[str, None] = None, + ws_token: Union[str, None] = Query(..., alias="token"), api_config: Dict[str, Any] = Depends(get_api_config) ): - secret_ws_token = api_config['ws_token'] + secret_ws_token = api_config.get('ws_token', 'secret_ws_t0ken.') + secret_jwt_key = api_config.get('jwt_secret_key', 'super-secret') - if token == secret_ws_token: + if secrets.compare_digest(secret_ws_token, ws_token): # Just return the token if it matches - return token + return ws_token + elif user := get_user_from_token(ws_token, secret_jwt_key, raise_on_error=False): + # If the token is a jwt, and it's valid return the user + return user else: logger.info("Denying websocket request") # If it doesn't match, close the websocket connection diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 16d5ef9a7..25d29a7ce 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -132,6 +132,10 @@ async def message_endpoint( else: await ws.close() + except RuntimeError: + # WebSocket was closed + await channel_manager.on_disconnect(ws) + except Exception as e: logger.error(f"Failed to serve - {ws.client}") # Log tracebacks to keep track of what errors are happening diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 6a37e7cdd..f1aa465f0 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -161,18 +161,20 @@ def test_api_auth(): def test_api_ws_auth(botclient): ftbot, client = botclient + def url(token): return f"/api/v1/message/ws?token={token}" bad_token = "bad-ws_token" - url = f"/api/v1/message/ws?token={bad_token}" - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect(url) as websocket: + with client.websocket_connect(url(bad_token)) as websocket: websocket.receive() good_token = _TEST_WS_TOKEN - url = f"/api/v1/message/ws?token={good_token}" + with client.websocket_connect(url(good_token)) as websocket: + pass - with client.websocket_connect(url) as websocket: + jwt_secret = ftbot.config['api_server'].get('jwt_secret_key', 'super-secret') + jwt_token = create_token({'identity': {'u': 'Freqtrade'}}, jwt_secret) + with client.websocket_connect(url(jwt_token)) as websocket: pass From 826eb8525470e8fa638f61247ed80e2f369493c5 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 9 Sep 2022 11:58:30 -0600 Subject: [PATCH 063/115] update confige example --- config_examples/config_full.example.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/config_examples/config_full.example.json b/config_examples/config_full.example.json index 37c604c72..d8d552814 100644 --- a/config_examples/config_full.example.json +++ b/config_examples/config_full.example.json @@ -173,7 +173,7 @@ "CORS_origins": [], "username": "freqtrader", "password": "SuperSecurePassword", - "ws_token": "a_secret_ws_token" + "ws_token": "secret_ws_t0ken." }, // The ExternalMessageConsumer config should only be enabled on an instance // that listens to outside data from another instance. This should not be enabled @@ -184,11 +184,11 @@ { "name": "default", "url": "ws://localhost:8081/api/v1/message/ws", - "ws_token": "a_secret_ws_token" + "ws_token": "secret_ws_t0ken." } ], - "reply_timeout": 30, - "ping_timeout": 5, + "poll_timeout": 300, + "ping_timeout": 10, "sleep_time": 10, "remove_entry_exit_signals": false }, From 2f6a61521f2bed67a40ed43d08ef53232b7e2ac5 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 9 Sep 2022 17:14:40 -0600 Subject: [PATCH 064/115] add more tests --- tests/data/test_dataprovider.py | 70 +++++++++++++++++++++++++++++++++ tests/rpc/test_rpc_apiserver.py | 6 +++ tests/test_misc.py | 20 ++++++++-- 3 files changed, 92 insertions(+), 4 deletions(-) diff --git a/tests/data/test_dataprovider.py b/tests/data/test_dataprovider.py index 49603feac..812688cb1 100644 --- a/tests/data/test_dataprovider.py +++ b/tests/data/test_dataprovider.py @@ -144,6 +144,76 @@ def test_available_pairs(mocker, default_conf, ohlcv_history): assert dp.available_pairs == [("XRP/BTC", timeframe), ("UNITTEST/BTC", timeframe), ] +def test_producer_pairs(mocker, default_conf, ohlcv_history): + dataprovider = DataProvider(default_conf, None) + + producer = "default" + whitelist = ["XRP/BTC", "ETH/BTC"] + assert len(dataprovider.get_producer_pairs(producer)) == 0 + + dataprovider._set_producer_pairs(whitelist, producer) + assert len(dataprovider.get_producer_pairs(producer)) == 2 + + new_whitelist = ["BTC/USDT"] + dataprovider._set_producer_pairs(new_whitelist, producer) + assert dataprovider.get_producer_pairs(producer) == new_whitelist + + assert dataprovider.get_producer_pairs("bad") == [] + + +def test_external_df(mocker, default_conf, ohlcv_history): + dataprovider = DataProvider(default_conf, None) + + pair = 'BTC/USDT' + timeframe = default_conf['timeframe'] + candle_type = CandleType.SPOT + + empty_la = datetime.fromtimestamp(0, tz=timezone.utc) + + # no data has been added, any request should return an empty dataframe + dataframe, la = dataprovider.get_external_df(pair, timeframe, candle_type) + assert dataframe.empty + assert la == empty_la + + # the data is added, should return that added dataframe + dataprovider._add_external_df(pair, ohlcv_history, timeframe=timeframe, candle_type=candle_type) + dataframe, la = dataprovider.get_external_df(pair, timeframe, candle_type) + assert len(dataframe) > 0 + assert la > empty_la + + # no data on this producer, should return empty dataframe + dataframe, la = dataprovider.get_external_df(pair, producer_name='bad') + assert dataframe.empty + assert la == empty_la + + # non existent timeframe, empty dataframe + datframe, la = dataprovider.get_external_df(pair, timeframe='1h') + assert dataframe.empty + assert la == empty_la + + +def test_emit_df(mocker, default_conf, ohlcv_history): + mocker.patch('freqtrade.rpc.rpc_manager.RPCManager.__init__', MagicMock()) + rpc_mock = mocker.patch('freqtrade.rpc.rpc_manager.RPCManager', MagicMock()) + send_mock = mocker.patch('freqtrade.rpc.rpc_manager.RPCManager.send_msg', MagicMock()) + + dataprovider = DataProvider(default_conf, exchange=None, rpc=rpc_mock) + dataprovider_no_rpc = DataProvider(default_conf, exchange=None) + + pair = "BTC/USDT" + + # No emit yet + assert send_mock.call_count == 0 + + # Rpc is added, we call emit, should call send_msg + dataprovider._emit_df(pair, ohlcv_history) + assert send_mock.call_count == 1 + + # No rpc added, emit called, should not call send_msg + dataprovider_no_rpc._emit_df(pair, ohlcv_history) + assert send_mock.call_count == 1 + + def test_refresh(mocker, default_conf, ohlcv_history): refresh_mock = MagicMock() mocker.patch("freqtrade.exchange.Exchange.refresh_latest_ohlcv", refresh_mock) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index f1aa465f0..17705e62e 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -158,6 +158,12 @@ def test_api_auth(): with pytest.raises(HTTPException): get_user_from_token(b'not_a_token', 'secret1234') + # Check returning false instead of error on bad token + assert not get_user_from_token(b'not_a_token', 'secret1234', raise_on_error=False) + + # Check returning false instead of error on bad token type + assert not get_user_from_token(token, 'secret1234', token_type='refresh', raise_on_error=False) + def test_api_ws_auth(botclient): ftbot, client = botclient diff --git a/tests/test_misc.py b/tests/test_misc.py index 107932be4..514fec54a 100644 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -7,10 +7,11 @@ from unittest.mock import MagicMock import pytest -from freqtrade.misc import (decimals_per_coin, deep_merge_dicts, file_dump_json, file_load_json, - format_ms_time, pair_to_filename, parse_db_uri_for_logging, plural, - render_template, render_template_with_fallback, round_coin_value, - safe_value_fallback, safe_value_fallback2, shorten_date) +from freqtrade.misc import (dataframe_to_json, decimals_per_coin, deep_merge_dicts, file_dump_json, + file_load_json, format_ms_time, json_to_dataframe, pair_to_filename, + parse_db_uri_for_logging, plural, render_template, + render_template_with_fallback, round_coin_value, safe_value_fallback, + safe_value_fallback2, shorten_date) def test_decimals_per_coin(): @@ -219,3 +220,14 @@ def test_deep_merge_dicts(): res2['first']['rows']['test'] = 'asdf' assert deep_merge_dicts(a, deepcopy(b), allow_null_overrides=False) == res2 + + +def test_dataframe_json(ohlcv_history): + from pandas.testing import assert_frame_equal + json = dataframe_to_json(ohlcv_history) + dataframe = json_to_dataframe(json) + + assert list(ohlcv_history.columns) == list(dataframe.columns) + assert len(ohlcv_history) == len(dataframe) + + assert_frame_equal(ohlcv_history, dataframe) From b344f78d007c20b75acefa181c2a2129f4787ecd Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 10 Sep 2022 14:19:11 +0200 Subject: [PATCH 065/115] Improve logic for token validation --- freqtrade/rpc/api_server/api_auth.py | 35 +++++++++++----------------- freqtrade/rpc/api_server/api_ws.py | 4 ++-- tests/rpc/test_rpc_apiserver.py | 6 ----- 3 files changed, 16 insertions(+), 29 deletions(-) diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index a2b722f0a..767a2d5b9 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -29,8 +29,7 @@ httpbasic = HTTPBasic(auto_error=False) oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False) -def get_user_from_token(token, secret_key: str, token_type: str = "access", - raise_on_error: bool = True) -> Union[bool, str]: +def get_user_from_token(token, secret_key: str, token_type: str = "access") -> str: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", @@ -40,28 +39,19 @@ def get_user_from_token(token, secret_key: str, token_type: str = "access", payload = jwt.decode(token, secret_key, algorithms=[ALGORITHM]) username: str = payload.get("identity", {}).get('u') if username is None: - if raise_on_error: - raise credentials_exception - else: - return False + raise credentials_exception if payload.get("type") != token_type: - if raise_on_error: - raise credentials_exception - else: - return False + raise credentials_exception except jwt.PyJWTError: - if raise_on_error: - raise credentials_exception - else: - return False + raise credentials_exception return username # This should be reimplemented to better realign with the existing tools provided # by FastAPI regarding API Tokens # https://github.com/tiangolo/fastapi/blob/master/fastapi/security/api_key.py -async def get_ws_token( +async def validate_ws_token( ws: WebSocket, ws_token: Union[str, None] = Query(..., alias="token"), api_config: Dict[str, Any] = Depends(get_api_config) @@ -72,13 +62,16 @@ async def get_ws_token( if secrets.compare_digest(secret_ws_token, ws_token): # Just return the token if it matches return ws_token - elif user := get_user_from_token(ws_token, secret_jwt_key, raise_on_error=False): - # If the token is a jwt, and it's valid return the user - return user else: - logger.info("Denying websocket request") - # If it doesn't match, close the websocket connection - await ws.close(code=status.WS_1008_POLICY_VIOLATION) + try: + user = get_user_from_token(ws_token, secret_jwt_key) + return user + # If the token is a jwt, and it's valid return the user + except HTTPException: + pass + logger.info("Denying websocket request") + # If it doesn't match, close the websocket connection + await ws.close(code=status.WS_1008_POLICY_VIOLATION) def create_token(data: dict, secret_key: str, token_type: str = "access") -> str: diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 25d29a7ce..34b780956 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -7,7 +7,7 @@ from pydantic import ValidationError from starlette.websockets import WebSocketState from freqtrade.enums import RPCMessageType, RPCRequestType -from freqtrade.rpc.api_server.api_auth import get_ws_token +from freqtrade.rpc.api_server.api_auth import validate_ws_token from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc from freqtrade.rpc.api_server.ws.channel import WebSocketChannel from freqtrade.rpc.api_server.ws_schemas import (WSAnalyzedDFMessage, WSMessageSchema, @@ -96,7 +96,7 @@ async def message_endpoint( ws: WebSocket, rpc: RPC = Depends(get_rpc), channel_manager=Depends(get_channel_manager), - token: str = Depends(get_ws_token) + token: str = Depends(validate_ws_token) ): """ Message WebSocket endpoint, facilitates sending RPC messages diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 17705e62e..f1aa465f0 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -158,12 +158,6 @@ def test_api_auth(): with pytest.raises(HTTPException): get_user_from_token(b'not_a_token', 'secret1234') - # Check returning false instead of error on bad token - assert not get_user_from_token(b'not_a_token', 'secret1234', raise_on_error=False) - - # Check returning false instead of error on bad token type - assert not get_user_from_token(token, 'secret1234', token_type='refresh', raise_on_error=False) - def test_api_ws_auth(botclient): ftbot, client = botclient From 4250174de94b4b27acd5007b009034002212d86e Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 10 Sep 2022 14:29:58 +0200 Subject: [PATCH 066/115] Fix ws exception when no token is provided --- freqtrade/rpc/api_server/api_auth.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index 767a2d5b9..93be251ab 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -53,13 +53,13 @@ def get_user_from_token(token, secret_key: str, token_type: str = "access") -> s # https://github.com/tiangolo/fastapi/blob/master/fastapi/security/api_key.py async def validate_ws_token( ws: WebSocket, - ws_token: Union[str, None] = Query(..., alias="token"), + ws_token: Union[str, None] = Query(default=None, alias="token"), api_config: Dict[str, Any] = Depends(get_api_config) ): secret_ws_token = api_config.get('ws_token', 'secret_ws_t0ken.') secret_jwt_key = api_config.get('jwt_secret_key', 'super-secret') - if secrets.compare_digest(secret_ws_token, ws_token): + if ws_token and secrets.compare_digest(secret_ws_token, ws_token): # Just return the token if it matches return ws_token else: From d8cdd92140fc908fba0de5d55314ab2181fbc5c8 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 10 Sep 2022 11:47:21 -0600 Subject: [PATCH 067/115] wrap background cleanup in finally, add tests --- freqtrade/rpc/api_server/webserver.py | 9 ++++--- tests/rpc/test_rpc_apiserver.py | 36 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 557857ecc..3fb8159e1 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -200,14 +200,17 @@ class ApiServer(RPCHandler): # Sleep, make this configurable? await asyncio.sleep(0.1) except asyncio.CancelledError: - # Disconnect channels and stop the loop on cancel - await self._ws_channel_manager.disconnect_all() - self._ws_loop.stop() + pass # For testing, shouldn't happen when stable except Exception as e: logger.exception(f"Exception happened in background task: {e}") + finally: + # Disconnect channels and stop the loop on cancel + await self._ws_channel_manager.disconnect_all() + self._ws_loop.stop() + def start_api(self): """ Start API ... should be run in thread. diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index f1aa465f0..a7774c204 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -3,6 +3,8 @@ Unit test file for rpc/api_server.py """ import json +import logging +import time from datetime import datetime, timedelta, timezone from pathlib import Path from unittest.mock import ANY, MagicMock, PropertyMock @@ -436,6 +438,7 @@ def test_api_cleanup(default_conf, mocker, caplog): apiserver.cleanup() assert apiserver._server.cleanup.call_count == 1 assert log_has("Stopping API Server", caplog) + assert log_has("Stopping API Server background tasks", caplog) ApiServer.shutdown() @@ -1709,3 +1712,36 @@ def test_api_ws_subscribe(botclient, mocker): # Call count hasn't changed as the subscribe request was invalid assert sub_mock.call_count == 1 + + +def test_api_ws_send_msg(default_conf, mocker, caplog): + try: + caplog.set_level(logging.DEBUG) + + default_conf.update({"api_server": {"enabled": True, + "listen_ip_address": "127.0.0.1", + "listen_port": 8080, + "username": "TestUser", + "password": "testPass", + }}) + mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) + apiserver = ApiServer(default_conf) + apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf))) + + # Test message_queue coro receives the message + test_message = {"type": "status", "data": "test"} + apiserver.send_msg(test_message) + time.sleep(1) # Not sure how else to wait for the coro to receive the data + assert log_has("Found message of type: status", caplog) + + # Test if exception logged when error occurs in sending + mocker.patch('freqtrade.rpc.api_server.ws.channel.ChannelManager.broadcast', + side_effect=Exception) + + apiserver.send_msg(test_message) + time.sleep(2) # Not sure how else to wait for the coro to receive the data + assert log_has_re(r"Exception happened in background task.*", caplog) + + finally: + apiserver.cleanup() + ApiServer.shutdown() From 866a5649588c77ec686ba65e581d1306d8ea3751 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 10 Sep 2022 12:51:29 -0600 Subject: [PATCH 068/115] update emc start/shutdown, initial emc tests --- freqtrade/rpc/external_message_consumer.py | 21 +++--- tests/conftest.py | 5 ++ tests/rpc/test_rpc_emc.py | 79 ++++++++++++++++++++++ 3 files changed, 97 insertions(+), 8 deletions(-) create mode 100644 tests/rpc/test_rpc_emc.py diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 1c2a27617..ae7c1f765 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -90,16 +90,16 @@ class ExternalMessageConsumer: """ Start the main internal loop in another thread to run coroutines """ + if self._thread and self._loop: + return + + logger.info("Starting ExternalMessageConsumer") + self._loop = asyncio.new_event_loop() + self._thread = Thread(target=self._loop.run_forever) + self._thread.start() - if not self._thread: - logger.info("Starting ExternalMessageConsumer") - - self._thread = Thread(target=self._loop.run_forever) - self._thread.start() - self._running = True - else: - raise RuntimeError("A loop is already running") + self._running = True self._main_task = asyncio.run_coroutine_threadsafe(self._main(), loop=self._loop) @@ -121,6 +121,11 @@ class ExternalMessageConsumer: self._thread.join() + self._thread = None + self._loop = None + self._sub_tasks = None + self._main_task = None + async def _main(self): """ The main task coroutine diff --git a/tests/conftest.py b/tests/conftest.py index fffac8e0a..6ce767918 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -58,6 +58,11 @@ def log_has(line, logs): return any(line == message for message in logs.messages) +def log_has_when(line, logs, when): + """Check if line is found in caplog's messages during a specified stage""" + return any(line == message.message for message in logs.get_records(when)) + + def log_has_re(line, logs): """Check if line matches some caplog's message.""" return any(re.match(line, message) for message in logs.messages) diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py new file mode 100644 index 000000000..6512ff2be --- /dev/null +++ b/tests/rpc/test_rpc_emc.py @@ -0,0 +1,79 @@ +""" +Unit test file for rpc/external_message_consumer.py +""" +import pytest + +from freqtrade.data.dataprovider import DataProvider +from freqtrade.rpc.external_message_consumer import ExternalMessageConsumer +from tests.conftest import log_has, log_has_when + + +@pytest.fixture(autouse=True) +def patched_emc(default_conf, mocker): + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [ + { + "name": "default", + "url": "ws://127.0.0.1:8080/api/v1/message/ws", + "ws_token": "secret_Ws_t0ken" + } + ] + } + }) + dataprovider = DataProvider(default_conf, None, None, None) + emc = ExternalMessageConsumer(default_conf, dataprovider) + + try: + yield emc + finally: + emc.shutdown() + + +def test_emc_start(patched_emc, caplog): + # Test if the message was printed + assert log_has_when("Starting ExternalMessageConsumer", caplog, "setup") + # Test if the thread and loop objects were created + assert patched_emc._thread and patched_emc._loop + + # Test we call start again nothing happens + prev_thread = patched_emc._thread + patched_emc.start() + assert prev_thread == patched_emc._thread + + +def test_emc_shutdown(patched_emc, caplog): + patched_emc.shutdown() + + assert log_has("Stopping ExternalMessageConsumer", caplog) + # Test the loop has stopped + assert patched_emc._loop is None + # Test if the thread has stopped + assert patched_emc._thread is None + + caplog.clear() + patched_emc.shutdown() + + # Test func didn't run again as it was called once already + assert not log_has("Stopping ExternalMessageConsumer", caplog) + + +def test_emc_init(patched_emc, default_conf, mocker, caplog): + # Test the settings were set correctly + assert patched_emc.initial_candle_limit <= 1500 + assert patched_emc.wait_timeout > 0 + assert patched_emc.sleep_time > 0 + + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [] + } + }) + dataprovider = DataProvider(default_conf, None, None, None) + with pytest.raises(ValueError) as exc: + ExternalMessageConsumer(default_conf, dataprovider) + + # Make sure we failed because of no producers + assert str(exc.value) == "You must specify at least 1 Producer to connect to." From a7baccdb7df6d620b1d23a846d268611cac3ed79 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 10 Sep 2022 13:44:27 -0600 Subject: [PATCH 069/115] update log messages in emc, more tests --- freqtrade/rpc/external_message_consumer.py | 10 ++-- tests/rpc/test_rpc_emc.py | 58 +++++++++++++++++++++- 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index ae7c1f765..c571ac510 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -261,19 +261,19 @@ class ExternalMessageConsumer: try: producer_message = WSMessageSchema.parse_obj(message) except ValidationError as e: - logger.error(f"Invalid message from {producer_name}: {e}") + logger.error(f"Invalid message from `{producer_name}`: {e}") return # We shouldn't get empty messages if producer_message.data is None: return - logger.info(f"Received message of type {producer_message.type} from `{producer_name}`") + logger.info(f"Received message of type `{producer_message.type}` from `{producer_name}`") message_handler = self._message_handlers.get(producer_message.type) if not message_handler: - logger.info(f"Received unhandled message: {producer_message.data}, ignoring...") + logger.info(f"Received unhandled message: `{producer_message.data}`, ignoring...") return message_handler(producer_name, producer_message) @@ -288,7 +288,7 @@ class ExternalMessageConsumer: # Add the pairlist data to the DataProvider self._dp._set_producer_pairs(message.data, producer_name=producer_name) - logger.debug(f"Consumed message from {producer_name} of type `RPCMessageType.WHITELIST`") + logger.debug(f"Consumed message from `{producer_name}` of type `RPCMessageType.WHITELIST`") def _consume_analyzed_df_message(self, producer_name: str, message: Any): try: @@ -314,4 +314,4 @@ class ExternalMessageConsumer: producer_name=producer_name) logger.debug( - f"Consumed message from {producer_name} of type RPCMessageType.ANALYZED_DF") + f"Consumed message from `{producer_name}` of type `RPCMessageType.ANALYZED_DF`") diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index 6512ff2be..f33e80018 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -1,11 +1,14 @@ """ Unit test file for rpc/external_message_consumer.py """ +import logging +from datetime import datetime, timezone + import pytest from freqtrade.data.dataprovider import DataProvider from freqtrade.rpc.external_message_consumer import ExternalMessageConsumer -from tests.conftest import log_has, log_has_when +from tests.conftest import log_has, log_has_re, log_has_when @pytest.fixture(autouse=True) @@ -77,3 +80,56 @@ def test_emc_init(patched_emc, default_conf, mocker, caplog): # Make sure we failed because of no producers assert str(exc.value) == "You must specify at least 1 Producer to connect to." + + +def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history): + test_producer = {"name": "test", "url": "ws://test", "ws_token": "test"} + caplog.set_level(logging.DEBUG) + + # Test handle whitelist message + whitelist_message = {"type": "whitelist", "data": ["BTC/USDT"]} + patched_emc.handle_producer_message(test_producer, whitelist_message) + + assert log_has("Received message of type `whitelist` from `test`", caplog) + assert log_has("Consumed message from `test` of type `RPCMessageType.WHITELIST`", caplog) + + # Test handle analyzed_df message + df_message = { + "type": "analyzed_df", + "data": { + "key": ("BTC/USDT", "5m", "spot"), + "df": ohlcv_history, + "la": datetime.now(timezone.utc) + } + } + patched_emc.handle_producer_message(test_producer, df_message) + + assert log_has("Received message of type `analyzed_df` from `test`", caplog) + assert log_has("Consumed message from `test` of type `RPCMessageType.ANALYZED_DF`", caplog) + + # Test unhandled message + unhandled_message = {"type": "status", "data": "RUNNING"} + patched_emc.handle_producer_message(test_producer, unhandled_message) + + assert log_has_re(r"Received unhandled message\: .*", caplog) + + # Test malformed message + caplog.clear() + malformed_message = {"type": "whitelist", "data": {"pair": "BTC/USDT"}} + patched_emc.handle_producer_message(test_producer, malformed_message) + + assert log_has("Received message of type `whitelist` from `test`", caplog) + assert not log_has("Consumed message from `test` of type `RPCMessageType.WHITELIST`", caplog) + + malformed_message = { + "type": "analyzed_df", + "data": { + "key": "BTC/USDT", + "df": ohlcv_history, + "la": datetime.now(timezone.utc) + } + } + patched_emc.handle_producer_message(test_producer, malformed_message) + + assert log_has("Received message of type `analyzed_df` from `test`", caplog) + assert not log_has("Consumed message from `test` of type `RPCMessageType.ANALYZED_DF`", caplog) From c5d031733b271e51edbc54a5f2880f724ace7924 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 10 Sep 2022 13:50:36 -0600 Subject: [PATCH 070/115] remove old param in test fixture --- tests/rpc/test_rpc_emc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index f33e80018..d134a9eb1 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -11,7 +11,7 @@ from freqtrade.rpc.external_message_consumer import ExternalMessageConsumer from tests.conftest import log_has, log_has_re, log_has_when -@pytest.fixture(autouse=True) +@pytest.fixture def patched_emc(default_conf, mocker): default_conf.update({ "external_message_consumer": { From 2afd5c202c1f906dcd5c04187caa5a67b0337dde Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 10 Sep 2022 14:29:15 -0600 Subject: [PATCH 071/115] update message parsing, tests --- freqtrade/rpc/external_message_consumer.py | 10 +++---- tests/rpc/test_rpc_emc.py | 34 ++++++++++++++++------ 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index c571ac510..1d917577a 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -264,10 +264,6 @@ class ExternalMessageConsumer: logger.error(f"Invalid message from `{producer_name}`: {e}") return - # We shouldn't get empty messages - if producer_message.data is None: - return - logger.info(f"Received message of type `{producer_message.type}` from `{producer_name}`") message_handler = self._message_handlers.get(producer_message.type) @@ -282,7 +278,8 @@ class ExternalMessageConsumer: try: # Validate the message message = WSWhitelistMessage.parse_obj(message) - except ValidationError: + except ValidationError as e: + logger.error(f"Invalid message from `{producer_name}`: {e}") return # Add the pairlist data to the DataProvider @@ -293,7 +290,8 @@ class ExternalMessageConsumer: def _consume_analyzed_df_message(self, producer_name: str, message: Any): try: message = WSAnalyzedDFMessage.parse_obj(message) - except ValidationError: + except ValidationError as e: + logger.error(f"Invalid message from `{producer_name}`: {e}") return key = message.data.key diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index d134a9eb1..9b14c2039 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -82,16 +82,20 @@ def test_emc_init(patched_emc, default_conf, mocker, caplog): assert str(exc.value) == "You must specify at least 1 Producer to connect to." +# Parametrize this? def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history): test_producer = {"name": "test", "url": "ws://test", "ws_token": "test"} + producer_name = test_producer['name'] + caplog.set_level(logging.DEBUG) # Test handle whitelist message whitelist_message = {"type": "whitelist", "data": ["BTC/USDT"]} patched_emc.handle_producer_message(test_producer, whitelist_message) - assert log_has("Received message of type `whitelist` from `test`", caplog) - assert log_has("Consumed message from `test` of type `RPCMessageType.WHITELIST`", caplog) + assert log_has(f"Received message of type `whitelist` from `{producer_name}`", caplog) + assert log_has( + f"Consumed message from `{producer_name}` of type `RPCMessageType.WHITELIST`", caplog) # Test handle analyzed_df message df_message = { @@ -104,8 +108,9 @@ def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history): } patched_emc.handle_producer_message(test_producer, df_message) - assert log_has("Received message of type `analyzed_df` from `test`", caplog) - assert log_has("Consumed message from `test` of type `RPCMessageType.ANALYZED_DF`", caplog) + assert log_has(f"Received message of type `analyzed_df` from `{producer_name}`", caplog) + assert log_has( + f"Consumed message from `{producer_name}` of type `RPCMessageType.ANALYZED_DF`", caplog) # Test unhandled message unhandled_message = {"type": "status", "data": "RUNNING"} @@ -113,13 +118,12 @@ def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history): assert log_has_re(r"Received unhandled message\: .*", caplog) - # Test malformed message + # Test malformed messages caplog.clear() malformed_message = {"type": "whitelist", "data": {"pair": "BTC/USDT"}} patched_emc.handle_producer_message(test_producer, malformed_message) - assert log_has("Received message of type `whitelist` from `test`", caplog) - assert not log_has("Consumed message from `test` of type `RPCMessageType.WHITELIST`", caplog) + assert log_has_re(r"Invalid message .+", caplog) malformed_message = { "type": "analyzed_df", @@ -131,5 +135,17 @@ def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history): } patched_emc.handle_producer_message(test_producer, malformed_message) - assert log_has("Received message of type `analyzed_df` from `test`", caplog) - assert not log_has("Consumed message from `test` of type `RPCMessageType.ANALYZED_DF`", caplog) + assert log_has(f"Received message of type `analyzed_df` from `{producer_name}`", caplog) + assert log_has_re(r"Invalid message .+", caplog) + + caplog.clear() + malformed_message = {"some": "stuff"} + patched_emc.handle_producer_message(test_producer, malformed_message) + + assert log_has_re(r"Invalid message .+", caplog) + + caplog.clear() + malformed_message = {"type": "whitelist", "data": None} + patched_emc.handle_producer_message(test_producer, malformed_message) + + assert log_has_re(r"Invalid message .+", caplog) From 0bc18ea33c4004939acb62997a8e253b5ba2c08e Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 10 Sep 2022 15:12:18 -0600 Subject: [PATCH 072/115] call websocket close in channel close --- freqtrade/rpc/api_server/ws/channel.py | 1 + freqtrade/rpc/api_server/ws/proxy.py | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index cffe3092d..f4a0da47b 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -71,6 +71,7 @@ class WebSocketChannel: Close the WebSocketChannel """ + await self._websocket.close() self._closed = True def is_closed(self) -> bool: diff --git a/freqtrade/rpc/api_server/ws/proxy.py b/freqtrade/rpc/api_server/ws/proxy.py index da3e04887..2e5a59f05 100644 --- a/freqtrade/rpc/api_server/ws/proxy.py +++ b/freqtrade/rpc/api_server/ws/proxy.py @@ -56,8 +56,10 @@ class WebSocketProxy: Close the websocket connection, only supported by FastAPI WebSockets """ if hasattr(self._websocket, "close"): - return await self._websocket.close(code) - pass + try: + return await self._websocket.close(code) + except RuntimeError: + pass async def accept(self): """ @@ -65,4 +67,3 @@ class WebSocketProxy: """ if hasattr(self._websocket, "accept"): return await self._websocket.accept() - pass From 9a1a4dfb5b82677db48bbab6dd1861ed3a238172 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 10 Sep 2022 16:08:05 -0600 Subject: [PATCH 073/115] more ws endpoint tests --- tests/rpc/test_rpc_apiserver.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index a7774c204..2f25f442b 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -1714,6 +1714,38 @@ def test_api_ws_subscribe(botclient, mocker): assert sub_mock.call_count == 1 +def test_api_ws_requests(botclient, mocker, caplog): + caplog.set_level(logging.DEBUG) + + ftbot, client = botclient + ws_url = f"/api/v1/message/ws?token={_TEST_WS_TOKEN}" + + # Test whitelist request + with client.websocket_connect(ws_url) as ws: + ws.send_json({"type": "whitelist", "data": None}) + response = ws.receive_json() + + assert log_has_re(r"Request of type whitelist from.+", caplog) + assert response['type'] == "whitelist" + + # Test analyzed_df request + with client.websocket_connect(ws_url) as ws: + ws.send_json({"type": "analyzed_df", "data": {}}) + response = ws.receive_json() + + assert log_has_re(r"Request of type analyzed_df from.+", caplog) + assert response['type'] == "analyzed_df" + + caplog.clear() + # Test analyzed_df request with data + with client.websocket_connect(ws_url) as ws: + ws.send_json({"type": "analyzed_df", "data": {"limit": 100}}) + response = ws.receive_json() + + assert log_has_re(r"Request of type analyzed_df from.+", caplog) + assert response['type'] == "analyzed_df" + + def test_api_ws_send_msg(default_conf, mocker, caplog): try: caplog.set_level(logging.DEBUG) From ed4ba8801f039401231bb3e6a6cc3f018de41f33 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sat, 10 Sep 2022 23:57:17 -0600 Subject: [PATCH 074/115] more emc tests --- freqtrade/rpc/external_message_consumer.py | 5 + tests/rpc/test_rpc_emc.py | 177 ++++++++++++++++++++- 2 files changed, 181 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 1d917577a..89fa90c8e 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -203,8 +203,13 @@ class ExternalMessageConsumer: continue + except websockets.exceptions.ConnectionClosedOK: + # Successfully closed, just end + return + except Exception as e: # An unforseen error has occurred, log and stop + logger.error("Unexpected error has occurred:") logger.exception(e) break diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index 9b14c2039..a074334c5 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -1,16 +1,26 @@ """ Unit test file for rpc/external_message_consumer.py """ +import asyncio +import functools +import json import logging from datetime import datetime, timezone +from unittest.mock import MagicMock import pytest +import websockets from freqtrade.data.dataprovider import DataProvider from freqtrade.rpc.external_message_consumer import ExternalMessageConsumer from tests.conftest import log_has, log_has_re, log_has_when +_TEST_WS_TOKEN = "secret_Ws_t0ken" +_TEST_WS_HOST = "localhost" +_TEST_WS_PORT = 9989 + + @pytest.fixture def patched_emc(default_conf, mocker): default_conf.update({ @@ -20,7 +30,7 @@ def patched_emc(default_conf, mocker): { "name": "default", "url": "ws://127.0.0.1:8080/api/v1/message/ws", - "ws_token": "secret_Ws_t0ken" + "ws_token": _TEST_WS_TOKEN } ] } @@ -149,3 +159,168 @@ def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history): patched_emc.handle_producer_message(test_producer, malformed_message) assert log_has_re(r"Invalid message .+", caplog) + + +async def test_emc_create_connection_success(default_conf, caplog, mocker): + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [ + { + "name": "default", + "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "ws_token": _TEST_WS_TOKEN + } + ], + "wait_timeout": 60, + "ping_timeout": 60, + "sleep_timeout": 60 + } + }) + + mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', + MagicMock()) + dp = DataProvider(default_conf, None, None, None) + emc = ExternalMessageConsumer(default_conf, dp) + + test_producer = default_conf['external_message_consumer']['producers'][0] + lock = asyncio.Lock() + + async def eat(websocket): + pass + + try: + async with websockets.serve(eat, _TEST_WS_HOST, _TEST_WS_PORT): + emc._running = True + await emc._create_connection(test_producer, lock) + emc._running = False + + assert log_has_re(r"Producer connection success.+", caplog) + finally: + emc.shutdown() + + +async def test_emc_create_connection_invalid(default_conf, caplog, mocker): + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [ + { + "name": "default", + "url": "ws://localhost:8080/api/v1/message/ws", + "ws_token": _TEST_WS_TOKEN + } + ], + "wait_timeout": 60, + "ping_timeout": 60, + "sleep_timeout": 60 + } + }) + + mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', + MagicMock()) + + lock = asyncio.Lock() + dp = DataProvider(default_conf, None, None, None) + emc = ExternalMessageConsumer(default_conf, dp) + test_producer = default_conf['external_message_consumer']['producers'][0] + + try: + # Test invalid URL + test_producer['url'] = "tcp://localhost:8080/api/v1/message/ws" + emc._running = True + await emc._create_connection(test_producer, lock) + emc._running = False + + assert log_has_re(r".+is an invalid WebSocket URL.+", caplog) + finally: + emc.shutdown() + + +async def test_emc_create_connection_error(default_conf, caplog, mocker): + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [ + { + "name": "default", + "url": "ws://localhost:8080/api/v1/message/ws", + "ws_token": _TEST_WS_TOKEN + } + ], + "wait_timeout": 60, + "ping_timeout": 60, + "sleep_timeout": 60 + } + }) + + # Test unexpected error + mocker.patch('websockets.connect', side_effect=RuntimeError) + + dp = DataProvider(default_conf, None, None, None) + emc = ExternalMessageConsumer(default_conf, dp) + + try: + await asyncio.sleep(1) + assert log_has("Unexpected error has occurred:", caplog) + finally: + emc.shutdown() + + +async def test_emc_receive_messages(default_conf, caplog, mocker): + """ + Test ExternalMessageConsumer._receive_messages + + Instantiates a patched ExternalMessageConsumer, creates a dummy websocket server, + and listens to the generated messages from the server for 1 second, then checks logs + """ + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [ + { + "name": "default", + "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "ws_token": _TEST_WS_TOKEN + } + ], + "wait_timeout": 60, + "ping_timeout": 60, + "sleep_timeout": 60 + } + }) + + mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', + MagicMock()) + + lock = asyncio.Lock() + test_producer = default_conf['external_message_consumer']['producers'][0] + + dp = DataProvider(default_conf, None, None, None) + emc = ExternalMessageConsumer(default_conf, dp) + + # Dummy generator + async def generate_messages(websocket): + try: + for i in range(3): + message = json.dumps({"type": "whitelist", "data": ["BTC/USDT"]}) + await websocket.send(message) + await asyncio.sleep(1) + except websockets.exceptions.ConnectionClosedOK: + return + + loop = asyncio.get_event_loop() + def change_running(emc): emc._running = not emc._running + + try: + # Start the dummy websocket server + async with websockets.serve(generate_messages, _TEST_WS_HOST, _TEST_WS_PORT): + # Change running to True, and call change_running in 1 second + emc._running = True + loop.call_later(1, functools.partial(change_running, emc=emc)) + # Create the connection that receives messages + await emc._create_connection(test_producer, lock) + + assert log_has_re(r"Received message of type `whitelist`.+", caplog) + finally: + emc.shutdown() From 0a8b7686d68c6eae10768eff8f1e035deb080630 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sun, 11 Sep 2022 00:50:18 -0600 Subject: [PATCH 075/115] reworked emc tests --- tests/rpc/test_rpc_emc.py | 183 ++++++++++++++++++++++++++++++++------ 1 file changed, 155 insertions(+), 28 deletions(-) diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index a074334c5..e29419102 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -3,7 +3,6 @@ Unit test file for rpc/external_message_consumer.py """ import asyncio import functools -import json import logging from datetime import datetime, timezone from unittest.mock import MagicMock @@ -220,10 +219,11 @@ async def test_emc_create_connection_invalid(default_conf, caplog, mocker): mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', MagicMock()) + test_producer = default_conf['external_message_consumer']['producers'][0] lock = asyncio.Lock() + dp = DataProvider(default_conf, None, None, None) emc = ExternalMessageConsumer(default_conf, dp) - test_producer = default_conf['external_message_consumer']['producers'][0] try: # Test invalid URL @@ -267,13 +267,7 @@ async def test_emc_create_connection_error(default_conf, caplog, mocker): emc.shutdown() -async def test_emc_receive_messages(default_conf, caplog, mocker): - """ - Test ExternalMessageConsumer._receive_messages - - Instantiates a patched ExternalMessageConsumer, creates a dummy websocket server, - and listens to the generated messages from the server for 1 second, then checks logs - """ +async def test_emc_receive_messages_valid(default_conf, caplog, mocker): default_conf.update({ "external_message_consumer": { "enabled": True, @@ -284,9 +278,9 @@ async def test_emc_receive_messages(default_conf, caplog, mocker): "ws_token": _TEST_WS_TOKEN } ], - "wait_timeout": 60, + "wait_timeout": 1, "ping_timeout": 60, - "sleep_timeout": 60 + "sleep_time": 60 } }) @@ -299,28 +293,161 @@ async def test_emc_receive_messages(default_conf, caplog, mocker): dp = DataProvider(default_conf, None, None, None) emc = ExternalMessageConsumer(default_conf, dp) - # Dummy generator - async def generate_messages(websocket): - try: - for i in range(3): - message = json.dumps({"type": "whitelist", "data": ["BTC/USDT"]}) - await websocket.send(message) - await asyncio.sleep(1) - except websockets.exceptions.ConnectionClosedOK: - return - loop = asyncio.get_event_loop() def change_running(emc): emc._running = not emc._running + class TestChannel: + async def recv(self, *args, **kwargs): + return {"type": "whitelist", "data": ["BTC/USDT"]} + + async def ping(self, *args, **kwargs): + return asyncio.Future() + try: - # Start the dummy websocket server - async with websockets.serve(generate_messages, _TEST_WS_HOST, _TEST_WS_PORT): - # Change running to True, and call change_running in 1 second - emc._running = True - loop.call_later(1, functools.partial(change_running, emc=emc)) - # Create the connection that receives messages - await emc._create_connection(test_producer, lock) + change_running(emc) + loop.call_soon(functools.partial(change_running, emc=emc)) + await emc._receive_messages(TestChannel(), test_producer, lock) assert log_has_re(r"Received message of type `whitelist`.+", caplog) finally: emc.shutdown() + + +async def test_emc_receive_messages_invalid(default_conf, caplog, mocker): + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [ + { + "name": "default", + "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "ws_token": _TEST_WS_TOKEN + } + ], + "wait_timeout": 1, + "ping_timeout": 60, + "sleep_time": 60 + } + }) + + mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', + MagicMock()) + + lock = asyncio.Lock() + test_producer = default_conf['external_message_consumer']['producers'][0] + + dp = DataProvider(default_conf, None, None, None) + emc = ExternalMessageConsumer(default_conf, dp) + + loop = asyncio.get_event_loop() + def change_running(emc): emc._running = not emc._running + + class TestChannel: + async def recv(self, *args, **kwargs): + return {"type": ["BTC/USDT"]} + + async def ping(self, *args, **kwargs): + return asyncio.Future() + + try: + change_running(emc) + loop.call_soon(functools.partial(change_running, emc=emc)) + await emc._receive_messages(TestChannel(), test_producer, lock) + + assert log_has_re(r"Invalid message from.+", caplog) + finally: + emc.shutdown() + + +async def test_emc_receive_messages_timeout(default_conf, caplog, mocker): + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [ + { + "name": "default", + "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "ws_token": _TEST_WS_TOKEN + } + ], + "wait_timeout": 1, + "ping_timeout": 1, + "sleep_time": 1 + } + }) + + mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', + MagicMock()) + + lock = asyncio.Lock() + test_producer = default_conf['external_message_consumer']['producers'][0] + + dp = DataProvider(default_conf, None, None, None) + emc = ExternalMessageConsumer(default_conf, dp) + + loop = asyncio.get_event_loop() + def change_running(emc): emc._running = not emc._running + + class TestChannel: + async def recv(self, *args, **kwargs): + await asyncio.sleep(10) + + async def ping(self, *args, **kwargs): + return asyncio.Future() + + try: + change_running(emc) + loop.call_soon(functools.partial(change_running, emc=emc)) + await emc._receive_messages(TestChannel(), test_producer, lock) + + assert log_has_re(r"Ping error.+", caplog) + finally: + emc.shutdown() + + +async def test_emc_receive_messages_handle_error(default_conf, caplog, mocker): + default_conf.update({ + "external_message_consumer": { + "enabled": True, + "producers": [ + { + "name": "default", + "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "ws_token": _TEST_WS_TOKEN + } + ], + "wait_timeout": 1, + "ping_timeout": 1, + "sleep_time": 1 + } + }) + + mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', + MagicMock()) + + lock = asyncio.Lock() + test_producer = default_conf['external_message_consumer']['producers'][0] + + dp = DataProvider(default_conf, None, None, None) + emc = ExternalMessageConsumer(default_conf, dp) + + emc.handle_producer_message = MagicMock(side_effect=Exception) + + loop = asyncio.get_event_loop() + def change_running(emc): emc._running = not emc._running + + class TestChannel: + async def recv(self, *args, **kwargs): + return {"type": "whitelist", "data": ["BTC/USDT"]} + + async def ping(self, *args, **kwargs): + return asyncio.Future() + + try: + change_running(emc) + loop.call_soon(functools.partial(change_running, emc=emc)) + await emc._receive_messages(TestChannel(), test_producer, lock) + + assert log_has_re(r"Error handling producer message.+", caplog) + finally: + emc.shutdown() From 5483cf21f694a4bc0ec90bb533d587d5428c7da1 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Sun, 11 Sep 2022 11:42:13 -0600 Subject: [PATCH 076/115] remove default secret_ws_token, set timeout min to 0 --- freqtrade/constants.py | 7 ++++--- freqtrade/rpc/api_server/api_auth.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index e77940b3c..2cc2fd115 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -502,12 +502,13 @@ CONF_SCHEMA = { 'required': ['name', 'url', 'ws_token'] } }, - 'wait_timeout': {'type': 'integer'}, - 'sleep_time': {'type': 'integer'}, - 'ping_timeout': {'type': 'integer'}, + 'wait_timeout': {'type': 'integer', 'minimum': 0}, + 'sleep_time': {'type': 'integer', 'minimum': 0}, + 'ping_timeout': {'type': 'integer', 'minimum': 0}, 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False}, 'initial_candle_limit': { 'type': 'integer', + 'minimum': 0, 'maximum': 1500, 'default': 1500 } diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index 93be251ab..1ab158ea7 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -56,7 +56,7 @@ async def validate_ws_token( ws_token: Union[str, None] = Query(default=None, alias="token"), api_config: Dict[str, Any] = Depends(get_api_config) ): - secret_ws_token = api_config.get('ws_token', 'secret_ws_t0ken.') + secret_ws_token = api_config.get('ws_token', None) secret_jwt_key = api_config.get('jwt_secret_key', 'super-secret') if ws_token and secrets.compare_digest(secret_ws_token, ws_token): From 715a71465d36a1b613b2884855b006e892b94ff9 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 12 Sep 2022 07:28:31 +0200 Subject: [PATCH 077/115] Fix auth bug when no token is set --- freqtrade/data/dataprovider.py | 5 ++--- freqtrade/rpc/api_server/api_auth.py | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 8ca638046..fd7997521 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -88,11 +88,10 @@ class DataProvider: def _set_producer_pairs(self, pairlist: List[str], producer_name: str = "default"): """ Set the pairs received to later be used. - This only supports 1 Producer right now. :param pairlist: List of pairs """ - self.__producer_pairs[producer_name] = pairlist.copy() + self.__producer_pairs[producer_name] = pairlist def get_producer_pairs(self, producer_name: str = "default") -> List[str]: """ @@ -100,7 +99,7 @@ class DataProvider: :returns: List of pairs """ - return self.__producer_pairs.get(producer_name, []) + return self.__producer_pairs.get(producer_name, []).copy() def _emit_df( self, diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index 1ab158ea7..e91e5941b 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -59,7 +59,7 @@ async def validate_ws_token( secret_ws_token = api_config.get('ws_token', None) secret_jwt_key = api_config.get('jwt_secret_key', 'super-secret') - if ws_token and secrets.compare_digest(secret_ws_token, ws_token): + if ws_token and secret_ws_token and secrets.compare_digest(secret_ws_token, ws_token): # Just return the token if it matches return ws_token else: @@ -69,7 +69,7 @@ async def validate_ws_token( # If the token is a jwt, and it's valid return the user except HTTPException: pass - logger.info("Denying websocket request") + logger.debug("Denying websocket request.") # If it doesn't match, close the websocket connection await ws.close(code=status.WS_1008_POLICY_VIOLATION) From d6205e6cfb653947be23afddaf2679ff236a2e30 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 07:36:11 -0600 Subject: [PATCH 078/115] test logging lines --- freqtrade/rpc/external_message_consumer.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 89fa90c8e..59064c90b 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -305,6 +305,9 @@ class ExternalMessageConsumer: pair, timeframe, candle_type = key + logger.debug(message.data.key) + logger.debug(message.data) + # If set, remove the Entry and Exit signals from the Producer if self._emc_config.get('remove_entry_exit_signals', False): df = remove_entry_exit_signals(df) From 457075b82386006e5d543f207f8cd00151a97e49 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 07:47:30 -0600 Subject: [PATCH 079/115] one more line --- freqtrade/data/dataprovider.py | 1 + 1 file changed, 1 insertion(+) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 94e79c8be..f8ea0073b 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -113,6 +113,7 @@ class DataProvider: :param data: Tuple containing the DataFrame and the datetime it was cached """ if self.__rpc: + logger.debug(f"Sending df {dataframe}") self.__rpc.send_msg( { 'type': RPCMessageType.ANALYZED_DF, From 10852555e593fc84b4d56b58616201154eb1ea24 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 09:53:47 -0600 Subject: [PATCH 080/115] change verbosity of testing log --- freqtrade/data/dataprovider.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index f8ea0073b..19d6d6ae1 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -113,7 +113,7 @@ class DataProvider: :param data: Tuple containing the DataFrame and the datetime it was cached """ if self.__rpc: - logger.debug(f"Sending df {dataframe}") + logger.debug(f"Sending df {dataframe.iloc[-1]}") self.__rpc.send_msg( { 'type': RPCMessageType.ANALYZED_DF, From a477b3c244680e0e2e72d12f5a12a1ed557640f0 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 10:45:59 -0600 Subject: [PATCH 081/115] remove log line, fix tests to not connect to actual ip --- freqtrade/data/dataprovider.py | 1 - tests/rpc/test_rpc_emc.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 19d6d6ae1..94e79c8be 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -113,7 +113,6 @@ class DataProvider: :param data: Tuple containing the DataFrame and the datetime it was cached """ if self.__rpc: - logger.debug(f"Sending df {dataframe.iloc[-1]}") self.__rpc.send_msg( { 'type': RPCMessageType.ANALYZED_DF, diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index e29419102..b3f6fdc4d 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -28,7 +28,7 @@ def patched_emc(default_conf, mocker): "producers": [ { "name": "default", - "url": "ws://127.0.0.1:8080/api/v1/message/ws", + "url": "ws://something:port/api/v1/message/ws", "ws_token": _TEST_WS_TOKEN } ] From 0052e5891788ffbfdaf20dd0374599924369644e Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 12 Sep 2022 19:50:22 +0200 Subject: [PATCH 082/115] emc: Fix potential startup timing issue --- freqtrade/rpc/external_message_consumer.py | 6 +++--- tests/rpc/test_rpc_emc.py | 9 ++++----- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 59064c90b..122863987 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -15,6 +15,7 @@ from pydantic import ValidationError from freqtrade.data.dataprovider import DataProvider from freqtrade.enums import RPCMessageType +from freqtrade.exceptions import OperationalException from freqtrade.misc import remove_entry_exit_signals from freqtrade.rpc.api_server.ws.channel import WebSocketChannel from freqtrade.rpc.api_server.ws_schemas import (WSAnalyzedDFMessage, WSAnalyzedDFRequest, @@ -57,7 +58,7 @@ class ExternalMessageConsumer: self.producers = self._emc_config.get('producers', []) if self.enabled and len(self.producers) < 1: - raise ValueError("You must specify at least 1 Producer to connect to.") + raise OperationalException("You must specify at least 1 Producer to connect to.") self.wait_timeout = self._emc_config.get('wait_timeout', 300) # in seconds self.ping_timeout = self._emc_config.get('ping_timeout', 10) # in seconds @@ -97,9 +98,8 @@ class ExternalMessageConsumer: self._loop = asyncio.new_event_loop() self._thread = Thread(target=self._loop.run_forever) - self._thread.start() - self._running = True + self._thread.start() self._main_task = asyncio.run_coroutine_threadsafe(self._main(), loop=self._loop) diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index b3f6fdc4d..94635810c 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -11,6 +11,7 @@ import pytest import websockets from freqtrade.data.dataprovider import DataProvider +from freqtrade.exceptions import OperationalException from freqtrade.rpc.external_message_consumer import ExternalMessageConsumer from tests.conftest import log_has, log_has_re, log_has_when @@ -71,7 +72,7 @@ def test_emc_shutdown(patched_emc, caplog): assert not log_has("Stopping ExternalMessageConsumer", caplog) -def test_emc_init(patched_emc, default_conf, mocker, caplog): +def test_emc_init(patched_emc, default_conf): # Test the settings were set correctly assert patched_emc.initial_candle_limit <= 1500 assert patched_emc.wait_timeout > 0 @@ -84,12 +85,10 @@ def test_emc_init(patched_emc, default_conf, mocker, caplog): } }) dataprovider = DataProvider(default_conf, None, None, None) - with pytest.raises(ValueError) as exc: + with pytest.raises(OperationalException, + match="You must specify at least 1 Producer to connect to."): ExternalMessageConsumer(default_conf, dataprovider) - # Make sure we failed because of no producers - assert str(exc.value) == "You must specify at least 1 Producer to connect to." - # Parametrize this? def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history): From 867d59b930b27e774fd391d3f372272a5ddcd7d3 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 12 Sep 2022 20:00:01 +0200 Subject: [PATCH 083/115] Improve type specifitivity --- freqtrade/rpc/external_message_consumer.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 122863987..bd921cf8e 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -8,7 +8,7 @@ import asyncio import logging import socket from threading import Thread -from typing import TYPE_CHECKING, Any, Dict, List +from typing import TYPE_CHECKING, Any, Callable, Dict, List import websockets from pydantic import ValidationError @@ -80,7 +80,7 @@ class ExternalMessageConsumer: ] # Specify which function to use for which RPCMessageType - self._message_handlers = { + self._message_handlers: Dict[str, Callable[[str, WSMessageSchema], None]] = { RPCMessageType.WHITELIST: self._consume_whitelist_message, RPCMessageType.ANALYZED_DF: self._consume_analyzed_df_message, } @@ -279,7 +279,7 @@ class ExternalMessageConsumer: message_handler(producer_name, producer_message) - def _consume_whitelist_message(self, producer_name: str, message: Any): + def _consume_whitelist_message(self, producer_name: str, message: WSMessageSchema): try: # Validate the message message = WSWhitelistMessage.parse_obj(message) @@ -292,7 +292,7 @@ class ExternalMessageConsumer: logger.debug(f"Consumed message from `{producer_name}` of type `RPCMessageType.WHITELIST`") - def _consume_analyzed_df_message(self, producer_name: str, message: Any): + def _consume_analyzed_df_message(self, producer_name: str, message: WSMessageSchema): try: message = WSAnalyzedDFMessage.parse_obj(message) except ValidationError as e: From b6434040de76f43d66b710da60f1be4f88b80adf Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 12 Sep 2022 20:24:28 +0200 Subject: [PATCH 084/115] Remove plain json serializer implementation --- freqtrade/rpc/api_server/ws/serializer.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py index d1ddd84f0..22d177f85 100644 --- a/freqtrade/rpc/api_server/ws/serializer.py +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -1,4 +1,3 @@ -import json import logging from abc import ABC, abstractmethod @@ -38,14 +37,6 @@ class WebSocketSerializer(ABC): await self._websocket.close(code) -class JSONWebSocketSerializer(WebSocketSerializer): - def _serialize(self, data): - return json.dumps(data, default=_json_default) - - def _deserialize(self, data): - return json.loads(data, object_hook=_json_object_hook) - - class HybridJSONWebSocketSerializer(WebSocketSerializer): def _serialize(self, data) -> str: return str(orjson.dumps(data, default=_json_default), "utf-8") From c19a5fbe06e35839255ad0b961d20c39299b7e1d Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 13:57:29 -0600 Subject: [PATCH 085/115] copy data being transferred, remove debug messages in emc --- freqtrade/data/dataprovider.py | 3 ++- freqtrade/rpc/external_message_consumer.py | 19 ++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 94e79c8be..e3bee7118 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -184,7 +184,8 @@ class DataProvider: return (DataFrame(), datetime.fromtimestamp(0, tz=timezone.utc)) # We have it, return this data - return self.__producer_pairs_df[producer_name][pair_key] + df, la = self.__producer_pairs_df[producer_name][pair_key] + return (df.copy(), la) def add_pairlisthandler(self, pairlists) -> None: """ diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index bd921cf8e..89edc8417 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -269,6 +269,10 @@ class ExternalMessageConsumer: logger.error(f"Invalid message from `{producer_name}`: {e}") return + if not producer_message.data: + logger.error(f"Empty message received from `{producer_name}`") + return + logger.info(f"Received message of type `{producer_message.type}` from `{producer_name}`") message_handler = self._message_handlers.get(producer_message.type) @@ -282,32 +286,29 @@ class ExternalMessageConsumer: def _consume_whitelist_message(self, producer_name: str, message: WSMessageSchema): try: # Validate the message - message = WSWhitelistMessage.parse_obj(message) + whitelist_message = WSWhitelistMessage.parse_obj(message) except ValidationError as e: logger.error(f"Invalid message from `{producer_name}`: {e}") return # Add the pairlist data to the DataProvider - self._dp._set_producer_pairs(message.data, producer_name=producer_name) + self._dp._set_producer_pairs(whitelist_message.data.copy(), producer_name=producer_name) logger.debug(f"Consumed message from `{producer_name}` of type `RPCMessageType.WHITELIST`") def _consume_analyzed_df_message(self, producer_name: str, message: WSMessageSchema): try: - message = WSAnalyzedDFMessage.parse_obj(message) + df_message = WSAnalyzedDFMessage.parse_obj(message) except ValidationError as e: logger.error(f"Invalid message from `{producer_name}`: {e}") return - key = message.data.key - df = message.data.df - la = message.data.la + key = df_message.data.key + df = df_message.data.df + la = df_message.data.la pair, timeframe, candle_type = key - logger.debug(message.data.key) - logger.debug(message.data) - # If set, remove the Entry and Exit signals from the Producer if self._emc_config.get('remove_entry_exit_signals', False): df = remove_entry_exit_signals(df) From 0697041f146fa1f4d3aaa74a0af6419d0a57143f Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 14:09:12 -0600 Subject: [PATCH 086/115] remove copy statement where not needed --- freqtrade/rpc/external_message_consumer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 89edc8417..a9fdd62ca 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -292,7 +292,7 @@ class ExternalMessageConsumer: return # Add the pairlist data to the DataProvider - self._dp._set_producer_pairs(whitelist_message.data.copy(), producer_name=producer_name) + self._dp._set_producer_pairs(whitelist_message.data, producer_name=producer_name) logger.debug(f"Consumed message from `{producer_name}` of type `RPCMessageType.WHITELIST`") From 12a3e90f7860920af11eb08047023ee782c21786 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 14:12:39 -0600 Subject: [PATCH 087/115] fix tests --- tests/rpc/test_rpc_emc.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index 94635810c..1968c5d39 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -29,7 +29,7 @@ def patched_emc(default_conf, mocker): "producers": [ { "name": "default", - "url": "ws://something:port/api/v1/message/ws", + "url": "ws://null:9891/api/v1/message/ws", "ws_token": _TEST_WS_TOKEN } ] @@ -156,7 +156,7 @@ def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history): malformed_message = {"type": "whitelist", "data": None} patched_emc.handle_producer_message(test_producer, malformed_message) - assert log_has_re(r"Invalid message .+", caplog) + assert log_has_re(r"Empty message .+", caplog) async def test_emc_create_connection_success(default_conf, caplog, mocker): From bf2e5dee759bd393dcff91570a9364c944d35f5e Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 14:21:39 -0600 Subject: [PATCH 088/115] add running false on shutdown, fix dp typing --- freqtrade/data/dataprovider.py | 14 +++++--------- freqtrade/rpc/external_message_consumer.py | 1 + 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index e3bee7118..dae8ec162 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -128,9 +128,9 @@ class DataProvider: self, pair: str, dataframe: DataFrame, - last_analyzed: Optional[datetime] = None, - timeframe: Optional[str] = None, - candle_type: Optional[CandleType] = None, + last_analyzed: datetime, + timeframe: str, + candle_type: CandleType, producer_name: str = "default" ) -> None: """ @@ -140,10 +140,7 @@ class DataProvider: :param timeframe: Timeframe to get data for :param candle_type: Any of the enum CandleType (must match trading mode!) """ - _timeframe = self._default_timeframe if not timeframe else timeframe - _candle_type = self._default_candle_type if not candle_type else candle_type - - pair_key = (pair, _timeframe, _candle_type) + pair_key = (pair, timeframe, candle_type) if producer_name not in self.__producer_pairs_df: self.__producer_pairs_df[producer_name] = {} @@ -161,8 +158,7 @@ class DataProvider: producer_name: str = "default" ) -> Tuple[DataFrame, datetime]: """ - Get the pair data from the external sources. Will wait if the policy is - set to, and data is not available. + Get the pair data from the external sources. :param pair: pair to get the data for :param timeframe: Timeframe to get data for diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index a9fdd62ca..e167ce24d 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -109,6 +109,7 @@ class ExternalMessageConsumer: """ if self._thread and self._loop: logger.info("Stopping ExternalMessageConsumer") + self._running = False if self._sub_tasks: # Cancel sub tasks From 75ce9067dcfdc32ad39cdddf7c7c89ee25dc1348 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Mon, 12 Sep 2022 16:39:16 -0600 Subject: [PATCH 089/115] fix dp test --- tests/data/test_dataprovider.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/data/test_dataprovider.py b/tests/data/test_dataprovider.py index 812688cb1..9915b6316 100644 --- a/tests/data/test_dataprovider.py +++ b/tests/data/test_dataprovider.py @@ -169,6 +169,7 @@ def test_external_df(mocker, default_conf, ohlcv_history): candle_type = CandleType.SPOT empty_la = datetime.fromtimestamp(0, tz=timezone.utc) + now = datetime.now(timezone.utc) # no data has been added, any request should return an empty dataframe dataframe, la = dataprovider.get_external_df(pair, timeframe, candle_type) @@ -176,7 +177,7 @@ def test_external_df(mocker, default_conf, ohlcv_history): assert la == empty_la # the data is added, should return that added dataframe - dataprovider._add_external_df(pair, ohlcv_history, timeframe=timeframe, candle_type=candle_type) + dataprovider._add_external_df(pair, ohlcv_history, now, timeframe, candle_type) dataframe, la = dataprovider.get_external_df(pair, timeframe, candle_type) assert len(dataframe) > 0 assert la > empty_la From 6d0dfd4dc8f122716784759926e21bc1f0c6c00b Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 13 Sep 2022 12:27:41 -0600 Subject: [PATCH 090/115] continue trying connect on ping error --- freqtrade/rpc/external_message_consumer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index e167ce24d..ef2417225 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -252,11 +252,11 @@ class ExternalMessageConsumer: continue except Exception: - logger.info( + logger.error( f"Ping error {channel} - retrying in {self.sleep_time}s") await asyncio.sleep(self.sleep_time) - break + continue def handle_producer_message(self, producer: Dict[str, Any], message: Dict[str, Any]): """ From 07aa206f71995ffc92f744d40ae40973d1c54813 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 13 Sep 2022 12:36:40 -0600 Subject: [PATCH 091/115] real fix for reconnecting --- freqtrade/rpc/external_message_consumer.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index ef2417225..f8e5315f9 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -205,14 +205,14 @@ class ExternalMessageConsumer: continue except websockets.exceptions.ConnectionClosedOK: - # Successfully closed, just end - return + # Successfully closed, just keep trying to connect again indefinitely + continue except Exception as e: # An unforseen error has occurred, log and stop logger.error("Unexpected error has occurred:") logger.exception(e) - break + continue async def _receive_messages( self, @@ -256,7 +256,7 @@ class ExternalMessageConsumer: f"Ping error {channel} - retrying in {self.sleep_time}s") await asyncio.sleep(self.sleep_time) - continue + break def handle_producer_message(self, producer: Dict[str, Any], message: Dict[str, Any]): """ From aeaca78940131ef4d3165d3d53c2082478d3d192 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 13 Sep 2022 12:39:12 -0600 Subject: [PATCH 092/115] change port in send_msg test --- tests/rpc/test_rpc_apiserver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 2f25f442b..f22499086 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -1752,7 +1752,7 @@ def test_api_ws_send_msg(default_conf, mocker, caplog): default_conf.update({"api_server": {"enabled": True, "listen_ip_address": "127.0.0.1", - "listen_port": 8080, + "listen_port": 9913, "username": "TestUser", "password": "testPass", }}) From 79c70bd52dc402a1e75252532b2a744e1ff0c891 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 13 Sep 2022 20:12:02 +0200 Subject: [PATCH 093/115] use WebSocketState from fastapi available since 0.82.0 --- freqtrade/rpc/api_server/api_ws.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 34b780956..174a0a85e 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -1,10 +1,9 @@ import logging from typing import Any, Dict -from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect +from fastapi import APIRouter, Depends, WebSocketDisconnect +from fastapi.websockets import WebSocket, WebSocketState from pydantic import ValidationError -# fastapi does not make this available through it, so import directly from starlette -from starlette.websockets import WebSocketState from freqtrade.enums import RPCMessageType, RPCRequestType from freqtrade.rpc.api_server.api_auth import validate_ws_token From d2abc9417f53f9a330e11dde257d7e014d120f96 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 13 Sep 2022 20:42:24 +0200 Subject: [PATCH 094/115] Simplify ws imports --- freqtrade/rpc/api_server/api_ws.py | 2 +- freqtrade/rpc/api_server/webserver.py | 2 +- freqtrade/rpc/api_server/ws/__init__.py | 6 ++++++ freqtrade/rpc/external_message_consumer.py | 5 ++--- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index 174a0a85e..c4a3e9d4a 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -8,7 +8,7 @@ from pydantic import ValidationError from freqtrade.enums import RPCMessageType, RPCRequestType from freqtrade.rpc.api_server.api_auth import validate_ws_token from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc -from freqtrade.rpc.api_server.ws.channel import WebSocketChannel +from freqtrade.rpc.api_server.ws import WebSocketChannel from freqtrade.rpc.api_server.ws_schemas import (WSAnalyzedDFMessage, WSMessageSchema, WSRequestSchema, WSWhitelistMessage) from freqtrade.rpc.rpc import RPC diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 3fb8159e1..7a59a7a4c 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -14,7 +14,7 @@ from starlette.responses import JSONResponse from freqtrade.exceptions import OperationalException from freqtrade.rpc.api_server.uvicorn_threaded import UvicornServer -from freqtrade.rpc.api_server.ws.channel import ChannelManager +from freqtrade.rpc.api_server.ws import ChannelManager from freqtrade.rpc.rpc import RPC, RPCException, RPCHandler diff --git a/freqtrade/rpc/api_server/ws/__init__.py b/freqtrade/rpc/api_server/ws/__init__.py index e69de29bb..c00d29e22 100644 --- a/freqtrade/rpc/api_server/ws/__init__.py +++ b/freqtrade/rpc/api_server/ws/__init__.py @@ -0,0 +1,6 @@ +# flake8: noqa: F401 +# isort: off +from freqtrade.rpc.api_server.ws.types import WebSocketType +from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy +from freqtrade.rpc.api_server.ws.serializer import HybridJSONWebSocketSerializer, MsgPackWebSocketSerializer +from freqtrade.rpc.api_server.ws.channel import ChannelManager, WebSocketChannel diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index f8e5315f9..2ff261eee 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -17,7 +17,7 @@ from freqtrade.data.dataprovider import DataProvider from freqtrade.enums import RPCMessageType from freqtrade.exceptions import OperationalException from freqtrade.misc import remove_entry_exit_signals -from freqtrade.rpc.api_server.ws.channel import WebSocketChannel +from freqtrade.rpc.api_server.ws import WebSocketChannel from freqtrade.rpc.api_server.ws_schemas import (WSAnalyzedDFMessage, WSAnalyzedDFRequest, WSMessageSchema, WSRequestSchema, WSSubscribeRequest, WSWhitelistMessage, @@ -252,8 +252,7 @@ class ExternalMessageConsumer: continue except Exception: - logger.error( - f"Ping error {channel} - retrying in {self.sleep_time}s") + logger.warning(f"Ping error {channel} - retrying in {self.sleep_time}s") await asyncio.sleep(self.sleep_time) break From 877d24bcdd1adb0d3378dbc24a7930d24638cba8 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 13 Sep 2022 20:42:32 +0200 Subject: [PATCH 095/115] Fix external dependency of test --- tests/rpc/test_rpc_apiserver.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index f22499086..e007e0a9e 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -1698,8 +1698,7 @@ def test_api_ws_subscribe(botclient, mocker): ftbot, client = botclient ws_url = f"/api/v1/message/ws?token={_TEST_WS_TOKEN}" - sub_mock = mocker.patch( - 'freqtrade.rpc.api_server.ws.channel.WebSocketChannel.set_subscriptions', MagicMock()) + sub_mock = mocker.patch('freqtrade.rpc.api_server.ws.WebSocketChannel.set_subscriptions') with client.websocket_connect(ws_url) as ws: ws.send_json({'type': 'subscribe', 'data': ['whitelist']}) @@ -1752,18 +1751,24 @@ def test_api_ws_send_msg(default_conf, mocker, caplog): default_conf.update({"api_server": {"enabled": True, "listen_ip_address": "127.0.0.1", - "listen_port": 9913, - "username": "TestUser", - "password": "testPass", + "listen_port": 8080, + "CORS_origins": ['http://example.com'], + "username": _TEST_USER, + "password": _TEST_PASS, + "ws_token": _TEST_WS_TOKEN }}) - mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) + mocker.patch('freqtrade.rpc.telegram.Updater') + mocker.patch('freqtrade.rpc.api_server.ApiServer.start_api') apiserver = ApiServer(default_conf) apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf))) + apiserver.start_message_queue() + # Give the queue thread time to start + time.sleep(0.2) # Test message_queue coro receives the message test_message = {"type": "status", "data": "test"} apiserver.send_msg(test_message) - time.sleep(1) # Not sure how else to wait for the coro to receive the data + time.sleep(0.1) # Not sure how else to wait for the coro to receive the data assert log_has("Found message of type: status", caplog) # Test if exception logged when error occurs in sending @@ -1771,7 +1776,7 @@ def test_api_ws_send_msg(default_conf, mocker, caplog): side_effect=Exception) apiserver.send_msg(test_message) - time.sleep(2) # Not sure how else to wait for the coro to receive the data + time.sleep(0.1) # Not sure how else to wait for the coro to receive the data assert log_has_re(r"Exception happened in background task.*", caplog) finally: From 46a425d1b640d8b15c2115e3478cd635e0dfdbd8 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 13 Sep 2022 13:36:21 -0600 Subject: [PATCH 096/115] fix OOM on emc test --- tests/rpc/test_rpc_emc.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index 1968c5d39..7bb727810 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -184,14 +184,14 @@ async def test_emc_create_connection_success(default_conf, caplog, mocker): test_producer = default_conf['external_message_consumer']['producers'][0] lock = asyncio.Lock() + emc._running = True + async def eat(websocket): - pass + emc._running = False try: async with websockets.serve(eat, _TEST_WS_HOST, _TEST_WS_PORT): - emc._running = True await emc._create_connection(test_producer, lock) - emc._running = False assert log_has_re(r"Producer connection success.+", caplog) finally: From 7a98775f012d9467b951427d56daead30e630e37 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 13 Sep 2022 22:07:59 +0200 Subject: [PATCH 097/115] Version bump apiVersion --- freqtrade/rpc/api_server/api_v1.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server/api_v1.py b/freqtrade/rpc/api_server/api_v1.py index bf21715b7..53f5c16d7 100644 --- a/freqtrade/rpc/api_server/api_v1.py +++ b/freqtrade/rpc/api_server/api_v1.py @@ -38,7 +38,8 @@ logger = logging.getLogger(__name__) # 2.15: Add backtest history endpoints # 2.16: Additional daily metrics # 2.17: Forceentry - leverage, partial force_exit -API_VERSION = 2.17 +# 2.20: Add websocket endpoints +API_VERSION = 2.20 # Public API, requires no auth. router_public = APIRouter() From d75d5a7dadaf60f3e0fc619af73d2964527a8d4a Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 13 Sep 2022 16:06:25 -0600 Subject: [PATCH 098/115] debug ping error message --- freqtrade/rpc/external_message_consumer.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 2ff261eee..fd6ccfacd 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -251,8 +251,9 @@ class ExternalMessageConsumer: logger.debug(f"Connection to {channel} still alive...") continue - except Exception: + except Exception as e: logger.warning(f"Ping error {channel} - retrying in {self.sleep_time}s") + logger.debug(e, exc_info=e) await asyncio.sleep(self.sleep_time) break From 06350a13cbad4de1780058dde2b145bca3146171 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 13 Sep 2022 16:39:53 -0600 Subject: [PATCH 099/115] support specifying message size in emc config --- freqtrade/constants.py | 6 ++++++ freqtrade/rpc/external_message_consumer.py | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 2cc2fd115..470ffb2a3 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -511,6 +511,12 @@ CONF_SCHEMA = { 'minimum': 0, 'maximum': 1500, 'default': 1500 + }, + 'max_message_size': { + 'type': 'integer', + 'minimum': 1048576, # 1mb + 'maxmium': 8388608, # 8.3mb, + 'default': 1048576, # 1mb } }, 'required': ['producers'] diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index fd6ccfacd..7dd6c09b0 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -67,6 +67,9 @@ class ExternalMessageConsumer: # The amount of candles per dataframe on the initial request self.initial_candle_limit = self._emc_config.get('initial_candle_limit', 1500) + # Message size limit, default 1mb + self.message_size_limit = self._emc_config.get('message_size_limit', 2**20) + # Setting these explicitly as they probably shouldn't be changed by a user # Unless we somehow integrate this with the strategy to allow creating # callbacks for the messages @@ -175,7 +178,7 @@ class ExternalMessageConsumer: ws_url = f"{url}?token={token}" # This will raise InvalidURI if the url is bad - async with websockets.connect(ws_url) as ws: + async with websockets.connect(ws_url, max_size=self.message_size_limit) as ws: channel = WebSocketChannel(ws, channel_id=name) logger.info(f"Producer connection success - {channel}") From aed19ff6cee279f1446338dab54b2bb348145902 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Tue, 13 Sep 2022 19:17:12 -0600 Subject: [PATCH 100/115] fix The future belongs to a different loop error --- freqtrade/rpc/api_server/ws/channel.py | 1 - 1 file changed, 1 deletion(-) diff --git a/freqtrade/rpc/api_server/ws/channel.py b/freqtrade/rpc/api_server/ws/channel.py index f4a0da47b..cffe3092d 100644 --- a/freqtrade/rpc/api_server/ws/channel.py +++ b/freqtrade/rpc/api_server/ws/channel.py @@ -71,7 +71,6 @@ class WebSocketChannel: Close the WebSocketChannel """ - await self._websocket.close() self._closed = True def is_closed(self) -> bool: From 6126925dbe8c125facc3e0898d3091e798a81f97 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 14 Sep 2022 16:42:14 -0600 Subject: [PATCH 101/115] message size limit in mb, default to 8mb --- freqtrade/constants.py | 8 ++++---- freqtrade/rpc/external_message_consumer.py | 8 ++++++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 470ffb2a3..371cb9578 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -512,11 +512,11 @@ CONF_SCHEMA = { 'maximum': 1500, 'default': 1500 }, - 'max_message_size': { + 'max_message_size': { # In megabytes 'type': 'integer', - 'minimum': 1048576, # 1mb - 'maxmium': 8388608, # 8.3mb, - 'default': 1048576, # 1mb + 'minimum': 1, + 'maxmium': 20, + 'default': 8, } }, 'required': ['producers'] diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 7dd6c09b0..95031488d 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -67,8 +67,9 @@ class ExternalMessageConsumer: # The amount of candles per dataframe on the initial request self.initial_candle_limit = self._emc_config.get('initial_candle_limit', 1500) - # Message size limit, default 1mb - self.message_size_limit = self._emc_config.get('message_size_limit', 2**20) + # Message size limit, in megabytes. Default 8mb, Use bitwise operator << 20 to convert + # as the websockets client expects bytes. + self.message_size_limit = (self._emc_config.get('message_size_limit', 8) << 20) # Setting these explicitly as they probably shouldn't be changed by a user # Unless we somehow integrate this with the strategy to allow creating @@ -177,6 +178,9 @@ class ExternalMessageConsumer: name = producer["name"] ws_url = f"{url}?token={token}" + logger.info( + f"Connecting to {name} @ {url}, max message size: {self.message_size_limit}") + # This will raise InvalidURI if the url is bad async with websockets.connect(ws_url, max_size=self.message_size_limit) as ws: channel = WebSocketChannel(ws, channel_id=name) From 8e75852ff309a69bb47e5fcdf576c3132ef1fd17 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 15 Sep 2022 11:12:05 -0600 Subject: [PATCH 102/115] fix constants, update config example, add emc config validation --- config_examples/config_full.example.json | 11 ++++----- freqtrade/constants.py | 11 +++++---- freqtrade/rpc/api_server/api_ws.py | 2 -- freqtrade/rpc/external_message_consumer.py | 27 ++++++++++++++-------- 4 files changed, 29 insertions(+), 22 deletions(-) diff --git a/config_examples/config_full.example.json b/config_examples/config_full.example.json index d8d552814..5a5096f81 100644 --- a/config_examples/config_full.example.json +++ b/config_examples/config_full.example.json @@ -175,22 +175,21 @@ "password": "SuperSecurePassword", "ws_token": "secret_ws_t0ken." }, - // The ExternalMessageConsumer config should only be enabled on an instance - // that listens to outside data from another instance. This should not be enabled - // in your producer of data. "external_message_consumer": { "enabled": false, "producers": [ { "name": "default", - "url": "ws://localhost:8081/api/v1/message/ws", + "host": "127.0.0.2", + "port": 8080, "ws_token": "secret_ws_t0ken." } ], - "poll_timeout": 300, + "wait_timeout": 300, "ping_timeout": 10, "sleep_time": 10, - "remove_entry_exit_signals": false + "remove_entry_exit_signals": false, + "message_size_limit": 8 }, "bot_name": "freqtrade", "db_url": "sqlite:///tradesv3.sqlite", diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 371cb9578..2fc855fbd 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -496,23 +496,24 @@ CONF_SCHEMA = { 'type': 'object', 'properties': { 'name': {'type': 'string'}, - 'url': {'type': 'string', 'default': ''}, - 'ws_token': {'type': 'string', 'default': ''}, + 'host': {'type': 'string'}, + 'port': {'type': 'integer', 'default': 8080}, + 'ws_token': {'type': 'string'}, }, - 'required': ['name', 'url', 'ws_token'] + 'required': ['name', 'host', 'ws_token'] } }, 'wait_timeout': {'type': 'integer', 'minimum': 0}, 'sleep_time': {'type': 'integer', 'minimum': 0}, 'ping_timeout': {'type': 'integer', 'minimum': 0}, - 'remove_signals_analyzed_df': {'type': 'boolean', 'default': False}, + 'remove_entry_exit_signals': {'type': 'boolean', 'default': False}, 'initial_candle_limit': { 'type': 'integer', 'minimum': 0, 'maximum': 1500, 'default': 1500 }, - 'max_message_size': { # In megabytes + 'message_size_limit': { # In megabytes 'type': 'integer', 'minimum': 1, 'maxmium': 20, diff --git a/freqtrade/rpc/api_server/api_ws.py b/freqtrade/rpc/api_server/api_ws.py index c4a3e9d4a..f55b2dbd3 100644 --- a/freqtrade/rpc/api_server/api_ws.py +++ b/freqtrade/rpc/api_server/api_ws.py @@ -101,8 +101,6 @@ async def message_endpoint( Message WebSocket endpoint, facilitates sending RPC messages """ try: - # TODO: - # Return a channel ID, pass that instead of ws to the rest of the methods channel = await channel_manager.on_connect(ws) if await is_websocket_alive(ws): diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 95031488d..6a8faef81 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -57,9 +57,6 @@ class ExternalMessageConsumer: self.enabled = self._emc_config.get('enabled', False) self.producers = self._emc_config.get('producers', []) - if self.enabled and len(self.producers) < 1: - raise OperationalException("You must specify at least 1 Producer to connect to.") - self.wait_timeout = self._emc_config.get('wait_timeout', 300) # in seconds self.ping_timeout = self._emc_config.get('ping_timeout', 10) # in seconds self.sleep_time = self._emc_config.get('sleep_time', 10) # in seconds @@ -71,6 +68,8 @@ class ExternalMessageConsumer: # as the websockets client expects bytes. self.message_size_limit = (self._emc_config.get('message_size_limit', 8) << 20) + self.validate_config() + # Setting these explicitly as they probably shouldn't be changed by a user # Unless we somehow integrate this with the strategy to allow creating # callbacks for the messages @@ -91,6 +90,18 @@ class ExternalMessageConsumer: self.start() + def validate_config(self): + """ + Make sure values are what they are supposed to be + """ + if self.enabled and len(self.producers) < 1: + raise OperationalException("You must specify at least 1 Producer to connect to.") + + if self.enabled and self._config.get('process_only_new_candles', True): + # Warning here or require it? + logger.warning("To receive best performance with external data," + "please set `process_only_new_candles` to False") + def start(self): """ Start the main internal loop in another thread to run coroutines @@ -174,12 +185,10 @@ class ExternalMessageConsumer: """ while self._running: try: - url, token = producer['url'], producer['ws_token'] - name = producer["name"] - ws_url = f"{url}?token={token}" - - logger.info( - f"Connecting to {name} @ {url}, max message size: {self.message_size_limit}") + host, port = producer['host'], producer['port'] + token = producer['ws_token'] + name = producer['name'] + ws_url = f"ws://{host}:{port}/api/v1/message/ws?token={token}" # This will raise InvalidURI if the url is bad async with websockets.connect(ws_url, max_size=self.message_size_limit) as ws: From 7d1645ac20df3392543b5c72f10ffefe65bc85c6 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 15 Sep 2022 17:54:31 -0600 Subject: [PATCH 103/115] fix tests and warning message --- freqtrade/rpc/external_message_consumer.py | 7 +- tests/rpc/test_rpc_emc.py | 96 ++++++++++++---------- 2 files changed, 53 insertions(+), 50 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 6a8faef81..e4b3c2609 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -99,7 +99,7 @@ class ExternalMessageConsumer: if self.enabled and self._config.get('process_only_new_candles', True): # Warning here or require it? - logger.warning("To receive best performance with external data," + logger.warning("To receive best performance with external data, " "please set `process_only_new_candles` to False") def start(self): @@ -205,11 +205,6 @@ class ExternalMessageConsumer: # Now receive data, if none is within the time limit, ping await self._receive_messages(channel, producer, lock) - # Catch invalid ws_url, and break the loop - except websockets.exceptions.InvalidURI as e: - logger.error(f"{ws_url} is an invalid WebSocket URL - {e}") - break - except ( socket.gaierror, ConnectionRefusedError, diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index 7bb727810..83276aabe 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -29,7 +29,8 @@ def patched_emc(default_conf, mocker): "producers": [ { "name": "default", - "url": "ws://null:9891/api/v1/message/ws", + "host": "null", + "port": 9891, "ws_token": _TEST_WS_TOKEN } ] @@ -166,7 +167,8 @@ async def test_emc_create_connection_success(default_conf, caplog, mocker): "producers": [ { "name": "default", - "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "host": _TEST_WS_HOST, + "port": _TEST_WS_PORT, "ws_token": _TEST_WS_TOKEN } ], @@ -198,42 +200,43 @@ async def test_emc_create_connection_success(default_conf, caplog, mocker): emc.shutdown() -async def test_emc_create_connection_invalid(default_conf, caplog, mocker): - default_conf.update({ - "external_message_consumer": { - "enabled": True, - "producers": [ - { - "name": "default", - "url": "ws://localhost:8080/api/v1/message/ws", - "ws_token": _TEST_WS_TOKEN - } - ], - "wait_timeout": 60, - "ping_timeout": 60, - "sleep_timeout": 60 - } - }) - - mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', - MagicMock()) - - test_producer = default_conf['external_message_consumer']['producers'][0] - lock = asyncio.Lock() - - dp = DataProvider(default_conf, None, None, None) - emc = ExternalMessageConsumer(default_conf, dp) - - try: - # Test invalid URL - test_producer['url'] = "tcp://localhost:8080/api/v1/message/ws" - emc._running = True - await emc._create_connection(test_producer, lock) - emc._running = False - - assert log_has_re(r".+is an invalid WebSocket URL.+", caplog) - finally: - emc.shutdown() +# async def test_emc_create_connection_invalid(default_conf, caplog, mocker): +# default_conf.update({ +# "external_message_consumer": { +# "enabled": True, +# "producers": [ +# { +# "name": "default", +# "host": _TEST_WS_HOST, +# "port": _TEST_WS_PORT, +# "ws_token": _TEST_WS_TOKEN +# } +# ], +# "wait_timeout": 60, +# "ping_timeout": 60, +# "sleep_timeout": 60 +# } +# }) +# +# mocker.patch('freqtrade.rpc.external_message_consumer.ExternalMessageConsumer.start', +# MagicMock()) +# +# test_producer = default_conf['external_message_consumer']['producers'][0] +# lock = asyncio.Lock() +# +# dp = DataProvider(default_conf, None, None, None) +# emc = ExternalMessageConsumer(default_conf, dp) +# +# try: +# # Test invalid URL +# test_producer['url'] = "tcp://null:8080/api/v1/message/ws" +# emc._running = True +# await emc._create_connection(test_producer, lock) +# emc._running = False +# +# assert log_has_re(r".+is an invalid WebSocket URL.+", caplog) +# finally: +# emc.shutdown() async def test_emc_create_connection_error(default_conf, caplog, mocker): @@ -243,7 +246,8 @@ async def test_emc_create_connection_error(default_conf, caplog, mocker): "producers": [ { "name": "default", - "url": "ws://localhost:8080/api/v1/message/ws", + "host": _TEST_WS_HOST, + "port": _TEST_WS_PORT, "ws_token": _TEST_WS_TOKEN } ], @@ -260,7 +264,7 @@ async def test_emc_create_connection_error(default_conf, caplog, mocker): emc = ExternalMessageConsumer(default_conf, dp) try: - await asyncio.sleep(1) + await asyncio.sleep(0.01) assert log_has("Unexpected error has occurred:", caplog) finally: emc.shutdown() @@ -273,7 +277,8 @@ async def test_emc_receive_messages_valid(default_conf, caplog, mocker): "producers": [ { "name": "default", - "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "host": _TEST_WS_HOST, + "port": _TEST_WS_PORT, "ws_token": _TEST_WS_TOKEN } ], @@ -319,7 +324,8 @@ async def test_emc_receive_messages_invalid(default_conf, caplog, mocker): "producers": [ { "name": "default", - "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "host": _TEST_WS_HOST, + "port": _TEST_WS_PORT, "ws_token": _TEST_WS_TOKEN } ], @@ -365,7 +371,8 @@ async def test_emc_receive_messages_timeout(default_conf, caplog, mocker): "producers": [ { "name": "default", - "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "host": _TEST_WS_HOST, + "port": _TEST_WS_PORT, "ws_token": _TEST_WS_TOKEN } ], @@ -411,7 +418,8 @@ async def test_emc_receive_messages_handle_error(default_conf, caplog, mocker): "producers": [ { "name": "default", - "url": f"ws://{_TEST_WS_HOST}:{_TEST_WS_PORT}/api/v1/message/ws", + "host": _TEST_WS_HOST, + "port": _TEST_WS_PORT, "ws_token": _TEST_WS_TOKEN } ], From 1ad25095c18cc44cdacc95ce9a9f5b0152285b0e Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Thu, 15 Sep 2022 19:40:45 -0600 Subject: [PATCH 104/115] change test server from localhost to 127.0.0.1 --- tests/rpc/test_rpc_emc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/rpc/test_rpc_emc.py b/tests/rpc/test_rpc_emc.py index 83276aabe..9aca88b4a 100644 --- a/tests/rpc/test_rpc_emc.py +++ b/tests/rpc/test_rpc_emc.py @@ -17,7 +17,7 @@ from tests.conftest import log_has, log_has_re, log_has_when _TEST_WS_TOKEN = "secret_Ws_t0ken" -_TEST_WS_HOST = "localhost" +_TEST_WS_HOST = "127.0.0.1" _TEST_WS_PORT = 9989 From b0b575ead919a9d197174d6da112d4068e6b896f Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 16 Sep 2022 00:02:27 -0600 Subject: [PATCH 105/115] change json serialize to split orient --- freqtrade/misc.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/misc.py b/freqtrade/misc.py index b2aca5fd6..56b3fef0e 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -259,7 +259,7 @@ def dataframe_to_json(dataframe: pandas.DataFrame) -> str: :param dataframe: A pandas DataFrame :returns: A JSON string of the pandas DataFrame """ - return dataframe.to_json(orient='records') + return dataframe.to_json(orient='split') def json_to_dataframe(data: str) -> pandas.DataFrame: @@ -268,7 +268,7 @@ def json_to_dataframe(data: str) -> pandas.DataFrame: :param data: A JSON string :returns: A pandas DataFrame from the JSON string """ - dataframe = pandas.read_json(data) + dataframe = pandas.read_json(data, orient='split') if 'date' in dataframe.columns: dataframe['date'] = pandas.to_datetime(dataframe['date'], unit='ms', utc=True) From 4422ac7f45f04b8ffb142fadf984c7c9e8438a51 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Fri, 16 Sep 2022 19:22:24 -0600 Subject: [PATCH 106/115] constrain port in config, catch value error --- freqtrade/constants.py | 7 ++++++- freqtrade/rpc/external_message_consumer.py | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 2fc855fbd..835b9dfcc 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -497,7 +497,12 @@ CONF_SCHEMA = { 'properties': { 'name': {'type': 'string'}, 'host': {'type': 'string'}, - 'port': {'type': 'integer', 'default': 8080}, + 'port': { + 'type': 'integer', + 'default': 8080, + 'minimum': 0, + 'maximum': 65535 + }, 'ws_token': {'type': 'string'}, }, 'required': ['name', 'host', 'ws_token'] diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index e4b3c2609..220f98706 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -205,6 +205,10 @@ class ExternalMessageConsumer: # Now receive data, if none is within the time limit, ping await self._receive_messages(channel, producer, lock) + except (websockets.exceptions.InvalidURI, ValueError) as e: + logger.error(f"{ws_url} is an invalid WebSocket URL - {e}") + break + except ( socket.gaierror, ConnectionRefusedError, From 3274bb07516bef27c28e547113dec4125f826467 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 20 Sep 2022 06:55:22 +0200 Subject: [PATCH 107/115] Remove msgpack for now --- freqtrade/rpc/api_server/ws/__init__.py | 2 +- freqtrade/rpc/api_server/ws/serializer.py | 9 --------- requirements.txt | 3 +-- setup.py | 1 - 4 files changed, 2 insertions(+), 13 deletions(-) diff --git a/freqtrade/rpc/api_server/ws/__init__.py b/freqtrade/rpc/api_server/ws/__init__.py index c00d29e22..055b20a9d 100644 --- a/freqtrade/rpc/api_server/ws/__init__.py +++ b/freqtrade/rpc/api_server/ws/__init__.py @@ -2,5 +2,5 @@ # isort: off from freqtrade.rpc.api_server.ws.types import WebSocketType from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy -from freqtrade.rpc.api_server.ws.serializer import HybridJSONWebSocketSerializer, MsgPackWebSocketSerializer +from freqtrade.rpc.api_server.ws.serializer import HybridJSONWebSocketSerializer from freqtrade.rpc.api_server.ws.channel import ChannelManager, WebSocketChannel diff --git a/freqtrade/rpc/api_server/ws/serializer.py b/freqtrade/rpc/api_server/ws/serializer.py index 22d177f85..6c402a100 100644 --- a/freqtrade/rpc/api_server/ws/serializer.py +++ b/freqtrade/rpc/api_server/ws/serializer.py @@ -1,7 +1,6 @@ import logging from abc import ABC, abstractmethod -import msgpack import orjson import rapidjson from pandas import DataFrame @@ -46,14 +45,6 @@ class HybridJSONWebSocketSerializer(WebSocketSerializer): return rapidjson.loads(data, object_hook=_json_object_hook) -class MsgPackWebSocketSerializer(WebSocketSerializer): - def _serialize(self, data): - return msgpack.packb(data, use_bin_type=True) - - def _deserialize(self, data): - return msgpack.unpackb(data, raw=False) - - # Support serializing pandas DataFrames def _json_default(z): if isinstance(z, DataFrame): diff --git a/requirements.txt b/requirements.txt index 1ace139ee..1579ef55c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -52,6 +52,5 @@ python-dateutil==2.8.2 schedule==1.1.0 #WS Messages -websockets~=10.3 -msgpack~=1.0.4 +websockets==10.3 janus==1.0.0 diff --git a/setup.py b/setup.py index c7b1f1c7c..2e6e354b0 100644 --- a/setup.py +++ b/setup.py @@ -81,7 +81,6 @@ setup( 'aiofiles', 'schedule', 'websockets', - 'msgpack', 'janus' ], extras_require={ From 366c6c24d897cb2e0d52e7ffbe2b927e553b79ac Mon Sep 17 00:00:00 2001 From: paranoidandy Date: Wed, 21 Sep 2022 15:22:50 +0100 Subject: [PATCH 108/115] Add docs for External Signals API --- docs/configuration.md | 5 +- docs/rest-api.md | 146 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 149 insertions(+), 2 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index f8a600e76..a37ca53ab 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -225,7 +225,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi | `webhook.webhookexitcancel` | Payload to send on exit order cancel. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
**Datatype:** String | `webhook.webhookexitfill` | Payload to send on exit order filled. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
**Datatype:** String | `webhook.webhookstatus` | Payload to send on status calls. Only required if `webhook.enabled` is `true`. See the [webhook documentation](webhook-config.md) for more details.
**Datatype:** String -| | **Rest API / FreqUI** +| | **Rest API / FreqUI / External Signals** | `api_server.enabled` | Enable usage of API Server. See the [API Server documentation](rest-api.md) for more details.
**Datatype:** Boolean | `api_server.listen_ip_address` | Bind IP address. See the [API Server documentation](rest-api.md) for more details.
**Datatype:** IPv4 | `api_server.listen_port` | Bind Port. See the [API Server documentation](rest-api.md) for more details.
**Datatype:** Integer between 1024 and 65535 @@ -233,6 +233,9 @@ Mandatory parameters are marked as **Required**, which means that they are requi | `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `bot_name` | Name of the bot. Passed via API to a client - can be shown to distinguish / name bots.
*Defaults to `freqtrade`*
**Datatype:** String +| `api_server.enable_message_ws` | Enable external signal publishing. See the [API Server documentation](rest-api.md) for more details.
**Datatype:** Boolean +| `api_server.ws_token` | API token for external signal publishing. Only required if `api_server.enable_message_ws` is `true`. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String +| `external_message_consumer` | Enable consuming of external signals. See the [API Server documentation](rest-api.md) for more details.
**Datatype:** Dict | | **Other** | `initial_state` | Defines the initial application state. If set to stopped, then the bot has to be explicitly started via `/start` RPC command.
*Defaults to `stopped`.*
**Datatype:** Enum, either `stopped` or `running` | `force_entry_enable` | Enables the RPC Commands to force a Trade entry. More information below.
**Datatype:** Boolean diff --git a/docs/rest-api.md b/docs/rest-api.md index 704f38f00..939258ca6 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -1,4 +1,4 @@ -# REST API & FreqUI +# REST API, FreqUI & External Signals ## FreqUI @@ -460,3 +460,147 @@ The correct configuration for this case is `http://localhost:8080` - the main pa !!! Note We strongly recommend to also set `jwt_secret_key` to something random and known only to yourself to avoid unauthorized access to your bot. + +## External Signals API + +FreqTrade provides a mechanism whereby a leader instance may provide analyzed dataframes to a subscriber/follower instance (or instances) using websockets. + +Run a bot in Leader mode to broadcast any populated indicators in the dataframes for each pair to bots running in Follower mode. This allows the reuse of computed indicators in multiple bots without needing to compute them multiple times. + +### Leader configuration + +Enable the leader websocket api by adding `enable_message_ws` to your `api_server` section and setting it to `true`, and providing an api token with `ws_token`. See [Security](#security) above for advice on token generation. + +!!! Note + We strongly recommend to also set `ws_token` to something random and known only to yourself to avoid unauthorized access to your bot. + +```jsonc +{ + //... + "api_server": { + //... + "enable_message_ws": true, + "ws_token": "mysecretapitoken" + //... + } + //... +} +``` + +The leader instance will listen for incoming reqests on the port configured by `api_server.listen_port` to forward its analyzed dataframes for each pair in its active whitelist calculated in its `populate_indicators()`. + +### Follower configuration + +Enable subscribing to a leader instance by adding the `external_message_consumer` section to the follower's config file. + +```jsonc +{ + //... + "external_message_consumer": { + "enabled": true, + "producers": [ + { + "name": "default", + "host": "127.0.0.1", + "port": 8080, + "ws_token": "mysecretapitoken" + } + ], + "reply_timeout": 10, + "ping_timeout": 5, + "sleep_time": 5, + "message_size_limit": 8, // in MB, default=8 + "remove_entry_exit_signals": false + } + //... +} +``` + +Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance opens a websocket connection to a leader instance (or multiple leader instances in advanced configurations) and requests the leader's most recently analyzed dataframes for each pair in the active whitelist. + +A follower instance will then have a full copy of the analyzed dataframes without the need to calculate them itself. + +### Example - Leader Strategy + +A simple strategy with multiple indicators. No special considerations are required in the strategy itself, only in the configuration file to enable websocket listening. + +```py +class LeaderStrategy(IStrategy): + #... + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Calculate indicators in the standard freqtrade way which can then be broadcast to other instances + """ + dataframe['rsi'] = ta.RSI(dataframe) + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) + dataframe['bb_lowerband'] = bollinger['lower'] + dataframe['bb_middleband'] = bollinger['mid'] + dataframe['bb_upperband'] = bollinger['upper'] + dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) + + return dataframe + + def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Populates the entry signal for the given dataframe + """ + dataframe.loc[ + ( + (qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)) & + (dataframe['tema'] <= dataframe['bb_middleband']) & + (dataframe['tema'] > dataframe['tema'].shift(1)) & + (dataframe['volume'] > 0) + ), + 'enter_long'] = 1 + + return dataframe +``` + +### Example - Follower Strategy + +A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes to make trading decisions from as the leader. In this example the follower has the same entry criteria, however this is not necessary. The follower may use different logic to enter/exit trades. + +```py +class FollowerStrategy(IStrategy): + #... + process_only_new_candles = False # required for followers + + _columns_to_expect = ['rsi_default', 'tema_default', 'bb_middleband_default'] + + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Use the websocket api to get pre-populated indicators from another FreqTrade instance. + Use `self.dp.get_external_df(pair)` to get the dataframe + """ + pair = metadata['pair'] + timeframe = self.timeframe + + leader_dataframe, _ = self.dp.get_external_df(pair) + + if not leader_dataframe.empty: + merged_dataframe = merge_informative_pair(dataframe, leader_dataframe, + timeframe, timeframe, + append_timeframe=False, + suffix="default") + return merged_dataframe + else: + dataframe[self._columns_to_expect] = 0 + + return dataframe + + def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Populates the entry signal for the given dataframe + """ + # Use the dataframe columns as if we calculated them ourselves + dataframe.loc[ + ( + (qtpylib.crossed_above(dataframe['rsi_default'], self.buy_rsi.value)) & + (dataframe['tema_default'] <= dataframe['bb_middleband_default']) & + (dataframe['tema_default'] > dataframe['tema_default'].shift(1)) & + (dataframe['volume'] > 0) + ), + 'enter_long'] = 1 + + return dataframe +``` \ No newline at end of file From 0811bca8b4ef384ee6c08a08f7fa6b3e344cc086 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 21 Sep 2022 15:50:11 -0600 Subject: [PATCH 109/115] revise docs, update dp method docstring --- docs/advanced-external-signals.md | 133 +++++++++++++++++++++++++++ docs/configuration.md | 5 +- docs/rest-api.md | 144 ------------------------------ freqtrade/data/dataprovider.py | 1 + mkdocs.yml | 1 + 5 files changed, 137 insertions(+), 147 deletions(-) create mode 100644 docs/advanced-external-signals.md diff --git a/docs/advanced-external-signals.md b/docs/advanced-external-signals.md new file mode 100644 index 000000000..caf708ee2 --- /dev/null +++ b/docs/advanced-external-signals.md @@ -0,0 +1,133 @@ +FreqTrade provides a mechanism whereby an instance may listen to messages from an upstream FreqTrade instance using the message websocket. Mainly, `analyzed_df` and `whitelist` messages. This allows the reuse of computed indicators (and signals) for pairs in multiple bots without needing to compute them multiple times. + +See [Message Websocket](rest-api.md#message-websocket) in the Rest API docs for setting up the `api_server` configuration for your message websocket. + +!!! Note + We strongly recommend to also set `ws_token` to something random and known only to yourself to avoid unauthorized access to your bot. + +### Configuration + +Enable subscribing to an instance by adding the `external_message_consumer` section to the follower's config file. + +```jsonc +{ + //... + "external_message_consumer": { + "enabled": true, + "producers": [ + { + "name": "default", // This can be any name you'd like, default is "default" + "host": "127.0.0.1", // The host from your leader's api_server config + "port": 8080, // The port from your leader's api_server config + "ws_token": "mysecretapitoken" // The ws_token from your leader's api_server config + } + ], + } + //... +} +``` + +See [`config_examples/config_full.example.json`](https://github.com/freqtrade/freqtrade/blob/develop/config_examples/config_full.example.json) for all of the parameters you can set. + +Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance listens on the connection to a leader instance's message websocket (or multiple leader instances in advanced configurations) and requests the leader's most recently analyzed dataframes for each pair in the active whitelist. + +A follower instance will then have a full copy of the analyzed dataframes without the need to calculate them itself. + +### Example - Leader Strategy + +A simple strategy with multiple indicators. No special considerations are required in the strategy itself. + +```py +class LeaderStrategy(IStrategy): + #... + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Calculate indicators in the standard freqtrade way which can then be broadcast to other instances + """ + dataframe['rsi'] = ta.RSI(dataframe) + bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) + dataframe['bb_lowerband'] = bollinger['lower'] + dataframe['bb_middleband'] = bollinger['mid'] + dataframe['bb_upperband'] = bollinger['upper'] + dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) + + return dataframe + + def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Populates the entry signal for the given dataframe + """ + dataframe.loc[ + ( + (qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)) & + (dataframe['tema'] <= dataframe['bb_middleband']) & + (dataframe['tema'] > dataframe['tema'].shift(1)) & + (dataframe['volume'] > 0) + ), + 'enter_long'] = 1 + + return dataframe +``` + +### Example - Follower Strategy + +A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes to make trading decisions from as the leader. In this example the follower has the same entry criteria, however this is not necessary. The follower may use different logic to enter/exit trades. + +```py +class FollowerStrategy(IStrategy): + #... + process_only_new_candles = False # required for followers + + _columns_to_expect = ['rsi_default', 'tema_default', 'bb_middleband_default'] + + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Use the websocket api to get pre-populated indicators from another FreqTrade instance. + Use `self.dp.get_external_df(pair)` to get the dataframe + """ + pair = metadata['pair'] + timeframe = self.timeframe + + leader_pairs = self.dp.get_producer_pairs() + # You can specify which producer to get pairs from via: + # self.dp.get_producer_pairs("my_other_producer") + + # This func returns the analyzed dataframe, and when it was analyzed + leader_dataframe, _ = self.dp.get_external_df(pair) + # You can get other data if your leader makes it available: + # self.dp.get_external_df( + # pair, + # timeframe="1h", + # candle_type=CandleType.SPOT, + # producer_name="my_other_producer" + # ) + + if not leader_dataframe.empty: + # If you plan on passing the leader's entry/exit signal directly, + # specify ffill=False or it will have unintended results + merged_dataframe = merge_informative_pair(dataframe, leader_dataframe, + timeframe, timeframe, + append_timeframe=False, + suffix="default") + return merged_dataframe + else: + dataframe[self._columns_to_expect] = 0 + + return dataframe + + def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Populates the entry signal for the given dataframe + """ + # Use the dataframe columns as if we calculated them ourselves + dataframe.loc[ + ( + (qtpylib.crossed_above(dataframe['rsi_default'], self.buy_rsi.value)) & + (dataframe['tema_default'] <= dataframe['bb_middleband_default']) & + (dataframe['tema_default'] > dataframe['tema_default'].shift(1)) & + (dataframe['volume'] > 0) + ), + 'enter_long'] = 1 + + return dataframe +``` diff --git a/docs/configuration.md b/docs/configuration.md index a37ca53ab..f4fb46707 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -110,7 +110,7 @@ This is similar to using multiple `--config` parameters, but simpler in usage as "stake_amount": "unlimited" } ``` - + If multiple files are in the `add_config_files` section, then they will be assumed to be at identical levels, having the last occurrence override the earlier config (unless a parent already defined such a key). ## Configuration parameters @@ -232,9 +232,8 @@ Mandatory parameters are marked as **Required**, which means that they are requi | `api_server.verbosity` | Logging verbosity. `info` will print all RPC Calls, while "error" will only display errors.
**Datatype:** Enum, either `info` or `error`. Defaults to `info`. | `api_server.username` | Username for API server. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String +| `api_server.ws_token` | API token for the Message WebSocket. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `bot_name` | Name of the bot. Passed via API to a client - can be shown to distinguish / name bots.
*Defaults to `freqtrade`*
**Datatype:** String -| `api_server.enable_message_ws` | Enable external signal publishing. See the [API Server documentation](rest-api.md) for more details.
**Datatype:** Boolean -| `api_server.ws_token` | API token for external signal publishing. Only required if `api_server.enable_message_ws` is `true`. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `external_message_consumer` | Enable consuming of external signals. See the [API Server documentation](rest-api.md) for more details.
**Datatype:** Dict | | **Other** | `initial_state` | Defines the initial application state. If set to stopped, then the bot has to be explicitly started via `/start` RPC command.
*Defaults to `stopped`.*
**Datatype:** Enum, either `stopped` or `running` diff --git a/docs/rest-api.md b/docs/rest-api.md index 939258ca6..e1ba1e889 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -460,147 +460,3 @@ The correct configuration for this case is `http://localhost:8080` - the main pa !!! Note We strongly recommend to also set `jwt_secret_key` to something random and known only to yourself to avoid unauthorized access to your bot. - -## External Signals API - -FreqTrade provides a mechanism whereby a leader instance may provide analyzed dataframes to a subscriber/follower instance (or instances) using websockets. - -Run a bot in Leader mode to broadcast any populated indicators in the dataframes for each pair to bots running in Follower mode. This allows the reuse of computed indicators in multiple bots without needing to compute them multiple times. - -### Leader configuration - -Enable the leader websocket api by adding `enable_message_ws` to your `api_server` section and setting it to `true`, and providing an api token with `ws_token`. See [Security](#security) above for advice on token generation. - -!!! Note - We strongly recommend to also set `ws_token` to something random and known only to yourself to avoid unauthorized access to your bot. - -```jsonc -{ - //... - "api_server": { - //... - "enable_message_ws": true, - "ws_token": "mysecretapitoken" - //... - } - //... -} -``` - -The leader instance will listen for incoming reqests on the port configured by `api_server.listen_port` to forward its analyzed dataframes for each pair in its active whitelist calculated in its `populate_indicators()`. - -### Follower configuration - -Enable subscribing to a leader instance by adding the `external_message_consumer` section to the follower's config file. - -```jsonc -{ - //... - "external_message_consumer": { - "enabled": true, - "producers": [ - { - "name": "default", - "host": "127.0.0.1", - "port": 8080, - "ws_token": "mysecretapitoken" - } - ], - "reply_timeout": 10, - "ping_timeout": 5, - "sleep_time": 5, - "message_size_limit": 8, // in MB, default=8 - "remove_entry_exit_signals": false - } - //... -} -``` - -Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance opens a websocket connection to a leader instance (or multiple leader instances in advanced configurations) and requests the leader's most recently analyzed dataframes for each pair in the active whitelist. - -A follower instance will then have a full copy of the analyzed dataframes without the need to calculate them itself. - -### Example - Leader Strategy - -A simple strategy with multiple indicators. No special considerations are required in the strategy itself, only in the configuration file to enable websocket listening. - -```py -class LeaderStrategy(IStrategy): - #... - def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: - """ - Calculate indicators in the standard freqtrade way which can then be broadcast to other instances - """ - dataframe['rsi'] = ta.RSI(dataframe) - bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) - dataframe['bb_lowerband'] = bollinger['lower'] - dataframe['bb_middleband'] = bollinger['mid'] - dataframe['bb_upperband'] = bollinger['upper'] - dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) - - return dataframe - - def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: - """ - Populates the entry signal for the given dataframe - """ - dataframe.loc[ - ( - (qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)) & - (dataframe['tema'] <= dataframe['bb_middleband']) & - (dataframe['tema'] > dataframe['tema'].shift(1)) & - (dataframe['volume'] > 0) - ), - 'enter_long'] = 1 - - return dataframe -``` - -### Example - Follower Strategy - -A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes to make trading decisions from as the leader. In this example the follower has the same entry criteria, however this is not necessary. The follower may use different logic to enter/exit trades. - -```py -class FollowerStrategy(IStrategy): - #... - process_only_new_candles = False # required for followers - - _columns_to_expect = ['rsi_default', 'tema_default', 'bb_middleband_default'] - - def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: - """ - Use the websocket api to get pre-populated indicators from another FreqTrade instance. - Use `self.dp.get_external_df(pair)` to get the dataframe - """ - pair = metadata['pair'] - timeframe = self.timeframe - - leader_dataframe, _ = self.dp.get_external_df(pair) - - if not leader_dataframe.empty: - merged_dataframe = merge_informative_pair(dataframe, leader_dataframe, - timeframe, timeframe, - append_timeframe=False, - suffix="default") - return merged_dataframe - else: - dataframe[self._columns_to_expect] = 0 - - return dataframe - - def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: - """ - Populates the entry signal for the given dataframe - """ - # Use the dataframe columns as if we calculated them ourselves - dataframe.loc[ - ( - (qtpylib.crossed_above(dataframe['rsi_default'], self.buy_rsi.value)) & - (dataframe['tema_default'] <= dataframe['bb_middleband_default']) & - (dataframe['tema_default'] > dataframe['tema_default'].shift(1)) & - (dataframe['volume'] > 0) - ), - 'enter_long'] = 1 - - return dataframe -``` \ No newline at end of file diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 1dfa53caa..031a6d704 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -163,6 +163,7 @@ class DataProvider: :param pair: pair to get the data for :param timeframe: Timeframe to get data for :param candle_type: Any of the enum CandleType (must match trading mode!) + :returns: Tuple of the DataFrame and last analyzed timestamp """ _timeframe = self._default_timeframe if not timeframe else timeframe _candle_type = self._default_candle_type if not candle_type else candle_type diff --git a/mkdocs.yml b/mkdocs.yml index 257db7867..27995cfc0 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -35,6 +35,7 @@ nav: - Advanced Post-installation Tasks: advanced-setup.md - Advanced Strategy: strategy-advanced.md - Advanced Hyperopt: advanced-hyperopt.md + - External Signals: advanced-external-signals.md - FreqAI: freqai.md - Edge Positioning: edge.md - Sandbox Testing: sandbox-testing.md From 128b117af66f5091796ce82d9c453fd4432f6f77 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 21 Sep 2022 16:02:21 -0600 Subject: [PATCH 110/115] support list of tokens in ws_token --- freqtrade/constants.py | 2 +- freqtrade/rpc/api_server/api_auth.py | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index e2a24ea35..a97ded95b 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -401,7 +401,7 @@ CONF_SCHEMA = { }, 'username': {'type': 'string'}, 'password': {'type': 'string'}, - 'ws_token': {'type': 'string'}, + 'ws_token': {'type': ['string', 'array'], 'items': {'type': 'string'}}, 'jwt_secret_key': {'type': 'string'}, 'CORS_origins': {'type': 'array', 'items': {'type': 'string'}}, 'verbosity': {'type': 'string', 'enum': ['error', 'info']}, diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index e91e5941b..492daf5a2 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -59,9 +59,18 @@ async def validate_ws_token( secret_ws_token = api_config.get('ws_token', None) secret_jwt_key = api_config.get('jwt_secret_key', 'super-secret') - if ws_token and secret_ws_token and secrets.compare_digest(secret_ws_token, ws_token): - # Just return the token if it matches - return ws_token + if ws_token and secret_ws_token: + is_valid_ws_token = False + if isinstance(secret_ws_token, str): + is_valid_ws_token = secrets.compare_digest(secret_ws_token, ws_token) + elif isinstance(secret_ws_token, list): + is_valid_ws_token = any([ + secrets.compare_digest(potential, ws_token) + for potential in secret_ws_token + ]) + + if is_valid_ws_token: + return ws_token else: try: user = get_user_from_token(ws_token, secret_jwt_key) From 77ed713232851a72200c1446acf8aae60d9a104d Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 21 Sep 2022 16:04:25 -0600 Subject: [PATCH 111/115] add catch for invalid message error --- freqtrade/rpc/external_message_consumer.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 220f98706..61b8ac2db 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -212,7 +212,8 @@ class ExternalMessageConsumer: except ( socket.gaierror, ConnectionRefusedError, - websockets.exceptions.InvalidStatusCode + websockets.exceptions.InvalidStatusCode, + websockets.exceptions.InvalidMessage ) as e: logger.error(f"Connection Refused - {e} retrying in {self.sleep_time}s") await asyncio.sleep(self.sleep_time) @@ -224,7 +225,7 @@ class ExternalMessageConsumer: continue except Exception as e: - # An unforseen error has occurred, log and stop + # An unforseen error has occurred, log and continue logger.error("Unexpected error has occurred:") logger.exception(e) continue From 6a6ae809f465f4d92cc6e2db45877ae621ded5a3 Mon Sep 17 00:00:00 2001 From: Timothy Pogue Date: Wed, 21 Sep 2022 18:23:00 -0600 Subject: [PATCH 112/115] fix jwt auth --- freqtrade/rpc/api_server/api_auth.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/freqtrade/rpc/api_server/api_auth.py b/freqtrade/rpc/api_server/api_auth.py index 492daf5a2..ee66fce2b 100644 --- a/freqtrade/rpc/api_server/api_auth.py +++ b/freqtrade/rpc/api_server/api_auth.py @@ -59,6 +59,7 @@ async def validate_ws_token( secret_ws_token = api_config.get('ws_token', None) secret_jwt_key = api_config.get('jwt_secret_key', 'super-secret') + # Check if ws_token is/in secret_ws_token if ws_token and secret_ws_token: is_valid_ws_token = False if isinstance(secret_ws_token, str): @@ -71,13 +72,16 @@ async def validate_ws_token( if is_valid_ws_token: return ws_token - else: - try: - user = get_user_from_token(ws_token, secret_jwt_key) - return user - # If the token is a jwt, and it's valid return the user - except HTTPException: - pass + + # Check if ws_token is a JWT + try: + user = get_user_from_token(ws_token, secret_jwt_key) + return user + # If the token is a jwt, and it's valid return the user + except HTTPException: + pass + + # No checks passed, deny the connection logger.debug("Denying websocket request.") # If it doesn't match, close the websocket connection await ws.close(code=status.WS_1008_POLICY_VIOLATION) From e6c5c22ea08114d4ea1f5409d1afc4e3cd8d4ec3 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 22 Sep 2022 19:58:38 +0200 Subject: [PATCH 113/115] Update websocket/follower docs --- docs/advanced-external-signals.md | 37 ++++++++++++++++++---- docs/configuration.md | 2 +- docs/rest-api.md | 15 ++++----- freqtrade/rpc/external_message_consumer.py | 2 +- 4 files changed, 38 insertions(+), 18 deletions(-) diff --git a/docs/advanced-external-signals.md b/docs/advanced-external-signals.md index caf708ee2..3fb3ce6ce 100644 --- a/docs/advanced-external-signals.md +++ b/docs/advanced-external-signals.md @@ -1,15 +1,17 @@ -FreqTrade provides a mechanism whereby an instance may listen to messages from an upstream FreqTrade instance using the message websocket. Mainly, `analyzed_df` and `whitelist` messages. This allows the reuse of computed indicators (and signals) for pairs in multiple bots without needing to compute them multiple times. +# External Signals + +freqtrade provides a mechanism whereby an instance may listen to messages from an upstream freqtrade instance using the message websocket. Mainly, `analyzed_df` and `whitelist` messages. This allows the reuse of computed indicators (and signals) for pairs in multiple bots without needing to compute them multiple times. See [Message Websocket](rest-api.md#message-websocket) in the Rest API docs for setting up the `api_server` configuration for your message websocket. !!! Note We strongly recommend to also set `ws_token` to something random and known only to yourself to avoid unauthorized access to your bot. -### Configuration +## Configuration Enable subscribing to an instance by adding the `external_message_consumer` section to the follower's config file. -```jsonc +```json { //... "external_message_consumer": { @@ -22,17 +24,38 @@ Enable subscribing to an instance by adding the `external_message_consumer` sect "ws_token": "mysecretapitoken" // The ws_token from your leader's api_server config } ], + // The following configurations are optional, and usually not required + // "wait_timeout": 300, + // "ping_timeout": 10, + // "sleep_time": 10, + // "remove_entry_exit_signals": false, + // "message_size_limit": 8 } //... } ``` -See [`config_examples/config_full.example.json`](https://github.com/freqtrade/freqtrade/blob/develop/config_examples/config_full.example.json) for all of the parameters you can set. +| Parameter | Description | +|------------|-------------| +| `enabled` | **Required.** Enable follower mode. If set to false, all other settings in this section are ignored.
*Defaults to `false`.*
**Datatype:** boolean . +| `producers` | **Required.** List of producers
**Datatype:** Array. +| `producers.name` | **Required.** Name of this producer. This name must be used in calls to `get_producer_pairs()` and `get_external_df()` if more than one producer is used.
**Datatype:** string +| `producers.host` | **Required.** The hostname or IP address from your leader.
**Datatype:** string +| `producers.port` | **Required.** The port matching the above host.
**Datatype:** string +| `producers.ws_token` | **Required.** `ws_token` as configured on the leader.
**Datatype:** string +| | **Optional settings** +| `wait_timeout` | Timeout until we ping again if no message is received.
*Defaults to `300`.*
**Datatype:** Integer - in seconds. +| `wait_timeout` | Ping timeout
*Defaults to `10`.*
**Datatype:** Integer - in seconds. +| `sleep_time` | Sleep time before retrying to connect.
*Defaults to `10`.*
**Datatype:** Integer - in seconds. +| `remove_entry_exit_signals` | Remove signal columns from the dataframe (set them to 0) on dataframe receipt.
*Defaults to `10`.*
**Datatype:** Integer - in seconds. +| `message_size_limit` | Size limit per message
*Defaults to `8`.*
**Datatype:** Integer - Megabytes. -Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance listens on the connection to a leader instance's message websocket (or multiple leader instances in advanced configurations) and requests the leader's most recently analyzed dataframes for each pair in the active whitelist. +Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance listens on the connection to a leader instance's messages (or multiple leader instances in advanced configurations) and requests the leader's most recently analyzed dataframes for each pair in the active whitelist. A follower instance will then have a full copy of the analyzed dataframes without the need to calculate them itself. +## Examples + ### Example - Leader Strategy A simple strategy with multiple indicators. No special considerations are required in the strategy itself. @@ -71,7 +94,7 @@ class LeaderStrategy(IStrategy): ### Example - Follower Strategy -A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes to make trading decisions from as the leader. In this example the follower has the same entry criteria, however this is not necessary. The follower may use different logic to enter/exit trades. +A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes available to make trading decisions based on the indicators calculated in the leader. In this example the follower has the same entry criteria, however this is not necessary. The follower may use different logic to enter/exit trades, and only use the indicators as specified. ```py class FollowerStrategy(IStrategy): @@ -82,7 +105,7 @@ class FollowerStrategy(IStrategy): def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ - Use the websocket api to get pre-populated indicators from another FreqTrade instance. + Use the websocket api to get pre-populated indicators from another freqtrade instance. Use `self.dp.get_external_df(pair)` to get the dataframe """ pair = metadata['pair'] diff --git a/docs/configuration.md b/docs/configuration.md index f4fb46707..211feef05 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -234,7 +234,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi | `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `api_server.ws_token` | API token for the Message WebSocket. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `bot_name` | Name of the bot. Passed via API to a client - can be shown to distinguish / name bots.
*Defaults to `freqtrade`*
**Datatype:** String -| `external_message_consumer` | Enable consuming of external signals. See the [API Server documentation](rest-api.md) for more details.
**Datatype:** Dict +| `external_message_consumer` | Enable consuming of external signals. See the [External signals](advanced-external-signals.md) for more details.
**Datatype:** Dict | | **Other** | `initial_state` | Defines the initial application state. If set to stopped, then the bot has to be explicitly started via `/start` RPC command.
*Defaults to `stopped`.*
**Datatype:** Enum, either `stopped` or `running` | `force_entry_enable` | Enables the RPC Commands to force a Trade entry. More information below.
**Datatype:** Boolean diff --git a/docs/rest-api.md b/docs/rest-api.md index e1ba1e889..1f09704b7 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -1,4 +1,4 @@ -# REST API, FreqUI & External Signals +# REST API & FreqUI ## FreqUI @@ -325,15 +325,14 @@ whitelist ### Message WebSocket -The API Server makes available a websocket endpoint for subscribing to RPC messages -from the FreqTrade Bot. This can be used to consume real-time data from your bot, such as entry/exit fill messages, whitelist changes, populated indicators for pairs, and more. +The API Server includes a websocket endpoint for subscribing to RPC messages +from the freqtrade Bot. This can be used to consume real-time data from your bot, such as entry/exit fill messages, whitelist changes, populated indicators for pairs, and more. Assuming your rest API is set to `127.0.0.1` on port `8080`, the endpoint is available at `http://localhost:8080/api/v1/message/ws`. To access the websocket endpoint, the `ws_token` is required as a query parameter in the endpoint URL. - - To generate a safe `ws_token` you can run the following code: +To generate a safe `ws_token` you can run the following code: ``` python >>> import secrets @@ -341,7 +340,6 @@ To access the websocket endpoint, the `ws_token` is required as a query paramete 'hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q' ``` - You would then add that token under `ws_token` in your `api_server` config. Like so: ``` json @@ -361,11 +359,9 @@ You would then add that token under `ws_token` in your `api_server` config. Like You can now connect to the endpoint at `http://localhost:8080/api/v1/message/ws?token=hZ-y58LXyX_HZ8O1cJzVyN6ePWrLpNQv4Q`. -!!! warning "Warning" - +!!! Danger "Reuse of example tokens" Please do not use the above example token. To make sure you are secure, generate a completely new token. - #### Using the WebSocket Once connected to the WebSocket, the bot will broadcast RPC messages to anyone who is subscribed to them. To subscribe to a list of messages, you must send a JSON request through the WebSocket like the one below. The `data` key must be a list of message type strings. @@ -376,6 +372,7 @@ Once connected to the WebSocket, the bot will broadcast RPC messages to anyone w "data": ["whitelist", "analyzed_df"] // A list of string message types } ``` + For a list of message types, please refer to the RPCMessageType enum in `freqtrade/enums/rpcmessagetype.py` Now anytime those types of RPC messages are sent in the bot, you will receive them through the WebSocket as long as the connection is active. They typically take the same form as the request: diff --git a/freqtrade/rpc/external_message_consumer.py b/freqtrade/rpc/external_message_consumer.py index 61b8ac2db..a57fac144 100644 --- a/freqtrade/rpc/external_message_consumer.py +++ b/freqtrade/rpc/external_message_consumer.py @@ -35,7 +35,7 @@ logger = logging.getLogger(__name__) class ExternalMessageConsumer: """ The main controller class for consuming external messages from - other FreqTrade bot's + other freqtrade bot's """ def __init__( From 1626eb7f97f3a3d4edbd5a5768dbc68916787a9e Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 22 Sep 2022 20:46:40 +0200 Subject: [PATCH 114/115] Update dataprovider function name to `get_producer_df` --- docs/advanced-external-signals.md | 8 ++++---- freqtrade/data/dataprovider.py | 4 ++-- tests/data/test_dataprovider.py | 10 +++++----- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/advanced-external-signals.md b/docs/advanced-external-signals.md index 3fb3ce6ce..43ff8f6d0 100644 --- a/docs/advanced-external-signals.md +++ b/docs/advanced-external-signals.md @@ -39,7 +39,7 @@ Enable subscribing to an instance by adding the `external_message_consumer` sect |------------|-------------| | `enabled` | **Required.** Enable follower mode. If set to false, all other settings in this section are ignored.
*Defaults to `false`.*
**Datatype:** boolean . | `producers` | **Required.** List of producers
**Datatype:** Array. -| `producers.name` | **Required.** Name of this producer. This name must be used in calls to `get_producer_pairs()` and `get_external_df()` if more than one producer is used.
**Datatype:** string +| `producers.name` | **Required.** Name of this producer. This name must be used in calls to `get_producer_pairs()` and `get_producer_df()` if more than one producer is used.
**Datatype:** string | `producers.host` | **Required.** The hostname or IP address from your leader.
**Datatype:** string | `producers.port` | **Required.** The port matching the above host.
**Datatype:** string | `producers.ws_token` | **Required.** `ws_token` as configured on the leader.
**Datatype:** string @@ -106,7 +106,7 @@ class FollowerStrategy(IStrategy): def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Use the websocket api to get pre-populated indicators from another freqtrade instance. - Use `self.dp.get_external_df(pair)` to get the dataframe + Use `self.dp.get_producer_df(pair)` to get the dataframe """ pair = metadata['pair'] timeframe = self.timeframe @@ -116,9 +116,9 @@ class FollowerStrategy(IStrategy): # self.dp.get_producer_pairs("my_other_producer") # This func returns the analyzed dataframe, and when it was analyzed - leader_dataframe, _ = self.dp.get_external_df(pair) + leader_dataframe, _ = self.dp.get_producer_df(pair) # You can get other data if your leader makes it available: - # self.dp.get_external_df( + # self.dp.get_producer_df( # pair, # timeframe="1h", # candle_type=CandleType.SPOT, diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index 031a6d704..1a0903516 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -150,7 +150,7 @@ class DataProvider: self.__producer_pairs_df[producer_name][pair_key] = (dataframe, _last_analyzed) logger.debug(f"External DataFrame for {pair_key} from {producer_name} added.") - def get_external_df( + def get_producer_df( self, pair: str, timeframe: Optional[str] = None, @@ -158,7 +158,7 @@ class DataProvider: producer_name: str = "default" ) -> Tuple[DataFrame, datetime]: """ - Get the pair data from the external sources. + Get the pair data from producers. :param pair: pair to get the data for :param timeframe: Timeframe to get data for diff --git a/tests/data/test_dataprovider.py b/tests/data/test_dataprovider.py index 9915b6316..8500fa06c 100644 --- a/tests/data/test_dataprovider.py +++ b/tests/data/test_dataprovider.py @@ -161,7 +161,7 @@ def test_producer_pairs(mocker, default_conf, ohlcv_history): assert dataprovider.get_producer_pairs("bad") == [] -def test_external_df(mocker, default_conf, ohlcv_history): +def test_get_producer_df(mocker, default_conf, ohlcv_history): dataprovider = DataProvider(default_conf, None) pair = 'BTC/USDT' @@ -172,23 +172,23 @@ def test_external_df(mocker, default_conf, ohlcv_history): now = datetime.now(timezone.utc) # no data has been added, any request should return an empty dataframe - dataframe, la = dataprovider.get_external_df(pair, timeframe, candle_type) + dataframe, la = dataprovider.get_producer_df(pair, timeframe, candle_type) assert dataframe.empty assert la == empty_la # the data is added, should return that added dataframe dataprovider._add_external_df(pair, ohlcv_history, now, timeframe, candle_type) - dataframe, la = dataprovider.get_external_df(pair, timeframe, candle_type) + dataframe, la = dataprovider.get_producer_df(pair, timeframe, candle_type) assert len(dataframe) > 0 assert la > empty_la # no data on this producer, should return empty dataframe - dataframe, la = dataprovider.get_external_df(pair, producer_name='bad') + dataframe, la = dataprovider.get_producer_df(pair, producer_name='bad') assert dataframe.empty assert la == empty_la # non existent timeframe, empty dataframe - datframe, la = dataprovider.get_external_df(pair, timeframe='1h') + datframe, la = dataprovider.get_producer_df(pair, timeframe='1h') assert dataframe.empty assert la == empty_la From 06a5cfa4010d9a276b33ea19d51a213bbf174ce0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 22 Sep 2022 21:08:06 +0200 Subject: [PATCH 115/115] Update "branding" to producer/follower mode --- docs/configuration.md | 2 +- ...ternal-signals.md => producer-consumer.md} | 57 +++++++++++-------- docs/rest-api.md | 7 ++- mkdocs.yml | 2 +- 4 files changed, 38 insertions(+), 30 deletions(-) rename docs/{advanced-external-signals.md => producer-consumer.md} (68%) diff --git a/docs/configuration.md b/docs/configuration.md index 211feef05..fe94613ff 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -234,7 +234,7 @@ Mandatory parameters are marked as **Required**, which means that they are requi | `api_server.password` | Password for API server. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `api_server.ws_token` | API token for the Message WebSocket. See the [API Server documentation](rest-api.md) for more details.
**Keep it in secret, do not disclose publicly.**
**Datatype:** String | `bot_name` | Name of the bot. Passed via API to a client - can be shown to distinguish / name bots.
*Defaults to `freqtrade`*
**Datatype:** String -| `external_message_consumer` | Enable consuming of external signals. See the [External signals](advanced-external-signals.md) for more details.
**Datatype:** Dict +| `external_message_consumer` | Enable [Producer/Consumer mode](producer-consumer.md) for more details.
**Datatype:** Dict | | **Other** | `initial_state` | Defines the initial application state. If set to stopped, then the bot has to be explicitly started via `/start` RPC command.
*Defaults to `stopped`.*
**Datatype:** Enum, either `stopped` or `running` | `force_entry_enable` | Enables the RPC Commands to force a Trade entry. More information below.
**Datatype:** Boolean diff --git a/docs/advanced-external-signals.md b/docs/producer-consumer.md similarity index 68% rename from docs/advanced-external-signals.md rename to docs/producer-consumer.md index 43ff8f6d0..b69406edf 100644 --- a/docs/advanced-external-signals.md +++ b/docs/producer-consumer.md @@ -1,15 +1,15 @@ -# External Signals +# Producer / Consumer mode -freqtrade provides a mechanism whereby an instance may listen to messages from an upstream freqtrade instance using the message websocket. Mainly, `analyzed_df` and `whitelist` messages. This allows the reuse of computed indicators (and signals) for pairs in multiple bots without needing to compute them multiple times. +freqtrade provides a mechanism whereby an instance (also called `consumer`) may listen to messages from an upstream freqtrade instance (also called `producer`) using the message websocket. Mainly, `analyzed_df` and `whitelist` messages. This allows the reuse of computed indicators (and signals) for pairs in multiple bots without needing to compute them multiple times. -See [Message Websocket](rest-api.md#message-websocket) in the Rest API docs for setting up the `api_server` configuration for your message websocket. +See [Message Websocket](rest-api.md#message-websocket) in the Rest API docs for setting up the `api_server` configuration for your message websocket (this will be your producer). !!! Note - We strongly recommend to also set `ws_token` to something random and known only to yourself to avoid unauthorized access to your bot. + We strongly recommend to set `ws_token` to something random and known only to yourself to avoid unauthorized access to your bot. ## Configuration -Enable subscribing to an instance by adding the `external_message_consumer` section to the follower's config file. +Enable subscribing to an instance by adding the `external_message_consumer` section to the consumer's config file. ```json { @@ -19,9 +19,9 @@ Enable subscribing to an instance by adding the `external_message_consumer` sect "producers": [ { "name": "default", // This can be any name you'd like, default is "default" - "host": "127.0.0.1", // The host from your leader's api_server config - "port": 8080, // The port from your leader's api_server config - "ws_token": "mysecretapitoken" // The ws_token from your leader's api_server config + "host": "127.0.0.1", // The host from your producer's api_server config + "port": 8080, // The port from your producer's api_server config + "ws_token": "sercet_Ws_t0ken" // The ws_token from your producer's api_server config } ], // The following configurations are optional, and usually not required @@ -37,12 +37,12 @@ Enable subscribing to an instance by adding the `external_message_consumer` sect | Parameter | Description | |------------|-------------| -| `enabled` | **Required.** Enable follower mode. If set to false, all other settings in this section are ignored.
*Defaults to `false`.*
**Datatype:** boolean . +| `enabled` | **Required.** Enable consumer mode. If set to false, all other settings in this section are ignored.
*Defaults to `false`.*
**Datatype:** boolean . | `producers` | **Required.** List of producers
**Datatype:** Array. | `producers.name` | **Required.** Name of this producer. This name must be used in calls to `get_producer_pairs()` and `get_producer_df()` if more than one producer is used.
**Datatype:** string -| `producers.host` | **Required.** The hostname or IP address from your leader.
**Datatype:** string +| `producers.host` | **Required.** The hostname or IP address from your producer.
**Datatype:** string | `producers.port` | **Required.** The port matching the above host.
**Datatype:** string -| `producers.ws_token` | **Required.** `ws_token` as configured on the leader.
**Datatype:** string +| `producers.ws_token` | **Required.** `ws_token` as configured on the producer.
**Datatype:** string | | **Optional settings** | `wait_timeout` | Timeout until we ping again if no message is received.
*Defaults to `300`.*
**Datatype:** Integer - in seconds. | `wait_timeout` | Ping timeout
*Defaults to `10`.*
**Datatype:** Integer - in seconds. @@ -50,18 +50,18 @@ Enable subscribing to an instance by adding the `external_message_consumer` sect | `remove_entry_exit_signals` | Remove signal columns from the dataframe (set them to 0) on dataframe receipt.
*Defaults to `10`.*
**Datatype:** Integer - in seconds. | `message_size_limit` | Size limit per message
*Defaults to `8`.*
**Datatype:** Integer - Megabytes. -Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance listens on the connection to a leader instance's messages (or multiple leader instances in advanced configurations) and requests the leader's most recently analyzed dataframes for each pair in the active whitelist. +Instead of (or as well as) calculating indicators in `populate_indicators()` the follower instance listens on the connection to a producer instance's messages (or multiple producer instances in advanced configurations) and requests the producer's most recently analyzed dataframes for each pair in the active whitelist. -A follower instance will then have a full copy of the analyzed dataframes without the need to calculate them itself. +A consumer instance will then have a full copy of the analyzed dataframes without the need to calculate them itself. ## Examples -### Example - Leader Strategy +### Example - Producer Strategy A simple strategy with multiple indicators. No special considerations are required in the strategy itself. ```py -class LeaderStrategy(IStrategy): +class ProducerStrategy(IStrategy): #... def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ @@ -92,14 +92,18 @@ class LeaderStrategy(IStrategy): return dataframe ``` -### Example - Follower Strategy +!!! Tip "FreqAI" + You can use this to setup [FreqAI](freqai.md) on a powerful machine, while you run consumers on simple machines like raspberries, which can interpret the signals generated from the producer in different ways. -A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes available to make trading decisions based on the indicators calculated in the leader. In this example the follower has the same entry criteria, however this is not necessary. The follower may use different logic to enter/exit trades, and only use the indicators as specified. + +### Example - Consumer Strategy + +A logically equivalent strategy which calculates no indicators itself, but will have the same analyzed dataframes available to make trading decisions based on the indicators calculated in the producer. In this example the consumer has the same entry criteria, however this is not necessary. The consumer may use different logic to enter/exit trades, and only use the indicators as specified. ```py -class FollowerStrategy(IStrategy): +class ConsumerStrategy(IStrategy): #... - process_only_new_candles = False # required for followers + process_only_new_candles = False # required for consumers _columns_to_expect = ['rsi_default', 'tema_default', 'bb_middleband_default'] @@ -111,13 +115,13 @@ class FollowerStrategy(IStrategy): pair = metadata['pair'] timeframe = self.timeframe - leader_pairs = self.dp.get_producer_pairs() + producer_pairs = self.dp.get_producer_pairs() # You can specify which producer to get pairs from via: # self.dp.get_producer_pairs("my_other_producer") # This func returns the analyzed dataframe, and when it was analyzed - leader_dataframe, _ = self.dp.get_producer_df(pair) - # You can get other data if your leader makes it available: + producer_dataframe, _ = self.dp.get_producer_df(pair) + # You can get other data if the producer makes it available: # self.dp.get_producer_df( # pair, # timeframe="1h", @@ -125,10 +129,10 @@ class FollowerStrategy(IStrategy): # producer_name="my_other_producer" # ) - if not leader_dataframe.empty: - # If you plan on passing the leader's entry/exit signal directly, + if not producer_dataframe.empty: + # If you plan on passing the producer's entry/exit signal directly, # specify ffill=False or it will have unintended results - merged_dataframe = merge_informative_pair(dataframe, leader_dataframe, + merged_dataframe = merge_informative_pair(dataframe, producer_dataframe, timeframe, timeframe, append_timeframe=False, suffix="default") @@ -154,3 +158,6 @@ class FollowerStrategy(IStrategy): return dataframe ``` + +!!! Tip "Using upstream signals" + By setting `remove_entry_exit_signals=false`, you can also use the producer's signals directly. They should be available as `enter_long_default` (assuming `suffix="default"` was used) - and can be used as either signal directly, or as additional indicator. diff --git a/docs/rest-api.md b/docs/rest-api.md index 1f09704b7..c7d762648 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -94,7 +94,6 @@ Make sure that the following 2 lines are available in your docker-compose file: !!! Danger "Security warning" By using `8080:8080` in the docker port mapping, the API will be available to everyone connecting to the server under the correct port, so others may be able to control your bot. - ## Rest API ### Consuming the API @@ -325,8 +324,10 @@ whitelist ### Message WebSocket -The API Server includes a websocket endpoint for subscribing to RPC messages -from the freqtrade Bot. This can be used to consume real-time data from your bot, such as entry/exit fill messages, whitelist changes, populated indicators for pairs, and more. +The API Server includes a websocket endpoint for subscribing to RPC messages from the freqtrade Bot. +This can be used to consume real-time data from your bot, such as entry/exit fill messages, whitelist changes, populated indicators for pairs, and more. + +This is also used to setup [Producer/Consumer mode](producer-consumer.md) in Freqtrade. Assuming your rest API is set to `127.0.0.1` on port `8080`, the endpoint is available at `http://localhost:8080/api/v1/message/ws`. diff --git a/mkdocs.yml b/mkdocs.yml index 27995cfc0..fd0280e83 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -35,7 +35,7 @@ nav: - Advanced Post-installation Tasks: advanced-setup.md - Advanced Strategy: strategy-advanced.md - Advanced Hyperopt: advanced-hyperopt.md - - External Signals: advanced-external-signals.md + - Producer/Consumer mode: producer-consumer.md - FreqAI: freqai.md - Edge Positioning: edge.md - Sandbox Testing: sandbox-testing.md