| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Simple command line client into RPC commands |
| 4 | Can be used as an alternate to Telegram |
| 5 | |
| 6 | Should not import anything from freqtrade, |
| 7 | so it can be used as a standalone script. |
| 8 | """ |
| 9 | |
| 10 | import argparse |
| 11 | import inspect |
| 12 | import json |
| 13 | import logging |
| 14 | import re |
| 15 | import sys |
| 16 | from pathlib import Path |
| 17 | from urllib.parse import urlencode, urlparse, urlunparse |
| 18 | |
| 19 | import rapidjson |
| 20 | import requests |
| 21 | from requests.exceptions import ConnectionError |
| 22 | |
| 23 | |
| 24 | logging.basicConfig( |
| 25 | level=logging.INFO, |
| 26 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
| 27 | ) |
| 28 | logger = logging.getLogger("ft_rest_client") |
| 29 | |
| 30 | |
| 31 | class FtRestClient(): |
| 32 | |
| 33 | def __init__(self, serverurl, username=None, password=None): |
| 34 | |
| 35 | self._serverurl = serverurl |
| 36 | self._session = requests.Session() |
| 37 | self._session.auth = (username, password) |
| 38 | |
| 39 | def _call(self, method, apipath, params: dict = None, data=None, files=None): |
| 40 | |
| 41 | if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'): |
| 42 | raise ValueError('invalid method <{0}>'.format(method)) |
| 43 | basepath = f"{self._serverurl}/api/v1/{apipath}" |
| 44 | |
| 45 | hd = {"Accept": "application/json", |
| 46 | "Content-Type": "application/json" |
| 47 | } |
| 48 | |
| 49 | # Split url |
| 50 | schema, netloc, path, par, query, fragment = urlparse(basepath) |
| 51 | # URLEncode query string |
| 52 | query = urlencode(params) if params else "" |
| 53 | # recombine url |
| 54 | url = urlunparse((schema, netloc, path, par, query, fragment)) |
| 55 | |
| 56 | try: |
| 57 | resp = self._session.request(method, url, headers=hd, data=json.dumps(data)) |
| 58 | # return resp.text |
| 59 | return resp.json() |
| 60 | except ConnectionError: |
| 61 | logger.warning("Connection error") |
| 62 | |
| 63 | def _get(self, apipath, params: dict = None): |
| 64 | return self._call("GET", apipath, params=params) |
| 65 | |
| 66 | def _delete(self, apipath, params: dict = None): |
| 67 | return self._call("DELETE", apipath, params=params) |
| 68 | |
| 69 | def _post(self, apipath, params: dict = None, data: dict = None): |
| 70 | return self._call("POST", apipath, params=params, data=data) |
| 71 | |
| 72 | def start(self): |
| 73 | """Start the bot if it's in the stopped state. |
| 74 | |
| 75 | :return: json object |
| 76 | """ |
| 77 | return self._post("start") |
| 78 | |
| 79 | def stop(self): |
| 80 | """Stop the bot. Use `start` to restart. |
| 81 | |
| 82 | :return: json object |
| 83 | """ |
| 84 | return self._post("stop") |
| 85 | |
| 86 | def stopbuy(self): |
| 87 | """Stop buying (but handle sells gracefully). Use `reload_config` to reset. |
| 88 | |
| 89 | :return: json object |
| 90 | """ |
| 91 | return self._post("stopbuy") |
| 92 | |
| 93 | def reload_config(self): |
| 94 | """Reload configuration. |
| 95 | |
| 96 | :return: json object |
| 97 | """ |
| 98 | return self._post("reload_config") |
| 99 | |
| 100 | def balance(self): |
| 101 | """Get the account balance. |
| 102 | |
| 103 | :return: json object |
| 104 | """ |
| 105 | return self._get("balance") |
| 106 | |
| 107 | def count(self): |
| 108 | """Return the amount of open trades. |
| 109 | |
| 110 | :return: json object |
| 111 | """ |
| 112 | return self._get("count") |
| 113 | |
| 114 | def locks(self): |
| 115 | """Return current locks |
| 116 | |
| 117 | :return: json object |
| 118 | """ |
| 119 | return self._get("locks") |
| 120 | |
| 121 | def delete_lock(self, lock_id): |
| 122 | """Delete (disable) lock from the database. |
| 123 | |
| 124 | :param lock_id: ID for the lock to delete |
| 125 | :return: json object |
| 126 | """ |
| 127 | return self._delete("locks/{}".format(lock_id)) |
| 128 | |
| 129 | def daily(self, days=None): |
| 130 | """Return the profits for each day, and amount of trades. |
| 131 | |
| 132 | :return: json object |
| 133 | """ |
| 134 | return self._get("daily", params={"timescale": days} if days else None) |
| 135 | |
| 136 | def edge(self): |
| 137 | """Return information about edge. |
| 138 | |
| 139 | :return: json object |
| 140 | """ |
| 141 | return self._get("edge") |
| 142 | |
| 143 | def profit(self): |
| 144 | """Return the profit summary. |
| 145 | |
| 146 | :return: json object |
| 147 | """ |
| 148 | return self._get("profit") |
| 149 | |
| 150 | def stats(self): |
| 151 | """Return the stats report (durations, sell-reasons). |
| 152 | |
| 153 | :return: json object |
| 154 | """ |
| 155 | return self._get("stats") |
| 156 | |
| 157 | def performance(self): |
| 158 | """Return the performance of the different coins. |
| 159 | |
| 160 | :return: json object |
| 161 | """ |
| 162 | return self._get("performance") |
| 163 | |
| 164 | def status(self): |
| 165 | """Get the status of open trades. |
| 166 | |
| 167 | :return: json object |
| 168 | """ |
| 169 | return self._get("status") |
| 170 | |
| 171 | def version(self): |
| 172 | """Return the version of the bot. |
| 173 | |
| 174 | :return: json object containing the version |
| 175 | """ |
| 176 | return self._get("version") |
| 177 | |
| 178 | def show_config(self): |
| 179 | """ |
| 180 | Returns part of the configuration, relevant for trading operations. |
| 181 | :return: json object containing the version |
| 182 | """ |
| 183 | return self._get("show_config") |
| 184 | |
| 185 | def ping(self): |
| 186 | """simple ping""" |
| 187 | configstatus = self.show_config() |
| 188 | if not configstatus: |
| 189 | return {"status": "not_running"} |
| 190 | elif configstatus['state'] == "running": |
| 191 | return {"status": "pong"} |
| 192 | else: |
| 193 | return {"status": "not_running"} |
| 194 | |
| 195 | def logs(self, limit=None): |
| 196 | """Show latest logs. |
| 197 | |
| 198 | :param limit: Limits log messages to the last <limit> logs. No limit to get the entire log. |
| 199 | :return: json object |
| 200 | """ |
| 201 | return self._get("logs", params={"limit": limit} if limit else 0) |
| 202 | |
| 203 | def trades(self, limit=None): |
| 204 | """Return trades history. |
| 205 | |
| 206 | :param limit: Limits trades to the X last trades. No limit to get all the trades. |
| 207 | :return: json object |
| 208 | """ |
| 209 | return self._get("trades", params={"limit": limit} if limit else 0) |
| 210 | |
| 211 | def trade(self, trade_id): |
| 212 | """Return specific trade |
| 213 | |
| 214 | :param trade_id: Specify which trade to get. |
| 215 | :return: json object |
| 216 | """ |
| 217 | return self._get("trade/{}".format(trade_id)) |
| 218 | |
| 219 | def delete_trade(self, trade_id): |
| 220 | """Delete trade from the database. |
| 221 | Tries to close open orders. Requires manual handling of this asset on the exchange. |
| 222 | |
| 223 | :param trade_id: Deletes the trade with this ID from the database. |
| 224 | :return: json object |
| 225 | """ |
| 226 | return self._delete("trades/{}".format(trade_id)) |
| 227 | |
| 228 | def whitelist(self): |
| 229 | """Show the current whitelist. |
| 230 | |
| 231 | :return: json object |
| 232 | """ |
| 233 | return self._get("whitelist") |
| 234 | |
| 235 | def blacklist(self, *args): |
| 236 | """Show the current blacklist. |
| 237 | |
| 238 | :param add: List of coins to add (example: "BNB/BTC") |
| 239 | :return: json object |
| 240 | """ |
| 241 | if not args: |
| 242 | return self._get("blacklist") |
| 243 | else: |
| 244 | return self._post("blacklist", data={"blacklist": args}) |
| 245 | |
| 246 | def forcebuy(self, pair, price=None): |
| 247 | """Buy an asset. |
| 248 | |
| 249 | :param pair: Pair to buy (ETH/BTC) |
| 250 | :param price: Optional - price to buy |
| 251 | :return: json object of the trade |
| 252 | """ |
| 253 | data = {"pair": pair, |
| 254 | "price": price |
| 255 | } |
| 256 | return self._post("forcebuy", data=data) |
| 257 | |
| 258 | def forcesell(self, tradeid): |
| 259 | """Force-sell a trade. |
| 260 | |
| 261 | :param tradeid: Id of the trade (can be received via status command) |
| 262 | :return: json object |
| 263 | """ |
| 264 | |
| 265 | return self._post("forcesell", data={"tradeid": tradeid}) |
| 266 | |
| 267 | def strategies(self): |
| 268 | """Lists available strategies |
| 269 | |
| 270 | :return: json object |
| 271 | """ |
| 272 | return self._get("strategies") |
| 273 | |
| 274 | def strategy(self, strategy): |
| 275 | """Get strategy details |
| 276 | |
| 277 | :param strategy: Strategy class name |
| 278 | :return: json object |
| 279 | """ |
| 280 | return self._get(f"strategy/{strategy}") |
| 281 | |
| 282 | def plot_config(self): |
| 283 | """Return plot configuration if the strategy defines one. |
| 284 | |
| 285 | :return: json object |
| 286 | """ |
| 287 | return self._get("plot_config") |
| 288 | |
| 289 | def available_pairs(self, timeframe=None, stake_currency=None): |
| 290 | """Return available pair (backtest data) based on timeframe / stake_currency selection |
| 291 | |
| 292 | :param timeframe: Only pairs with this timeframe available. |
| 293 | :param stake_currency: Only pairs that include this timeframe |
| 294 | :return: json object |
| 295 | """ |
| 296 | return self._get("available_pairs", params={ |
| 297 | "stake_currency": stake_currency if timeframe else '', |
| 298 | "timeframe": timeframe if timeframe else '', |
| 299 | }) |
| 300 | |
| 301 | def pair_candles(self, pair, timeframe, limit=None): |
| 302 | """Return live dataframe for <pair><timeframe>. |
| 303 | |
| 304 | :param pair: Pair to get data for |
| 305 | :param timeframe: Only pairs with this timeframe available. |
| 306 | :param limit: Limit result to the last n candles. |
| 307 | :return: json object |
| 308 | """ |
| 309 | return self._get("available_pairs", params={ |
| 310 | "pair": pair, |
| 311 | "timeframe": timeframe, |
| 312 | "limit": limit, |
| 313 | }) |
| 314 | |
| 315 | def pair_history(self, pair, timeframe, strategy, timerange=None): |
| 316 | """Return historic, analyzed dataframe |
| 317 | |
| 318 | :param pair: Pair to get data for |
| 319 | :param timeframe: Only pairs with this timeframe available. |
| 320 | :param strategy: Strategy to analyze and get values for |
| 321 | :param timerange: Timerange to get data for (same format than --timerange endpoints) |
| 322 | :return: json object |
| 323 | """ |
| 324 | return self._get("pair_history", params={ |
| 325 | "pair": pair, |
| 326 | "timeframe": timeframe, |
| 327 | "strategy": strategy, |
| 328 | "timerange": timerange if timerange else '', |
| 329 | }) |
| 330 | |
| 331 | |
| 332 | def add_arguments(): |
| 333 | parser = argparse.ArgumentParser() |
| 334 | parser.add_argument("command", |
| 335 | help="Positional argument defining the command to execute.", |
| 336 | nargs="?" |
| 337 | ) |
| 338 | |
| 339 | parser.add_argument('--show', |
| 340 | help='Show possible methods with this client', |
| 341 | dest='show', |
| 342 | action='store_true', |
| 343 | default=False |
| 344 | ) |
| 345 | |
| 346 | parser.add_argument('-c', '--config', |
| 347 | help='Specify configuration file (default: %(default)s). ', |
| 348 | dest='config', |
| 349 | type=str, |
| 350 | metavar='PATH', |
| 351 | default='config.json' |
| 352 | ) |
| 353 | |
| 354 | parser.add_argument("command_arguments", |
| 355 | help="Positional arguments for the parameters for [command]", |
| 356 | nargs="*", |
| 357 | default=[] |
| 358 | ) |
| 359 | |
| 360 | args = parser.parse_args() |
| 361 | return vars(args) |
| 362 | |
| 363 | |
| 364 | def load_config(configfile): |
| 365 | file = Path(configfile) |
| 366 | if file.is_file(): |
| 367 | with file.open("r") as f: |
| 368 | config = rapidjson.load(f, parse_mode=rapidjson.PM_COMMENTS | |
| 369 | rapidjson.PM_TRAILING_COMMAS) |
| 370 | return config |
| 371 | else: |
| 372 | logger.warning(f"Could not load config file {file}.") |
| 373 | sys.exit(1) |
| 374 | |
| 375 | |
| 376 | def print_commands(): |
| 377 | # Print dynamic help for the different commands using the commands doc-strings |
| 378 | client = FtRestClient(None) |
| 379 | print("Possible commands:\n") |
| 380 | for x, y in inspect.getmembers(client): |
| 381 | if not x.startswith('_'): |
| 382 | doc = re.sub(':return:.*', '', getattr(client, x).__doc__, flags=re.MULTILINE).rstrip() |
| 383 | print(f"{x}\n\t{doc}\n") |
| 384 | |
| 385 | |
| 386 | def main(args): |
| 387 | |
| 388 | if args.get("show"): |
| 389 | print_commands() |
| 390 | sys.exit() |
| 391 | |
| 392 | config = load_config(args['config']) |
| 393 | url = config.get('api_server', {}).get('server_url', '127.0.0.1') |
| 394 | port = config.get('api_server', {}).get('listen_port', '8080') |
| 395 | username = config.get('api_server', {}).get('username') |
| 396 | password = config.get('api_server', {}).get('password') |
| 397 | |
| 398 | server_url = f"http://{url}:{port}" |
| 399 | client = FtRestClient(server_url, username, password) |
| 400 | |
| 401 | m = [x for x, y in inspect.getmembers(client) if not x.startswith('_')] |
| 402 | command = args["command"] |
| 403 | if command not in m: |
| 404 | logger.error(f"Command {command} not defined") |
| 405 | print_commands() |
| 406 | return |
| 407 | |
| 408 | print(json.dumps(getattr(client, command)(*args["command_arguments"]))) |
| 409 | |
| 410 | |
| 411 | if __name__ == "__main__": |
| 412 | args = add_arguments() |
| 413 | main(args) |