2022-12-07 16:01:45 +00:00
|
|
|
"""
|
|
|
|
Remote PairList provider
|
|
|
|
|
|
|
|
Provides pair list fetched from a remote source
|
|
|
|
"""
|
2024-05-12 14:37:11 +00:00
|
|
|
|
2022-12-07 16:01:45 +00:00
|
|
|
import logging
|
2022-12-07 23:52:54 +00:00
|
|
|
from pathlib import Path
|
2022-12-19 14:36:28 +00:00
|
|
|
from typing import Any, Dict, List, Tuple
|
2022-12-07 16:01:45 +00:00
|
|
|
|
2023-07-27 16:02:49 +00:00
|
|
|
import rapidjson
|
2022-12-07 16:01:45 +00:00
|
|
|
import requests
|
|
|
|
from cachetools import TTLCache
|
|
|
|
|
2022-12-12 12:24:33 +00:00
|
|
|
from freqtrade import __version__
|
2023-07-27 16:02:49 +00:00
|
|
|
from freqtrade.configuration.load_config import CONFIG_PARSE_MODE
|
2022-12-07 16:01:45 +00:00
|
|
|
from freqtrade.exceptions import OperationalException
|
|
|
|
from freqtrade.exchange.types import Tickers
|
2024-06-21 12:09:30 +00:00
|
|
|
from freqtrade.plugins.pairlist.IPairList import IPairList, PairlistParameter, SupportsBacktesting
|
2023-06-24 19:32:20 +00:00
|
|
|
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
2022-12-07 16:01:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class RemotePairList(IPairList):
|
2023-04-20 16:09:47 +00:00
|
|
|
is_pairlist_generator = True
|
2024-06-21 12:09:30 +00:00
|
|
|
# Potential winner bias
|
|
|
|
supports_backtesting = SupportsBacktesting.TODAYS_DATA
|
2023-04-20 16:09:47 +00:00
|
|
|
|
2024-06-09 06:54:48 +00:00
|
|
|
def __init__(self, *args, **kwargs) -> None:
|
|
|
|
super().__init__(*args, **kwargs)
|
2022-12-07 16:01:45 +00:00
|
|
|
|
2024-05-12 14:37:11 +00:00
|
|
|
if "number_assets" not in self._pairlistconfig:
|
2022-12-07 16:01:45 +00:00
|
|
|
raise OperationalException(
|
2024-05-12 14:37:11 +00:00
|
|
|
"`number_assets` not specified. Please check your configuration "
|
|
|
|
'for "pairlist.config.number_assets"'
|
|
|
|
)
|
2022-12-07 16:01:45 +00:00
|
|
|
|
2024-05-12 14:37:11 +00:00
|
|
|
if "pairlist_url" not in self._pairlistconfig:
|
2022-12-07 16:01:45 +00:00
|
|
|
raise OperationalException(
|
2024-05-12 14:37:11 +00:00
|
|
|
"`pairlist_url` not specified. Please check your configuration "
|
|
|
|
'for "pairlist.config.pairlist_url"'
|
|
|
|
)
|
|
|
|
|
|
|
|
self._mode = self._pairlistconfig.get("mode", "whitelist")
|
|
|
|
self._processing_mode = self._pairlistconfig.get("processing_mode", "filter")
|
|
|
|
self._number_pairs = self._pairlistconfig["number_assets"]
|
|
|
|
self._refresh_period: int = self._pairlistconfig.get("refresh_period", 1800)
|
|
|
|
self._keep_pairlist_on_failure = self._pairlistconfig.get("keep_pairlist_on_failure", True)
|
2022-12-19 14:36:28 +00:00
|
|
|
self._pair_cache: TTLCache = TTLCache(maxsize=1, ttl=self._refresh_period)
|
2024-05-12 14:37:11 +00:00
|
|
|
self._pairlist_url = self._pairlistconfig.get("pairlist_url", "")
|
|
|
|
self._read_timeout = self._pairlistconfig.get("read_timeout", 60)
|
|
|
|
self._bearer_token = self._pairlistconfig.get("bearer_token", "")
|
2022-12-18 21:28:12 +00:00
|
|
|
self._init_done = False
|
2024-05-12 14:37:11 +00:00
|
|
|
self._save_to_file = self._pairlistconfig.get("save_to_file", None)
|
2022-12-07 16:01:45 +00:00
|
|
|
self._last_pairlist: List[Any] = list()
|
|
|
|
|
2024-05-12 14:37:11 +00:00
|
|
|
if self._mode not in ["whitelist", "blacklist"]:
|
2023-06-24 12:31:30 +00:00
|
|
|
raise OperationalException(
|
2024-05-12 14:37:11 +00:00
|
|
|
"`mode` not configured correctly. Supported Modes " 'are "whitelist","blacklist"'
|
|
|
|
)
|
2023-06-24 12:31:30 +00:00
|
|
|
|
2024-05-12 14:37:11 +00:00
|
|
|
if self._processing_mode not in ["filter", "append"]:
|
2023-07-08 16:05:46 +00:00
|
|
|
raise OperationalException(
|
2024-05-12 14:37:11 +00:00
|
|
|
"`processing_mode` not configured correctly. Supported Modes "
|
|
|
|
'are "filter","append"'
|
|
|
|
)
|
2023-07-08 16:05:46 +00:00
|
|
|
|
2024-05-12 14:37:11 +00:00
|
|
|
if self._pairlist_pos == 0 and self._mode == "blacklist":
|
2023-07-08 16:05:46 +00:00
|
|
|
raise OperationalException(
|
2024-05-12 14:37:11 +00:00
|
|
|
"A `blacklist` mode RemotePairList can not be on the first "
|
|
|
|
"position of your pairlist."
|
|
|
|
)
|
2023-07-08 16:05:46 +00:00
|
|
|
|
2022-12-07 16:01:45 +00:00
|
|
|
@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
|
|
|
|
"""
|
|
|
|
return f"{self.name} - {self._pairlistconfig['number_assets']} pairs from RemotePairlist."
|
|
|
|
|
2023-05-28 16:21:23 +00:00
|
|
|
@staticmethod
|
|
|
|
def description() -> str:
|
2023-07-09 09:37:06 +00:00
|
|
|
return "Retrieve pairs from a remote API or local file."
|
2023-05-28 16:21:23 +00:00
|
|
|
|
2023-04-20 05:20:45 +00:00
|
|
|
@staticmethod
|
|
|
|
def available_parameters() -> Dict[str, PairlistParameter]:
|
|
|
|
return {
|
2023-07-09 09:09:59 +00:00
|
|
|
"pairlist_url": {
|
|
|
|
"type": "string",
|
|
|
|
"default": "",
|
|
|
|
"description": "URL to fetch pairlist from",
|
|
|
|
"help": "URL to fetch pairlist from",
|
|
|
|
},
|
|
|
|
"number_assets": {
|
|
|
|
"type": "number",
|
|
|
|
"default": 30,
|
|
|
|
"description": "Number of assets",
|
|
|
|
"help": "Number of assets to use from the pairlist.",
|
|
|
|
},
|
2023-07-08 05:31:55 +00:00
|
|
|
"mode": {
|
|
|
|
"type": "option",
|
|
|
|
"default": "whitelist",
|
|
|
|
"options": ["whitelist", "blacklist"],
|
|
|
|
"description": "Pairlist mode",
|
|
|
|
"help": "Should this pairlist operate as a whitelist or blacklist?",
|
|
|
|
},
|
2023-07-09 09:09:59 +00:00
|
|
|
"processing_mode": {
|
|
|
|
"type": "option",
|
|
|
|
"default": "filter",
|
|
|
|
"options": ["filter", "append"],
|
|
|
|
"description": "Processing mode",
|
2024-04-18 20:51:25 +00:00
|
|
|
"help": "Append pairs to incoming pairlist or filter them?",
|
2023-04-20 05:20:45 +00:00
|
|
|
},
|
|
|
|
**IPairList.refresh_period_parameter(),
|
|
|
|
"keep_pairlist_on_failure": {
|
|
|
|
"type": "boolean",
|
|
|
|
"default": True,
|
|
|
|
"description": "Keep last pairlist on failure",
|
|
|
|
"help": "Keep last pairlist on failure",
|
|
|
|
},
|
|
|
|
"read_timeout": {
|
|
|
|
"type": "number",
|
|
|
|
"default": 60,
|
|
|
|
"description": "Read timeout",
|
|
|
|
"help": "Request timeout for remote pairlist",
|
|
|
|
},
|
|
|
|
"bearer_token": {
|
|
|
|
"type": "string",
|
|
|
|
"default": "",
|
|
|
|
"description": "Bearer token",
|
|
|
|
"help": "Bearer token - used for auth against the upstream service.",
|
|
|
|
},
|
2024-01-27 07:18:18 +00:00
|
|
|
"save_to_file": {
|
|
|
|
"type": "string",
|
|
|
|
"default": "",
|
|
|
|
"description": "Filename to save processed pairlist to.",
|
|
|
|
"help": "Specify a filename to save the processed pairlist in JSON format.",
|
|
|
|
},
|
2023-04-20 05:20:45 +00:00
|
|
|
}
|
|
|
|
|
2022-12-19 14:36:28 +00:00
|
|
|
def process_json(self, jsonparse) -> List[str]:
|
2024-05-12 14:37:11 +00:00
|
|
|
pairlist = jsonparse.get("pairs", [])
|
|
|
|
remote_refresh_period = int(jsonparse.get("refresh_period", self._refresh_period))
|
2022-12-18 22:37:18 +00:00
|
|
|
|
2022-12-19 14:36:28 +00:00
|
|
|
if self._refresh_period < remote_refresh_period:
|
2024-05-12 14:37:11 +00:00
|
|
|
self.log_once(
|
|
|
|
f"Refresh Period has been increased from {self._refresh_period}"
|
|
|
|
f" to minimum allowed: {remote_refresh_period} from Remote.",
|
|
|
|
logger.info,
|
|
|
|
)
|
2022-12-18 22:37:18 +00:00
|
|
|
|
2022-12-19 14:36:28 +00:00
|
|
|
self._refresh_period = remote_refresh_period
|
|
|
|
self._pair_cache = TTLCache(maxsize=1, ttl=remote_refresh_period)
|
2022-12-19 15:25:22 +00:00
|
|
|
|
|
|
|
self._init_done = True
|
2022-12-18 22:37:18 +00:00
|
|
|
|
2022-12-19 14:36:28 +00:00
|
|
|
return pairlist
|
2022-12-18 22:37:18 +00:00
|
|
|
|
2022-12-18 21:28:12 +00:00
|
|
|
def return_last_pairlist(self) -> List[str]:
|
|
|
|
if self._keep_pairlist_on_failure:
|
|
|
|
pairlist = self._last_pairlist
|
2024-05-12 14:37:11 +00:00
|
|
|
self.log_once("Keeping last fetched pairlist", logger.info)
|
2022-12-18 21:28:12 +00:00
|
|
|
else:
|
|
|
|
pairlist = []
|
|
|
|
|
|
|
|
return pairlist
|
|
|
|
|
2022-12-19 14:36:28 +00:00
|
|
|
def fetch_pairlist(self) -> Tuple[List[str], float]:
|
2024-05-12 14:37:11 +00:00
|
|
|
headers = {"User-Agent": "Freqtrade/" + __version__ + " Remotepairlist"}
|
2022-12-07 16:47:38 +00:00
|
|
|
|
2022-12-12 12:24:33 +00:00
|
|
|
if self._bearer_token:
|
2024-05-12 14:37:11 +00:00
|
|
|
headers["Authorization"] = f"Bearer {self._bearer_token}"
|
2022-12-12 12:24:33 +00:00
|
|
|
|
2022-12-07 16:47:38 +00:00
|
|
|
try:
|
2024-05-12 14:37:11 +00:00
|
|
|
response = requests.get(self._pairlist_url, headers=headers, timeout=self._read_timeout)
|
|
|
|
content_type = response.headers.get("content-type")
|
2022-12-13 19:21:06 +00:00
|
|
|
time_elapsed = response.elapsed.total_seconds()
|
|
|
|
|
|
|
|
if "application/json" in str(content_type):
|
|
|
|
jsonparse = response.json()
|
2022-12-19 14:36:28 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
pairlist = self.process_json(jsonparse)
|
|
|
|
except Exception as e:
|
2024-05-12 14:37:11 +00:00
|
|
|
pairlist = self._handle_error(f"Failed processing JSON data: {type(e)}")
|
2022-12-13 19:21:06 +00:00
|
|
|
else:
|
2024-05-12 14:37:11 +00:00
|
|
|
pairlist = self._handle_error(
|
2024-05-12 15:51:21 +00:00
|
|
|
f"RemotePairList is not of type JSON. {self._pairlist_url}"
|
2024-05-12 14:37:11 +00:00
|
|
|
)
|
2022-12-07 16:47:38 +00:00
|
|
|
|
|
|
|
except requests.exceptions.RequestException:
|
2024-05-12 14:37:11 +00:00
|
|
|
pairlist = self._handle_error(
|
2024-05-12 15:51:21 +00:00
|
|
|
f"Was not able to fetch pairlist from: {self._pairlist_url}"
|
2024-05-12 14:37:11 +00:00
|
|
|
)
|
2022-12-07 16:47:38 +00:00
|
|
|
|
|
|
|
time_elapsed = 0
|
|
|
|
|
2022-12-19 14:36:28 +00:00
|
|
|
return pairlist, time_elapsed
|
2022-12-07 16:47:38 +00:00
|
|
|
|
2024-01-27 07:15:05 +00:00
|
|
|
def _handle_error(self, error: str) -> List[str]:
|
2024-01-26 17:32:46 +00:00
|
|
|
if self._init_done:
|
|
|
|
self.log_once("Error: " + error, logger.info)
|
2024-01-27 07:15:05 +00:00
|
|
|
return self.return_last_pairlist()
|
2024-01-26 17:32:46 +00:00
|
|
|
else:
|
|
|
|
raise OperationalException(error)
|
|
|
|
|
2022-12-07 16:01:45 +00:00
|
|
|
def gen_pairlist(self, tickers: Tickers) -> List[str]:
|
|
|
|
"""
|
|
|
|
Generate the pairlist
|
|
|
|
:param tickers: Tickers (from exchange.get_tickers). May be cached.
|
|
|
|
:return: List of pairs
|
|
|
|
"""
|
2022-12-07 23:52:54 +00:00
|
|
|
|
2022-12-19 14:36:28 +00:00
|
|
|
if self._init_done:
|
2024-05-12 14:37:11 +00:00
|
|
|
pairlist = self._pair_cache.get("pairlist")
|
2023-04-13 16:19:52 +00:00
|
|
|
if pairlist == [None]:
|
|
|
|
# Valid but empty pairlist.
|
2023-04-12 17:32:28 +00:00
|
|
|
return []
|
2022-12-18 21:28:12 +00:00
|
|
|
else:
|
|
|
|
pairlist = []
|
|
|
|
|
2022-12-12 10:05:03 +00:00
|
|
|
time_elapsed = 0.0
|
2022-12-07 16:01:45 +00:00
|
|
|
|
|
|
|
if pairlist:
|
|
|
|
# Item found - no refresh necessary
|
|
|
|
return pairlist.copy()
|
|
|
|
else:
|
2022-12-07 23:52:54 +00:00
|
|
|
if self._pairlist_url.startswith("file:///"):
|
|
|
|
filename = self._pairlist_url.split("file:///", 1)[1]
|
|
|
|
file_path = Path(filename)
|
|
|
|
|
|
|
|
if file_path.exists():
|
2023-02-25 16:08:02 +00:00
|
|
|
with file_path.open() as json_file:
|
2022-12-19 14:36:28 +00:00
|
|
|
try:
|
2024-01-26 15:46:54 +00:00
|
|
|
# Load the JSON data into a dictionary
|
|
|
|
jsonparse = rapidjson.load(json_file, parse_mode=CONFIG_PARSE_MODE)
|
2022-12-19 14:36:28 +00:00
|
|
|
pairlist = self.process_json(jsonparse)
|
|
|
|
except Exception as e:
|
2024-05-12 14:37:11 +00:00
|
|
|
pairlist = self._handle_error(f"processing JSON data: {type(e)}")
|
2022-12-07 16:01:45 +00:00
|
|
|
else:
|
2024-01-27 07:15:05 +00:00
|
|
|
pairlist = self._handle_error(f"{self._pairlist_url} does not exist.")
|
2024-01-26 17:32:46 +00:00
|
|
|
|
2022-12-07 23:52:54 +00:00
|
|
|
else:
|
|
|
|
# Fetch Pairlist from Remote URL
|
2022-12-19 14:36:28 +00:00
|
|
|
pairlist, time_elapsed = self.fetch_pairlist()
|
2022-12-07 16:01:45 +00:00
|
|
|
|
2022-12-18 21:28:12 +00:00
|
|
|
self.log_once(f"Fetched pairs: {pairlist}", logger.debug)
|
|
|
|
|
2023-06-24 19:32:20 +00:00
|
|
|
pairlist = expand_pairlist(pairlist, list(self._exchange.get_markets().keys()))
|
2022-12-18 21:28:12 +00:00
|
|
|
pairlist = self._whitelist_for_active_markets(pairlist)
|
2024-05-12 14:37:11 +00:00
|
|
|
pairlist = pairlist[: self._number_pairs]
|
2022-12-18 21:28:12 +00:00
|
|
|
|
2023-04-12 11:16:53 +00:00
|
|
|
if pairlist:
|
2024-05-12 14:37:11 +00:00
|
|
|
self._pair_cache["pairlist"] = pairlist.copy()
|
2023-04-12 11:16:53 +00:00
|
|
|
else:
|
2023-04-13 16:19:52 +00:00
|
|
|
# If pairlist is empty, set a dummy value to avoid fetching again
|
2024-05-12 14:37:11 +00:00
|
|
|
self._pair_cache["pairlist"] = [None]
|
2022-12-07 16:01:45 +00:00
|
|
|
|
2022-12-12 10:05:03 +00:00
|
|
|
if time_elapsed != 0.0:
|
2024-05-12 14:37:11 +00:00
|
|
|
self.log_once(f"Pairlist Fetched in {time_elapsed} seconds.", logger.info)
|
2022-12-08 00:09:17 +00:00
|
|
|
else:
|
2024-05-12 14:37:11 +00:00
|
|
|
self.log_once("Fetched Pairlist.", logger.info)
|
2022-12-07 16:01:45 +00:00
|
|
|
|
|
|
|
self._last_pairlist = list(pairlist)
|
2022-12-18 21:28:12 +00:00
|
|
|
|
2024-01-26 15:46:54 +00:00
|
|
|
if self._save_to_file:
|
|
|
|
self.save_pairlist(pairlist, self._save_to_file)
|
|
|
|
|
2022-12-07 16:01:45 +00:00
|
|
|
return pairlist
|
|
|
|
|
2024-01-26 15:46:54 +00:00
|
|
|
def save_pairlist(self, pairlist: List[str], filename: str) -> None:
|
2024-05-12 14:37:11 +00:00
|
|
|
pairlist_data = {"pairs": pairlist}
|
2024-01-26 15:46:54 +00:00
|
|
|
try:
|
|
|
|
file_path = Path(filename)
|
2024-05-12 14:37:11 +00:00
|
|
|
with file_path.open("w") as json_file:
|
2024-01-26 15:46:54 +00:00
|
|
|
rapidjson.dump(pairlist_data, json_file)
|
|
|
|
logger.info(f"Processed pairlist saved to {filename}")
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Error saving processed pairlist to {filename}: {e}")
|
|
|
|
|
2022-12-07 16:01:45 +00:00
|
|
|
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
|
|
|
|
"""
|
2022-12-18 21:28:12 +00:00
|
|
|
rpl_pairlist = self.gen_pairlist(tickers)
|
2023-06-24 10:38:31 +00:00
|
|
|
merged_list = []
|
|
|
|
filtered = []
|
|
|
|
|
|
|
|
if self._mode == "whitelist":
|
2023-07-08 16:05:46 +00:00
|
|
|
if self._processing_mode == "filter":
|
|
|
|
merged_list = [pair for pair in pairlist if pair in rpl_pairlist]
|
|
|
|
elif self._processing_mode == "append":
|
|
|
|
merged_list = pairlist + rpl_pairlist
|
2023-06-24 10:38:31 +00:00
|
|
|
merged_list = sorted(set(merged_list), key=merged_list.index)
|
2023-06-24 12:31:30 +00:00
|
|
|
else:
|
2023-06-24 10:38:31 +00:00
|
|
|
for pair in pairlist:
|
|
|
|
if pair not in rpl_pairlist:
|
|
|
|
merged_list.append(pair)
|
|
|
|
else:
|
|
|
|
filtered.append(pair)
|
|
|
|
if filtered:
|
|
|
|
self.log_once(f"Blacklist - Filtered out pairs: {filtered}", logger.info)
|
|
|
|
|
2024-05-12 14:37:11 +00:00
|
|
|
merged_list = merged_list[: self._number_pairs]
|
2022-12-18 21:28:12 +00:00
|
|
|
return merged_list
|