From c3c745ca19f0bb2885bae9fa1858c731564498a4 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 07:08:24 +0200 Subject: [PATCH 01/71] Get new files from old branch --- freqtrade/rpc/api_server.py | 203 +++++++++++++++++++++++++++++ freqtrade/rpc/api_server_common.py | 74 +++++++++++ freqtrade/rpc/rest_client.py | 47 +++++++ 3 files changed, 324 insertions(+) create mode 100644 freqtrade/rpc/api_server.py create mode 100644 freqtrade/rpc/api_server_common.py create mode 100755 freqtrade/rpc/rest_client.py diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py new file mode 100644 index 000000000..1055a0553 --- /dev/null +++ b/freqtrade/rpc/api_server.py @@ -0,0 +1,203 @@ +import json +import threading +import logging +# import json +from typing import Dict + +from flask import Flask, request +# from flask_restful import Resource, Api +from freqtrade.rpc.rpc import RPC, RPCException +from ipaddress import IPv4Address + + +logger = logging.getLogger(__name__) +app = Flask(__name__) + + +class ApiServer(RPC): + """ + This class runs api server and provides rpc.rpc functionality to it + + This class starts a none blocking thread the api server runs within + """ + + def __init__(self, freqtrade) -> None: + """ + Init the api server, and init the super class RPC + :param freqtrade: Instance of a freqtrade bot + :return: None + """ + super().__init__(freqtrade) + + self._config = freqtrade.config + + # Register application handling + self.register_rest_other() + self.register_rest_rpc_urls() + + thread = threading.Thread(target=self.run, daemon=True) + thread.start() + + def register_rest_other(self): + """ + Registers flask app URLs that are not calls to functionality in rpc.rpc. + :return: + """ + app.register_error_handler(404, self.page_not_found) + app.add_url_rule('/', 'hello', view_func=self.hello, methods=['GET']) + + def register_rest_rpc_urls(self): + """ + Registers flask app URLs that are calls to functonality in rpc.rpc. + + First two arguments passed are /URL and 'Label' + Label can be used as a shortcut when refactoring + :return: + """ + app.add_url_rule('/stop', 'stop', view_func=self.stop, methods=['GET']) + app.add_url_rule('/start', 'start', view_func=self.start, methods=['GET']) + app.add_url_rule('/daily', 'daily', view_func=self.daily, methods=['GET']) + app.add_url_rule('/profit', 'profit', view_func=self.profit, methods=['GET']) + app.add_url_rule('/status_table', 'status_table', + view_func=self.status_table, methods=['GET']) + + def run(self): + """ Method that runs flask app in its own thread forever """ + + """ + Section to handle configuration and running of the Rest server + also to check and warn if not bound to a loopback, warn on security risk. + """ + rest_ip = self._config['api_server']['listen_ip_address'] + rest_port = self._config['api_server']['listen_port'] + + logger.info('Starting HTTP Server at {}:{}'.format(rest_ip, rest_port)) + if not IPv4Address(rest_ip).is_loopback: + logger.info("SECURITY WARNING - Local Rest Server listening to external connections") + logger.info("SECURITY WARNING - This is insecure please set to your loopback," + "e.g 127.0.0.1 in config.json") + + # Run the Server + logger.info('Starting Local Rest Server') + try: + app.run(host=rest_ip, port=rest_port) + except Exception: + logger.exception("Api server failed to start, exception message is:") + + def cleanup(self) -> None: + pass + + def send_msg(self, msg: Dict[str, str]) -> None: + pass + + """ + Define the application methods here, called by app.add_url_rule + each Telegram command should have a like local substitute + """ + + def page_not_found(self, error): + """ + Return "404 not found", 404. + """ + return json.dumps({ + 'status': 'error', + 'reason': '''There's no API call for %s''' % request.base_url, + 'code': 404 + }), 404 + + def hello(self): + """ + None critical but helpful default index page. + + That lists URLs added to the flask server. + This may be deprecated at any time. + :return: index.html + """ + rest_cmds = 'Commands implemented:
' \ + 'Show 7 days of stats' \ + '
' \ + 'Stop the Trade thread' \ + '
' \ + 'Start the Traded thread' \ + '
' \ + 'Show profit summary' \ + '
' \ + 'Show status table - Open trades' \ + '
' \ + ' 404 page does not exist' \ + '
' + + return rest_cmds + + def daily(self): + """ + Returns the last X days trading stats summary. + + :return: stats + """ + try: + timescale = request.args.get('timescale') + logger.info("LocalRPC - Daily Command Called") + timescale = int(timescale) + + stats = self._rpc_daily_profit(timescale, + self._config['stake_currency'], + self._config['fiat_display_currency'] + ) + + return json.dumps(stats, indent=4, sort_keys=True, default=str) + except RPCException as e: + logger.exception("API Error querying daily:", e) + return "Error querying daily" + + def profit(self): + """ + Handler for /profit. + + Returns a cumulative profit statistics + :return: stats + """ + try: + logger.info("LocalRPC - Profit Command Called") + + stats = self._rpc_trade_statistics(self._config['stake_currency'], + self._config['fiat_display_currency'] + ) + + return json.dumps(stats, indent=4, sort_keys=True, default=str) + except RPCException as e: + logger.exception("API Error calling profit", e) + return "Error querying closed trades - maybe there are none" + + def status_table(self): + """ + Handler for /status table. + + Returns the current TradeThread status in table format + :return: results + """ + try: + results = self._rpc_trade_status() + return json.dumps(results, indent=4, sort_keys=True, default=str) + + except RPCException as e: + logger.exception("API Error calling status table", e) + return "Error querying open trades - maybe there are none." + + def start(self): + """ + Handler for /start. + + Starts TradeThread in bot if stopped. + """ + msg = self._rpc_start() + return json.dumps(msg) + + def stop(self): + """ + Handler for /stop. + + Stops TradeThread in bot if running + """ + msg = self._rpc_stop() + return json.dumps(msg) diff --git a/freqtrade/rpc/api_server_common.py b/freqtrade/rpc/api_server_common.py new file mode 100644 index 000000000..19338a825 --- /dev/null +++ b/freqtrade/rpc/api_server_common.py @@ -0,0 +1,74 @@ +import logging +import flask +from flask import request, jsonify + +logger = logging.getLogger(__name__) + + +class MyApiApp(flask.Flask): + def __init__(self, import_name): + """ + Contains common rest routes and resource that do not need + to access to rpc.rpc functionality + """ + super(MyApiApp, self).__init__(import_name) + + """ + Registers flask app URLs that are not calls to functionality in rpc.rpc. + :return: + """ + self.before_request(self.my_preprocessing) + self.register_error_handler(404, self.page_not_found) + self.add_url_rule('/', 'hello', view_func=self.hello, methods=['GET']) + self.add_url_rule('/stop_api', 'stop_api', view_func=self.stop_api, methods=['GET']) + + def my_preprocessing(self): + # Do stuff to flask.request + pass + + def page_not_found(self, error): + # Return "404 not found", 404. + return jsonify({'status': 'error', + 'reason': '''There's no API call for %s''' % request.base_url, + 'code': 404}), 404 + + def hello(self): + """ + None critical but helpful default index page. + + That lists URLs added to the flask server. + This may be deprecated at any time. + :return: index.html + """ + rest_cmds = 'Commands implemented:
' \ + 'Show 7 days of stats' \ + '
' \ + 'Stop the Trade thread' \ + '
' \ + 'Start the Traded thread' \ + '
' \ + ' 404 page does not exist' \ + '
' \ + '
' \ + 'Shut down the api server - be sure' + return rest_cmds + + def stop_api(self): + """ For calling shutdown_api_server over via api server HTTP""" + self.shutdown_api_server() + return 'Api Server shutting down... ' + + def shutdown_api_server(self): + """ + Stop the running flask application + + Records the shutdown in logger.info + :return: + """ + func = request.environ.get('werkzeug.server.shutdown') + if func is None: + raise RuntimeError('Not running the Flask Werkzeug Server') + if func is not None: + logger.info('Stopping the Local Rest Server') + func() + return diff --git a/freqtrade/rpc/rest_client.py b/freqtrade/rpc/rest_client.py new file mode 100755 index 000000000..cabedebb8 --- /dev/null +++ b/freqtrade/rpc/rest_client.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +""" +Simple command line client into RPC commands +Can be used as an alternate to Telegram +""" + +import time +from requests import get +from sys import argv + +# TODO - use argparse to clean this up +# TODO - use IP and Port from config.json not hardcode + +if len(argv) == 1: + print('\nThis script accepts the following arguments') + print('- daily (int) - Where int is the number of days to report back. daily 3') + print('- start - this will start the trading thread') + print('- stop - this will start the trading thread') + print('- there will be more....\n') + +if len(argv) == 3 and argv[1] == "daily": + if str.isnumeric(argv[2]): + get_url = 'http://localhost:5002/daily?timescale=' + argv[2] + d = get(get_url).json() + print(d) + else: + print("\nThe second argument to daily must be an integer, 1,2,3 etc") + +if len(argv) == 2 and argv[1] == "start": + get_url = 'http://localhost:5002/start' + d = get(get_url).text + print(d) + + if "already" not in d: + time.sleep(2) + d = get(get_url).text + print(d) + +if len(argv) == 2 and argv[1] == "stop": + get_url = 'http://localhost:5002/stop' + d = get(get_url).text + print(d) + + if "already" not in d: + time.sleep(2) + d = get(get_url).text + print(d) From 26c42bd5590e70356e59963425c990cf0c379198 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 07:12:58 +0200 Subject: [PATCH 02/71] Add apiserver tests --- freqtrade/tests/rpc/test_rpc_apiserver.py | 52 +++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 freqtrade/tests/rpc/test_rpc_apiserver.py diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py new file mode 100644 index 000000000..14c35a38e --- /dev/null +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -0,0 +1,52 @@ +""" +Unit test file for rpc/api_server.py +""" + +from unittest.mock import MagicMock + +from freqtrade.rpc.api_server import ApiServer +from freqtrade.state import State +from freqtrade.tests.conftest import get_patched_freqtradebot, patch_apiserver + + +def test__init__(default_conf, mocker): + """ + Test __init__() method + """ + mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) + mocker.patch('freqtrade.rpc.api_server.ApiServer.run', MagicMock()) + + apiserver = ApiServer(get_patched_freqtradebot(mocker, default_conf)) + assert apiserver._config == default_conf + + +def test_start_endpoint(default_conf, mocker): + """Test /start endpoint""" + patch_apiserver(mocker) + bot = get_patched_freqtradebot(mocker, default_conf) + apiserver = ApiServer(bot) + + bot.state = State.STOPPED + assert bot.state == State.STOPPED + result = apiserver.start() + assert result == '{"status": "starting trader ..."}' + assert bot.state == State.RUNNING + + result = apiserver.start() + assert result == '{"status": "already running"}' + + +def test_stop_endpoint(default_conf, mocker): + """Test /stop endpoint""" + patch_apiserver(mocker) + bot = get_patched_freqtradebot(mocker, default_conf) + apiserver = ApiServer(bot) + + bot.state = State.RUNNING + assert bot.state == State.RUNNING + result = apiserver.stop() + assert result == '{"status": "stopping trader ..."}' + assert bot.state == State.STOPPED + + result = apiserver.stop() + assert result == '{"status": "already stopped"}' From 6f67ea44dce5e81b3ebf3cd5e29f3d5e82459725 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 07:13:14 +0200 Subject: [PATCH 03/71] Enable config-check for rest server --- freqtrade/constants.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 619508e73..1b06eb726 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -156,6 +156,19 @@ CONF_SCHEMA = { 'webhookstatus': {'type': 'object'}, }, }, + 'api_server': { + 'type': 'object', + 'properties': { + 'enabled': {'type': 'boolean'}, + 'listen_ip_address': {'format': 'ipv4'}, + 'listen_port': { + 'type': 'integer', + "minimum": 1024, + "maximum": 65535 + }, + }, + 'required': ['enabled', 'listen_ip_address', 'listen_port'] + }, 'db_url': {'type': 'string'}, 'initial_state': {'type': 'string', 'enum': ['running', 'stopped']}, 'forcebuy_enable': {'type': 'boolean'}, From ef2950bca2210dd2873534d62ba02a19b89f9b63 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 07:13:40 +0200 Subject: [PATCH 04/71] Load api-server in rpc_manager --- freqtrade/rpc/rpc.py | 5 +++++ freqtrade/rpc/rpc_manager.py | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 2189a0d17..5b78c8356 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -48,6 +48,11 @@ class RPCException(Exception): def __str__(self): return self.message + def __json__(self): + return { + 'msg': self.message + } + class RPC(object): """ diff --git a/freqtrade/rpc/rpc_manager.py b/freqtrade/rpc/rpc_manager.py index 7f0d0a5d4..fad532aa0 100644 --- a/freqtrade/rpc/rpc_manager.py +++ b/freqtrade/rpc/rpc_manager.py @@ -29,6 +29,12 @@ class RPCManager(object): from freqtrade.rpc.webhook import Webhook self.registered_modules.append(Webhook(freqtrade)) + # Enable local rest api server for cmd line control + if freqtrade.config.get('api_server', {}).get('enabled', False): + logger.info('Enabling rpc.api_server') + from freqtrade.rpc.api_server import ApiServer + self.registered_modules.append(ApiServer(freqtrade)) + def cleanup(self) -> None: """ Stops all enabled rpc modules """ logger.info('Cleaning up rpc modules ...') From 68743012e400cde9e04a434e385eeceeded237c0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 07:13:55 +0200 Subject: [PATCH 05/71] Patch api server for tests --- freqtrade/tests/conftest.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/freqtrade/tests/conftest.py b/freqtrade/tests/conftest.py index 0bff1d5e9..98563a374 100644 --- a/freqtrade/tests/conftest.py +++ b/freqtrade/tests/conftest.py @@ -134,6 +134,15 @@ def patch_coinmarketcap(mocker) -> None: ) +def patch_apiserver(mocker) -> None: + mocker.patch.multiple( + 'freqtrade.rpc.api_server.ApiServer', + run=MagicMock(), + register_rest_other=MagicMock(), + register_rest_rpc_urls=MagicMock(), + ) + + @pytest.fixture(scope="function") def default_conf(): """ Returns validated configuration suitable for most tests """ From 9d95ae934190ce72435dae7f1ce819de77f0bc3a Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 19:34:05 +0200 Subject: [PATCH 06/71] Add flask to dependencies --- requirements-common.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/requirements-common.txt b/requirements-common.txt index 4f7309a6a..9e3e2816c 100644 --- a/requirements-common.txt +++ b/requirements-common.txt @@ -27,3 +27,6 @@ python-rapidjson==0.7.1 # Notify systemd sdnotify==0.3.2 + +# Api server +flask==1.0.2 From 6bb2fad9b07e2ffd64c2e3b22a9ab77f5f815224 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 19:34:19 +0200 Subject: [PATCH 07/71] Reorder some things --- freqtrade/rpc/api_server.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 1055a0553..46678466d 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -38,6 +38,12 @@ class ApiServer(RPC): thread = threading.Thread(target=self.run, daemon=True) thread.start() + def cleanup(self) -> None: + pass + + def send_msg(self, msg: Dict[str, str]) -> None: + pass + def register_rest_other(self): """ Registers flask app URLs that are not calls to functionality in rpc.rpc. @@ -84,12 +90,6 @@ class ApiServer(RPC): except Exception: logger.exception("Api server failed to start, exception message is:") - def cleanup(self) -> None: - pass - - def send_msg(self, msg: Dict[str, str]) -> None: - pass - """ Define the application methods here, called by app.add_url_rule each Telegram command should have a like local substitute From 96a260b027075809d4fc09e351a5f1a4733d36bf Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 20:21:26 +0200 Subject: [PATCH 08/71] rest_dump --- freqtrade/rpc/api_server.py | 43 +++++++++-------- freqtrade/rpc/api_server_common.py | 74 ------------------------------ 2 files changed, 21 insertions(+), 96 deletions(-) delete mode 100644 freqtrade/rpc/api_server_common.py diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 46678466d..a0532a3b3 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -4,7 +4,7 @@ import logging # import json from typing import Dict -from flask import Flask, request +from flask import Flask, request, jsonify # from flask_restful import Resource, Api from freqtrade.rpc.rpc import RPC, RPCException from ipaddress import IPv4Address @@ -39,11 +39,15 @@ class ApiServer(RPC): thread.start() def cleanup(self) -> None: - pass + logger.info("Stopping API Server") def send_msg(self, msg: Dict[str, str]) -> None: pass + def rest_dump(self, return_value): + """ Helper function to jsonify object for a webserver """ + return jsonify(return_value) + def register_rest_other(self): """ Registers flask app URLs that are not calls to functionality in rpc.rpc. @@ -89,6 +93,7 @@ class ApiServer(RPC): app.run(host=rest_ip, port=rest_port) except Exception: logger.exception("Api server failed to start, exception message is:") + logger.info('Starting Local Rest Server_end') """ Define the application methods here, called by app.add_url_rule @@ -99,7 +104,7 @@ class ApiServer(RPC): """ Return "404 not found", 404. """ - return json.dumps({ + return self.rest_dump({ 'status': 'error', 'reason': '''There's no API call for %s''' % request.base_url, 'code': 404 @@ -113,20 +118,14 @@ class ApiServer(RPC): This may be deprecated at any time. :return: index.html """ - rest_cmds = 'Commands implemented:
' \ - 'Show 7 days of stats' \ - '
' \ - 'Stop the Trade thread' \ - '
' \ - 'Start the Traded thread' \ - '
' \ - 'Show profit summary' \ - '
' \ - 'Show status table - Open trades' \ - '
' \ - ' 404 page does not exist' \ - '
' - + rest_cmds = ('Commands implemented:
' + 'Show 7 days of stats
' + 'Stop the Trade thread
' + 'Start the Traded thread
' + 'Show profit summary
' + 'Show status table - Open trades
' + ' 404 page does not exist
' + ) return rest_cmds def daily(self): @@ -145,7 +144,7 @@ class ApiServer(RPC): self._config['fiat_display_currency'] ) - return json.dumps(stats, indent=4, sort_keys=True, default=str) + return self.rest_dump(stats) except RPCException as e: logger.exception("API Error querying daily:", e) return "Error querying daily" @@ -164,7 +163,7 @@ class ApiServer(RPC): self._config['fiat_display_currency'] ) - return json.dumps(stats, indent=4, sort_keys=True, default=str) + return self.rest_dump(stats) except RPCException as e: logger.exception("API Error calling profit", e) return "Error querying closed trades - maybe there are none" @@ -178,7 +177,7 @@ class ApiServer(RPC): """ try: results = self._rpc_trade_status() - return json.dumps(results, indent=4, sort_keys=True, default=str) + return self.rest_dump(results) except RPCException as e: logger.exception("API Error calling status table", e) @@ -191,7 +190,7 @@ class ApiServer(RPC): Starts TradeThread in bot if stopped. """ msg = self._rpc_start() - return json.dumps(msg) + return self.rest_dump(msg) def stop(self): """ @@ -200,4 +199,4 @@ class ApiServer(RPC): Stops TradeThread in bot if running """ msg = self._rpc_stop() - return json.dumps(msg) + return self.rest_dump(msg) diff --git a/freqtrade/rpc/api_server_common.py b/freqtrade/rpc/api_server_common.py deleted file mode 100644 index 19338a825..000000000 --- a/freqtrade/rpc/api_server_common.py +++ /dev/null @@ -1,74 +0,0 @@ -import logging -import flask -from flask import request, jsonify - -logger = logging.getLogger(__name__) - - -class MyApiApp(flask.Flask): - def __init__(self, import_name): - """ - Contains common rest routes and resource that do not need - to access to rpc.rpc functionality - """ - super(MyApiApp, self).__init__(import_name) - - """ - Registers flask app URLs that are not calls to functionality in rpc.rpc. - :return: - """ - self.before_request(self.my_preprocessing) - self.register_error_handler(404, self.page_not_found) - self.add_url_rule('/', 'hello', view_func=self.hello, methods=['GET']) - self.add_url_rule('/stop_api', 'stop_api', view_func=self.stop_api, methods=['GET']) - - def my_preprocessing(self): - # Do stuff to flask.request - pass - - def page_not_found(self, error): - # Return "404 not found", 404. - return jsonify({'status': 'error', - 'reason': '''There's no API call for %s''' % request.base_url, - 'code': 404}), 404 - - def hello(self): - """ - None critical but helpful default index page. - - That lists URLs added to the flask server. - This may be deprecated at any time. - :return: index.html - """ - rest_cmds = 'Commands implemented:
' \ - 'Show 7 days of stats' \ - '
' \ - 'Stop the Trade thread' \ - '
' \ - 'Start the Traded thread' \ - '
' \ - ' 404 page does not exist' \ - '
' \ - '
' \ - 'Shut down the api server - be sure' - return rest_cmds - - def stop_api(self): - """ For calling shutdown_api_server over via api server HTTP""" - self.shutdown_api_server() - return 'Api Server shutting down... ' - - def shutdown_api_server(self): - """ - Stop the running flask application - - Records the shutdown in logger.info - :return: - """ - func = request.environ.get('werkzeug.server.shutdown') - if func is None: - raise RuntimeError('Not running the Flask Werkzeug Server') - if func is not None: - logger.info('Stopping the Local Rest Server') - func() - return From c6c2893e2cef4a058a4d5adc2c4e13755e44d876 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 4 Apr 2019 21:07:44 +0200 Subject: [PATCH 09/71] Improve rest-client interface --- freqtrade/rpc/rest_client.py | 96 ++++++++++++++++++++++++------------ 1 file changed, 65 insertions(+), 31 deletions(-) diff --git a/freqtrade/rpc/rest_client.py b/freqtrade/rpc/rest_client.py index cabedebb8..5ae65dc4a 100755 --- a/freqtrade/rpc/rest_client.py +++ b/freqtrade/rpc/rest_client.py @@ -2,46 +2,80 @@ """ Simple command line client into RPC commands Can be used as an alternate to Telegram + +Should not import anything from freqtrade, +so it can be used as a standalone script. """ +import argparse +import logging import time -from requests import get from sys import argv -# TODO - use argparse to clean this up +import click + +from requests import get +from requests.exceptions import ConnectionError + +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', +) +logger = logging.getLogger("ft_rest_client") + # TODO - use IP and Port from config.json not hardcode -if len(argv) == 1: - print('\nThis script accepts the following arguments') - print('- daily (int) - Where int is the number of days to report back. daily 3') - print('- start - this will start the trading thread') - print('- stop - this will start the trading thread') - print('- there will be more....\n') +COMMANDS_NO_ARGS = ["start", + "stop", + ] +COMMANDS_ARGS = ["daily", + ] -if len(argv) == 3 and argv[1] == "daily": - if str.isnumeric(argv[2]): - get_url = 'http://localhost:5002/daily?timescale=' + argv[2] - d = get(get_url).json() - print(d) - else: - print("\nThe second argument to daily must be an integer, 1,2,3 etc") +SERVER_URL = "http://localhost:5002" -if len(argv) == 2 and argv[1] == "start": - get_url = 'http://localhost:5002/start' - d = get(get_url).text - print(d) - if "already" not in d: - time.sleep(2) - d = get(get_url).text - print(d) +def add_arguments(): + parser = argparse.ArgumentParser() + parser.add_argument("command", + help="Positional argument defining the command to execute.") + args = parser.parse_args() + # if len(argv) == 1: + # print('\nThis script accepts the following arguments') + # print('- daily (int) - Where int is the number of days to report back. daily 3') + # print('- start - this will start the trading thread') + # print('- stop - this will start the trading thread') + # print('- there will be more....\n') + return vars(args) -if len(argv) == 2 and argv[1] == "stop": - get_url = 'http://localhost:5002/stop' - d = get(get_url).text - print(d) - if "already" not in d: - time.sleep(2) - d = get(get_url).text - print(d) +def call_authorized(url): + try: + return get(url).json() + except ConnectionError: + logger.warning("Connection error") + + +def call_command_noargs(command): + logger.info(f"Running command `{command}` at {SERVER_URL}") + r = call_authorized(f"{SERVER_URL}/{command}") + logger.info(r) + + +def main(args): + + # Call commands without arguments + if args["command"] in COMMANDS_NO_ARGS: + call_command_noargs(args["command"]) + + if args["command"] == "daily": + if str.isnumeric(argv[2]): + get_url = SERVER_URL + '/daily?timescale=' + argv[2] + d = get(get_url).json() + print(d) + else: + print("\nThe second argument to daily must be an integer, 1,2,3 etc") + + +if __name__ == "__main__": + args = add_arguments() + main(args) From 8993882dcb1434b0f938ac45eee23cb4e4c5f915 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 5 Apr 2019 06:39:33 +0200 Subject: [PATCH 10/71] Sort imports --- freqtrade/rpc/api_server.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index a0532a3b3..20850a3a1 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -1,14 +1,11 @@ -import json -import threading import logging -# import json +import threading +from ipaddress import IPv4Address from typing import Dict -from flask import Flask, request, jsonify -# from flask_restful import Resource, Api -from freqtrade.rpc.rpc import RPC, RPCException -from ipaddress import IPv4Address +from flask import Flask, jsonify, request +from freqtrade.rpc.rpc import RPC, RPCException logger = logging.getLogger(__name__) app = Flask(__name__) @@ -42,6 +39,7 @@ class ApiServer(RPC): logger.info("Stopping API Server") def send_msg(self, msg: Dict[str, str]) -> None: + """We don't push to endpoints at the moment. Look at webhooks for that.""" pass def rest_dump(self, return_value): From 3cf6c6ee0c4ed3c346b80983789ee2acbc192750 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 6 Apr 2019 19:58:00 +0200 Subject: [PATCH 11/71] Implement a few more methods --- freqtrade/rpc/api_server.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 20850a3a1..53520025b 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -37,6 +37,8 @@ class ApiServer(RPC): def cleanup(self) -> None: logger.info("Stopping API Server") + # TODO: Gracefully shutdown - right now it'll fail on /reload_conf + # since it's not terminated correctly. def send_msg(self, msg: Dict[str, str]) -> None: """We don't push to endpoints at the moment. Look at webhooks for that.""" @@ -62,8 +64,13 @@ class ApiServer(RPC): Label can be used as a shortcut when refactoring :return: """ - app.add_url_rule('/stop', 'stop', view_func=self.stop, methods=['GET']) + # TODO: actions should not be GET... app.add_url_rule('/start', 'start', view_func=self.start, methods=['GET']) + app.add_url_rule('/stop', 'stop', view_func=self.stop, methods=['GET']) + app.add_url_rule('/stopbuy', 'stopbuy', view_func=self.stopbuy, methods=['GET']) + app.add_url_rule('/reload_conf', 'reload_conf', view_func=self.reload_conf, + methods=['GET']) + app.add_url_rule('/count', 'count', view_func=self.count, methods=['GET']) app.add_url_rule('/daily', 'daily', view_func=self.daily, methods=['GET']) app.add_url_rule('/profit', 'profit', view_func=self.profit, methods=['GET']) app.add_url_rule('/status_table', 'status_table', @@ -198,3 +205,31 @@ class ApiServer(RPC): """ msg = self._rpc_stop() return self.rest_dump(msg) + + def stopbuy(self): + """ + Handler for /stopbuy. + + Sets max_open_trades to 0 and gracefully sells all open trades + """ + msg = self._rpc_stopbuy() + return self.rest_dump(msg) + + def reload_conf(self): + """ + Handler for /reload_conf. + Triggers a config file reload + """ + msg = self._rpc_reload_conf() + return self.rest_dump(msg) + + def count(self): + """ + Handler for /count. + Returns the number of trades running + """ + try: + msg = self._rpc_count() + except RPCException as e: + msg = {"status": str(e)} + return self.rest_dump(msg) From 2f8088432c9f16423ea7a3625cf5128a12b478a3 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 6 Apr 2019 20:08:01 +0200 Subject: [PATCH 12/71] All handlers should be private --- freqtrade/rpc/api_server.py | 119 +++++++++++++++++++----------------- 1 file changed, 62 insertions(+), 57 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 53520025b..30771bdc7 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -5,6 +5,7 @@ from typing import Dict from flask import Flask, jsonify, request +from freqtrade.__init__ import __version__ from freqtrade.rpc.rpc import RPC, RPCException logger = logging.getLogger(__name__) @@ -65,16 +66,17 @@ class ApiServer(RPC): :return: """ # TODO: actions should not be GET... - app.add_url_rule('/start', 'start', view_func=self.start, methods=['GET']) - app.add_url_rule('/stop', 'stop', view_func=self.stop, methods=['GET']) - app.add_url_rule('/stopbuy', 'stopbuy', view_func=self.stopbuy, methods=['GET']) - app.add_url_rule('/reload_conf', 'reload_conf', view_func=self.reload_conf, + app.add_url_rule('/start', 'start', view_func=self._start, methods=['GET']) + app.add_url_rule('/stop', 'stop', view_func=self._stop, methods=['GET']) + app.add_url_rule('/stopbuy', 'stopbuy', view_func=self._stopbuy, methods=['GET']) + app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) + app.add_url_rule('/reload_conf', 'reload_conf', view_func=self._reload_conf, methods=['GET']) - app.add_url_rule('/count', 'count', view_func=self.count, methods=['GET']) - app.add_url_rule('/daily', 'daily', view_func=self.daily, methods=['GET']) - app.add_url_rule('/profit', 'profit', view_func=self.profit, methods=['GET']) + app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) + app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) + app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) app.add_url_rule('/status_table', 'status_table', - view_func=self.status_table, methods=['GET']) + view_func=self._status_table, methods=['GET']) def run(self): """ Method that runs flask app in its own thread forever """ @@ -133,7 +135,56 @@ class ApiServer(RPC): ) return rest_cmds - def daily(self): + def _start(self): + """ + Handler for /start. + Starts TradeThread in bot if stopped. + """ + msg = self._rpc_start() + return self.rest_dump(msg) + + def _stop(self): + """ + Handler for /stop. + Stops TradeThread in bot if running + """ + msg = self._rpc_stop() + return self.rest_dump(msg) + + def _stopbuy(self): + """ + Handler for /stopbuy. + Sets max_open_trades to 0 and gracefully sells all open trades + """ + msg = self._rpc_stopbuy() + return self.rest_dump(msg) + + def _version(self): + """ + Prints the bot's version + """ + return self.rest_dump({"version": __version__}) + + def _reload_conf(self): + """ + Handler for /reload_conf. + Triggers a config file reload + """ + msg = self._rpc_reload_conf() + return self.rest_dump(msg) + + def _count(self): + """ + Handler for /count. + Returns the number of trades running + """ + try: + msg = self._rpc_count() + except RPCException as e: + msg = {"status": str(e)} + return self.rest_dump(msg) + + def _daily(self): """ Returns the last X days trading stats summary. @@ -154,7 +205,7 @@ class ApiServer(RPC): logger.exception("API Error querying daily:", e) return "Error querying daily" - def profit(self): + def _profit(self): """ Handler for /profit. @@ -173,7 +224,7 @@ class ApiServer(RPC): logger.exception("API Error calling profit", e) return "Error querying closed trades - maybe there are none" - def status_table(self): + def _status_table(self): """ Handler for /status table. @@ -187,49 +238,3 @@ class ApiServer(RPC): except RPCException as e: logger.exception("API Error calling status table", e) return "Error querying open trades - maybe there are none." - - def start(self): - """ - Handler for /start. - - Starts TradeThread in bot if stopped. - """ - msg = self._rpc_start() - return self.rest_dump(msg) - - def stop(self): - """ - Handler for /stop. - - Stops TradeThread in bot if running - """ - msg = self._rpc_stop() - return self.rest_dump(msg) - - def stopbuy(self): - """ - Handler for /stopbuy. - - Sets max_open_trades to 0 and gracefully sells all open trades - """ - msg = self._rpc_stopbuy() - return self.rest_dump(msg) - - def reload_conf(self): - """ - Handler for /reload_conf. - Triggers a config file reload - """ - msg = self._rpc_reload_conf() - return self.rest_dump(msg) - - def count(self): - """ - Handler for /count. - Returns the number of trades running - """ - try: - msg = self._rpc_count() - except RPCException as e: - msg = {"status": str(e)} - return self.rest_dump(msg) From a12e093417b3bc60c7c20b6410798e4ef3e836be Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 7 Apr 2019 13:09:53 +0200 Subject: [PATCH 13/71] Api server - custom json encoder --- freqtrade/rpc/api_server.py | 50 ++++++++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 14 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 30771bdc7..fe2367458 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -3,13 +3,31 @@ import threading from ipaddress import IPv4Address from typing import Dict +from arrow import Arrow from flask import Flask, jsonify, request +from flask.json import JSONEncoder from freqtrade.__init__ import __version__ from freqtrade.rpc.rpc import RPC, RPCException logger = logging.getLogger(__name__) + + +class ArrowJSONEncoder(JSONEncoder): + def default(self, obj): + try: + if isinstance(obj, Arrow): + return obj.for_json() + iterable = iter(obj) + except TypeError: + pass + else: + return list(iterable) + return JSONEncoder.default(self, obj) + + app = Flask(__name__) +app.json_encoder = ArrowJSONEncoder class ApiServer(RPC): @@ -42,13 +60,19 @@ class ApiServer(RPC): # since it's not terminated correctly. def send_msg(self, msg: Dict[str, str]) -> None: - """We don't push to endpoints at the moment. Look at webhooks for that.""" + """ + We don't push to endpoints at the moment. + Take a look at webhooks for that functionality. + """ pass def rest_dump(self, return_value): """ Helper function to jsonify object for a webserver """ return jsonify(return_value) + def rest_error(self, error_msg): + return jsonify({"error": error_msg}), 502 + def register_rest_other(self): """ Registers flask app URLs that are not calls to functionality in rpc.rpc. @@ -75,8 +99,7 @@ class ApiServer(RPC): app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) - app.add_url_rule('/status_table', 'status_table', - view_func=self._status_table, methods=['GET']) + app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) def run(self): """ Method that runs flask app in its own thread forever """ @@ -180,9 +203,9 @@ class ApiServer(RPC): """ try: msg = self._rpc_count() + return self.rest_dump(msg) except RPCException as e: - msg = {"status": str(e)} - return self.rest_dump(msg) + return self.rest_error(str(e)) def _daily(self): """ @@ -202,8 +225,8 @@ class ApiServer(RPC): return self.rest_dump(stats) except RPCException as e: - logger.exception("API Error querying daily:", e) - return "Error querying daily" + logger.exception("API Error querying daily: %s", e) + return self.rest_error(f"Error querying daily {e}") def _profit(self): """ @@ -221,20 +244,19 @@ class ApiServer(RPC): return self.rest_dump(stats) except RPCException as e: - logger.exception("API Error calling profit", e) - return "Error querying closed trades - maybe there are none" + logger.exception("API Error calling profit: %s", e) + return self.rest_error("Error querying closed trades - maybe there are none") - def _status_table(self): + def _status(self): """ Handler for /status table. - Returns the current TradeThread status in table format - :return: results + Returns the current status of the trades in json format """ try: results = self._rpc_trade_status() return self.rest_dump(results) except RPCException as e: - logger.exception("API Error calling status table", e) - return "Error querying open trades - maybe there are none." + logger.exception("API Error calling status table: %s", e) + return self.rest_error("Error querying open trades - maybe there are none.") From d8549fe09ab9bd5f9410149abc4b3fd780615603 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 7 Apr 2019 13:22:44 +0200 Subject: [PATCH 14/71] add balance handler --- freqtrade/rpc/api_server.py | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index fe2367458..a07057997 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -90,16 +90,27 @@ class ApiServer(RPC): :return: """ # TODO: actions should not be GET... + # Actions to control the bot app.add_url_rule('/start', 'start', view_func=self._start, methods=['GET']) app.add_url_rule('/stop', 'stop', view_func=self._stop, methods=['GET']) app.add_url_rule('/stopbuy', 'stopbuy', view_func=self._stopbuy, methods=['GET']) - app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) app.add_url_rule('/reload_conf', 'reload_conf', view_func=self._reload_conf, methods=['GET']) + # Info commands + app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) + app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) + # TODO: Implement the following + # performance + # forcebuy + # forcesell + # whitelist + # blacklist + # edge + # help (?) def run(self): """ Method that runs flask app in its own thread forever """ @@ -258,5 +269,19 @@ class ApiServer(RPC): return self.rest_dump(results) except RPCException as e: - logger.exception("API Error calling status table: %s", e) + logger.exception("API Error calling status: %s", e) return self.rest_error("Error querying open trades - maybe there are none.") + + def _balance(self): + """ + Handler for /balance table. + + Returns the current status of the trades in json format + """ + try: + results = self._rpc_balance(self._config.get('fiat_display_currency', '')) + return self.rest_dump(results) + + except RPCException as e: + logger.exception("API Error calling status table: %s", e) + return self.rest_error(f"{e}") From 01c93a2ee36d878289c3e90fe38df4888098c8df Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 9 Apr 2019 06:40:15 +0200 Subject: [PATCH 15/71] Load rest-client config from file --- freqtrade/rpc/rest_client.py | 40 ++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/freqtrade/rpc/rest_client.py b/freqtrade/rpc/rest_client.py index 5ae65dc4a..51c7a88f5 100755 --- a/freqtrade/rpc/rest_client.py +++ b/freqtrade/rpc/rest_client.py @@ -8,11 +8,10 @@ so it can be used as a standalone script. """ import argparse +import json import logging -import time from sys import argv - -import click +from pathlib import Path from requests import get from requests.exceptions import ConnectionError @@ -23,21 +22,27 @@ logging.basicConfig( ) logger = logging.getLogger("ft_rest_client") -# TODO - use IP and Port from config.json not hardcode COMMANDS_NO_ARGS = ["start", "stop", + "stopbuy", + "reload_conf" ] COMMANDS_ARGS = ["daily", ] -SERVER_URL = "http://localhost:5002" - def add_arguments(): parser = argparse.ArgumentParser() parser.add_argument("command", help="Positional argument defining the command to execute.") + parser.add_argument('-c', '--config', + help='Specify configuration file (default: %(default)s). ', + dest='config', + type=str, + metavar='PATH', + default='config.json' + ) args = parser.parse_args() # if len(argv) == 1: # print('\nThis script accepts the following arguments') @@ -48,6 +53,14 @@ def add_arguments(): return vars(args) +def load_config(configfile): + file = Path(configfile) + if file.is_file(): + with file.open("r") as f: + config = json.load(f) + return config + + def call_authorized(url): try: return get(url).json() @@ -55,21 +68,26 @@ def call_authorized(url): logger.warning("Connection error") -def call_command_noargs(command): - logger.info(f"Running command `{command}` at {SERVER_URL}") - r = call_authorized(f"{SERVER_URL}/{command}") +def call_command_noargs(server_url, command): + logger.info(f"Running command `{command}` at {server_url}") + r = call_authorized(f"{server_url}/{command}") logger.info(r) def main(args): + config = load_config(args["config"]) + url = config.get("api_server", {}).get("server_url", "127.0.0.1") + port = config.get("api_server", {}).get("listen_port", "8080") + server_url = f"http://{url}:{port}" + # Call commands without arguments if args["command"] in COMMANDS_NO_ARGS: - call_command_noargs(args["command"]) + call_command_noargs(server_url, args["command"]) if args["command"] == "daily": if str.isnumeric(argv[2]): - get_url = SERVER_URL + '/daily?timescale=' + argv[2] + get_url = server_url + '/daily?timescale=' + argv[2] d = get(get_url).json() print(d) else: From ae8660fe06f213d7e5017d6bceb0de84b2811f33 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 9 Apr 2019 06:59:07 +0200 Subject: [PATCH 16/71] Extract exception handling to decorator --- freqtrade/rpc/api_server.py | 85 ++++++++++++++++++++----------------- 1 file changed, 45 insertions(+), 40 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index a07057997..06f4ad0b9 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -37,6 +37,18 @@ class ApiServer(RPC): This class starts a none blocking thread the api server runs within """ + def safe_rpc(func): + + def func_wrapper(self, *args, **kwargs): + + try: + return func(self, *args, **kwargs) + except RPCException as e: + logger.exception("API Error calling %s: %s", func.__name__, e) + return self.rest_error(f"Error querying {func.__name__}: {e}") + + return func_wrapper + def __init__(self, freqtrade) -> None: """ Init the api server, and init the super class RPC @@ -103,11 +115,11 @@ class ApiServer(RPC): app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) + app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, methods=['GET']) # TODO: Implement the following # performance # forcebuy # forcesell - # whitelist # blacklist # edge # help (?) @@ -207,38 +219,34 @@ class ApiServer(RPC): msg = self._rpc_reload_conf() return self.rest_dump(msg) + @safe_rpc def _count(self): """ Handler for /count. Returns the number of trades running """ - try: - msg = self._rpc_count() - return self.rest_dump(msg) - except RPCException as e: - return self.rest_error(str(e)) + msg = self._rpc_count() + return self.rest_dump(msg) + @safe_rpc def _daily(self): """ Returns the last X days trading stats summary. :return: stats """ - try: - timescale = request.args.get('timescale') - logger.info("LocalRPC - Daily Command Called") - timescale = int(timescale) + timescale = request.args.get('timescale') + logger.info("LocalRPC - Daily Command Called") + timescale = int(timescale) - stats = self._rpc_daily_profit(timescale, - self._config['stake_currency'], - self._config['fiat_display_currency'] - ) + stats = self._rpc_daily_profit(timescale, + self._config['stake_currency'], + self._config['fiat_display_currency'] + ) - return self.rest_dump(stats) - except RPCException as e: - logger.exception("API Error querying daily: %s", e) - return self.rest_error(f"Error querying daily {e}") + return self.rest_dump(stats) + @safe_rpc def _profit(self): """ Handler for /profit. @@ -246,42 +254,39 @@ class ApiServer(RPC): Returns a cumulative profit statistics :return: stats """ - try: - logger.info("LocalRPC - Profit Command Called") + logger.info("LocalRPC - Profit Command Called") - stats = self._rpc_trade_statistics(self._config['stake_currency'], - self._config['fiat_display_currency'] - ) + stats = self._rpc_trade_statistics(self._config['stake_currency'], + self._config['fiat_display_currency'] + ) - return self.rest_dump(stats) - except RPCException as e: - logger.exception("API Error calling profit: %s", e) - return self.rest_error("Error querying closed trades - maybe there are none") + return self.rest_dump(stats) + @safe_rpc def _status(self): """ Handler for /status table. Returns the current status of the trades in json format """ - try: - results = self._rpc_trade_status() - return self.rest_dump(results) - - except RPCException as e: - logger.exception("API Error calling status: %s", e) - return self.rest_error("Error querying open trades - maybe there are none.") + results = self._rpc_trade_status() + return self.rest_dump(results) + @safe_rpc def _balance(self): """ Handler for /balance table. Returns the current status of the trades in json format """ - try: - results = self._rpc_balance(self._config.get('fiat_display_currency', '')) - return self.rest_dump(results) + results = self._rpc_balance(self._config.get('fiat_display_currency', '')) + return self.rest_dump(results) - except RPCException as e: - logger.exception("API Error calling status table: %s", e) - return self.rest_error(f"{e}") + @safe_rpc + def _whitelist(self): + """ + Handler for /whitelist table. + + """ + results = self._rpc_whitelist() + return self.rest_dump(results) From 99875afcc034e6a7cdb96a2be5eb71917d3e9115 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 9 Apr 2019 07:08:46 +0200 Subject: [PATCH 17/71] Add default argument --- freqtrade/rpc/api_server.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 06f4ad0b9..693b82bec 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -235,8 +235,7 @@ class ApiServer(RPC): :return: stats """ - timescale = request.args.get('timescale') - logger.info("LocalRPC - Daily Command Called") + timescale = request.args.get('timescale', 7) timescale = int(timescale) stats = self._rpc_daily_profit(timescale, From d2c2811249022671812e9a4f8754105cc9697782 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 19 Apr 2019 06:45:15 +0200 Subject: [PATCH 18/71] Move rest-client to scripts --- {freqtrade/rpc => scripts}/rest_client.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {freqtrade/rpc => scripts}/rest_client.py (100%) diff --git a/freqtrade/rpc/rest_client.py b/scripts/rest_client.py similarity index 100% rename from freqtrade/rpc/rest_client.py rename to scripts/rest_client.py From 5ba189ffb41a7d887cc4d74b92e0ffb708f62194 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 19 Apr 2019 06:55:38 +0200 Subject: [PATCH 19/71] Add more commands to rest client, fix bug in config handling --- scripts/rest_client.py | 46 ++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 51c7a88f5..bd1187a3e 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -26,16 +26,28 @@ logger = logging.getLogger("ft_rest_client") COMMANDS_NO_ARGS = ["start", "stop", "stopbuy", - "reload_conf" + "reload_conf", ] -COMMANDS_ARGS = ["daily", - ] +INFO_COMMANDS = {"version": [], + "count": [], + "daily": ["timescale"], + "profit": [], + "status": [], + "balance": [] + } def add_arguments(): parser = argparse.ArgumentParser() parser.add_argument("command", help="Positional argument defining the command to execute.") + + parser.add_argument("command_arguments", + help="Positional arguments for the parameters for [command]", + nargs="*", + default=[] + ) + parser.add_argument('-c', '--config', help='Specify configuration file (default: %(default)s). ', dest='config', @@ -58,7 +70,8 @@ def load_config(configfile): if file.is_file(): with file.open("r") as f: config = json.load(f) - return config + return config + return {} def call_authorized(url): @@ -74,6 +87,22 @@ def call_command_noargs(server_url, command): logger.info(r) +def call_info(server_url, command, command_args): + logger.info(f"Running command `{command}` with parameters `{command_args}` at {server_url}") + call = f"{server_url}/{command}?" + args = INFO_COMMANDS[command] + if len(args) < len(command_args): + logger.error(f"Command {command} does only support {len(args)} arguments.") + return + for idx, arg in enumerate(command_args): + + call += f"{args[idx]}={arg}" + logger.debug(call) + r = call_authorized(call) + + logger.info(r) + + def main(args): config = load_config(args["config"]) @@ -85,13 +114,8 @@ def main(args): if args["command"] in COMMANDS_NO_ARGS: call_command_noargs(server_url, args["command"]) - if args["command"] == "daily": - if str.isnumeric(argv[2]): - get_url = server_url + '/daily?timescale=' + argv[2] - d = get(get_url).json() - print(d) - else: - print("\nThe second argument to daily must be an integer, 1,2,3 etc") + if args["command"] in INFO_COMMANDS: + call_info(server_url, args["command"], args["command_arguments"]) if __name__ == "__main__": From a1043121fc0a760194ad434d79371368d835386d Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 19 Apr 2019 06:56:01 +0200 Subject: [PATCH 20/71] Add blacklist handler --- freqtrade/rpc/api_server.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 693b82bec..2c151daf3 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -116,11 +116,13 @@ class ApiServer(RPC): app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, methods=['GET']) + app.add_url_rule('/blacklist', 'blacklist', view_func=self._blacklist, methods=['GET']) # TODO: Implement the following # performance # forcebuy # forcesell - # blacklist + # whitelist param + # balacklist params # edge # help (?) @@ -264,7 +266,7 @@ class ApiServer(RPC): @safe_rpc def _status(self): """ - Handler for /status table. + Handler for /status. Returns the current status of the trades in json format """ @@ -274,7 +276,7 @@ class ApiServer(RPC): @safe_rpc def _balance(self): """ - Handler for /balance table. + Handler for /balance. Returns the current status of the trades in json format """ @@ -284,8 +286,15 @@ class ApiServer(RPC): @safe_rpc def _whitelist(self): """ - Handler for /whitelist table. - + Handler for /whitelist. """ results = self._rpc_whitelist() return self.rest_dump(results) + + @safe_rpc + def _blacklist(self): + """ + Handler for /blacklist. + """ + results = self._rpc_blacklist() + return self.rest_dump(results) From a132d6e141fccc257c0814fb6e24927e41f3a028 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 25 Apr 2019 20:32:10 +0200 Subject: [PATCH 21/71] Refactor client into class --- scripts/rest_client.py | 95 +++++++++++++++++++++++++++--------------- 1 file changed, 62 insertions(+), 33 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index bd1187a3e..4e576d3cd 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -10,10 +10,10 @@ so it can be used as a standalone script. import argparse import json import logging -from sys import argv +from urllib.parse import urlencode, urlparse, urlunparse from pathlib import Path -from requests import get +import requests from requests.exceptions import ConnectionError logging.basicConfig( @@ -37,6 +37,63 @@ INFO_COMMANDS = {"version": [], } +class FtRestClient(): + + def __init__(self, serverurl): + self.serverurl = serverurl + + self.session = requests.Session() + + def call(self, method, apipath, params: dict = None, data=None, files=None): + + if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'): + raise ValueError('invalid method <{0}>'.format(method)) + basepath = f"{self.serverurl}/{apipath}" + + hd = {"Accept": "application/json", + "Content-Type": "application/json" + } + + # Split url + schema, netloc, path, params, query, fragment = urlparse(basepath) + # URLEncode query string + query = urlencode(params) + # recombine url + url = urlunparse((schema, netloc, path, params, query, fragment)) + print(url) + try: + + req = requests.Request(method, url, headers=hd, data=data, + # auth=self.session.auth + ) + reqp = req.prepare() + return self.session.send(reqp).json() + # return requests.get(url).json() + except ConnectionError: + logger.warning("Connection error") + + def call_command_noargs(self, command): + logger.info(f"Running command `{command}` at {self.serverurl}") + r = self.call("GET", command) + logger.info(r) + + def call_info(self, command, command_args): + logger.info( + f"Running command `{command}` with parameters `{command_args}` at {self.serverurl}") + args = INFO_COMMANDS[command] + if len(args) < len(command_args): + logger.error(f"Command {command} does only support {len(args)} arguments.") + return + params = {} + for idx, arg in enumerate(command_args): + params[args[idx]] = arg + + logger.debug(params) + r = self.call("GET", command, params) + + logger.info(r) + + def add_arguments(): parser = argparse.ArgumentParser() parser.add_argument("command", @@ -74,48 +131,20 @@ def load_config(configfile): return {} -def call_authorized(url): - try: - return get(url).json() - except ConnectionError: - logger.warning("Connection error") - - -def call_command_noargs(server_url, command): - logger.info(f"Running command `{command}` at {server_url}") - r = call_authorized(f"{server_url}/{command}") - logger.info(r) - - -def call_info(server_url, command, command_args): - logger.info(f"Running command `{command}` with parameters `{command_args}` at {server_url}") - call = f"{server_url}/{command}?" - args = INFO_COMMANDS[command] - if len(args) < len(command_args): - logger.error(f"Command {command} does only support {len(args)} arguments.") - return - for idx, arg in enumerate(command_args): - - call += f"{args[idx]}={arg}" - logger.debug(call) - r = call_authorized(call) - - logger.info(r) - - def main(args): config = load_config(args["config"]) url = config.get("api_server", {}).get("server_url", "127.0.0.1") port = config.get("api_server", {}).get("listen_port", "8080") server_url = f"http://{url}:{port}" + client = FtRestClient(server_url) # Call commands without arguments if args["command"] in COMMANDS_NO_ARGS: - call_command_noargs(server_url, args["command"]) + client.call_command_noargs(args["command"]) if args["command"] in INFO_COMMANDS: - call_info(server_url, args["command"], args["command_arguments"]) + client.call_info(args["command"], args["command_arguments"]) if __name__ == "__main__": From b0ac98a7cd069ceffda15d018792bbff70acdaf7 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:08:03 +0200 Subject: [PATCH 22/71] Clean up rest client --- scripts/rest_client.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 4e576d3cd..e01fc086e 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -40,8 +40,8 @@ INFO_COMMANDS = {"version": [], class FtRestClient(): def __init__(self, serverurl): - self.serverurl = serverurl + self.serverurl = serverurl self.session = requests.Session() def call(self, method, apipath, params: dict = None, data=None, files=None): @@ -62,19 +62,17 @@ class FtRestClient(): url = urlunparse((schema, netloc, path, params, query, fragment)) print(url) try: - - req = requests.Request(method, url, headers=hd, data=data, - # auth=self.session.auth - ) - reqp = req.prepare() - return self.session.send(reqp).json() - # return requests.get(url).json() + resp = self.session.request(method, url, headers=hd, data=data, + # auth=self.session.auth + ) + # return resp.text + return resp.json() except ConnectionError: logger.warning("Connection error") def call_command_noargs(self, command): logger.info(f"Running command `{command}` at {self.serverurl}") - r = self.call("GET", command) + r = self.call("POST", command) logger.info(r) def call_info(self, command, command_args): From ebebf94750f8fd56add5520ecd0e0ef2777bbebf Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:10:07 +0200 Subject: [PATCH 23/71] Change commands to post --- freqtrade/rpc/api_server.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 2c151daf3..d520fd255 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -103,11 +103,11 @@ class ApiServer(RPC): """ # TODO: actions should not be GET... # Actions to control the bot - app.add_url_rule('/start', 'start', view_func=self._start, methods=['GET']) - app.add_url_rule('/stop', 'stop', view_func=self._stop, methods=['GET']) - app.add_url_rule('/stopbuy', 'stopbuy', view_func=self._stopbuy, methods=['GET']) + app.add_url_rule('/start', 'start', view_func=self._start, methods=['POST']) + app.add_url_rule('/stop', 'stop', view_func=self._stop, methods=['POST']) + app.add_url_rule('/stopbuy', 'stopbuy', view_func=self._stopbuy, methods=['POST']) app.add_url_rule('/reload_conf', 'reload_conf', view_func=self._reload_conf, - methods=['GET']) + methods=['POST']) # Info commands app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) From d1fffab23580ff615d3bd3fbbe532c451c2ad69a Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:10:23 +0200 Subject: [PATCH 24/71] Rename internal methods to _ --- scripts/rest_client.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index e01fc086e..6843bb31d 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -44,7 +44,7 @@ class FtRestClient(): self.serverurl = serverurl self.session = requests.Session() - def call(self, method, apipath, params: dict = None, data=None, files=None): + def _call(self, method, apipath, params: dict = None, data=None, files=None): if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'): raise ValueError('invalid method <{0}>'.format(method)) @@ -70,12 +70,12 @@ class FtRestClient(): except ConnectionError: logger.warning("Connection error") - def call_command_noargs(self, command): + def _call_command_noargs(self, command): logger.info(f"Running command `{command}` at {self.serverurl}") - r = self.call("POST", command) + r = self._call("POST", command) logger.info(r) - def call_info(self, command, command_args): + def _call_info(self, command, command_args): logger.info( f"Running command `{command}` with parameters `{command_args}` at {self.serverurl}") args = INFO_COMMANDS[command] @@ -87,7 +87,7 @@ class FtRestClient(): params[args[idx]] = arg logger.debug(params) - r = self.call("GET", command, params) + r = self._call("GET", command, params) logger.info(r) @@ -139,10 +139,10 @@ def main(args): # Call commands without arguments if args["command"] in COMMANDS_NO_ARGS: - client.call_command_noargs(args["command"]) + client._call_command_noargs(args["command"]) if args["command"] in INFO_COMMANDS: - client.call_info(args["command"], args["command_arguments"]) + client._call_info(args["command"], args["command_arguments"]) if __name__ == "__main__": From 8f9b9d31e2f667cbaa0083b6982f01eae006d9f0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:12:03 +0200 Subject: [PATCH 25/71] Reorder arguments --- scripts/rest_client.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 6843bb31d..fc3478046 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -97,12 +97,6 @@ def add_arguments(): parser.add_argument("command", help="Positional argument defining the command to execute.") - parser.add_argument("command_arguments", - help="Positional arguments for the parameters for [command]", - nargs="*", - default=[] - ) - parser.add_argument('-c', '--config', help='Specify configuration file (default: %(default)s). ', dest='config', @@ -110,6 +104,13 @@ def add_arguments(): metavar='PATH', default='config.json' ) + + parser.add_argument("command_arguments", + help="Positional arguments for the parameters for [command]", + nargs="*", + default=[] + ) + args = parser.parse_args() # if len(argv) == 1: # print('\nThis script accepts the following arguments') From 938d7275ba49b6cf718d6c8c5ff03958b13c4243 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:27:20 +0200 Subject: [PATCH 26/71] implement some methods --- scripts/rest_client.py | 50 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index fc3478046..eb6fb97a9 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -10,6 +10,7 @@ so it can be used as a standalone script. import argparse import json import logging +import inspect from urllib.parse import urlencode, urlparse, urlunparse from pathlib import Path @@ -55,11 +56,11 @@ class FtRestClient(): } # Split url - schema, netloc, path, params, query, fragment = urlparse(basepath) + schema, netloc, path, par, query, fragment = urlparse(basepath) # URLEncode query string query = urlencode(params) # recombine url - url = urlunparse((schema, netloc, path, params, query, fragment)) + url = urlunparse((schema, netloc, path, par, query, fragment)) print(url) try: resp = self.session.request(method, url, headers=hd, data=data, @@ -70,6 +71,12 @@ class FtRestClient(): except ConnectionError: logger.warning("Connection error") + def _get(self, apipath, params: dict = None): + return self._call("GET", apipath, params=params) + + def _post(self, apipath, params: dict = None, data: dict = None): + return self._call("POST", apipath, params=params, data=data) + def _call_command_noargs(self, command): logger.info(f"Running command `{command}` at {self.serverurl}") r = self._call("POST", command) @@ -91,6 +98,27 @@ class FtRestClient(): logger.info(r) + def version(self): + """ + Returns the version of the bot + :returns: json object containing the version + """ + return self._get("version") + + def count(self): + """ + Returns the amount of open trades + :returns: json object + """ + return self._get("count") + + def daily(self, days=None): + """ + Returns the amount of open trades + :returns: json object + """ + return self._get("daily", params={"timescale": days} if days else None) + def add_arguments(): parser = argparse.ArgumentParser() @@ -138,12 +166,20 @@ def main(args): server_url = f"http://{url}:{port}" client = FtRestClient(server_url) - # Call commands without arguments - if args["command"] in COMMANDS_NO_ARGS: - client._call_command_noargs(args["command"]) + m = [x for x, y in inspect.getmembers(client) if not x.startswith('_')] + command = args["command"] + if command not in m: + logger.error(f"Command {command} not defined") + return - if args["command"] in INFO_COMMANDS: - client._call_info(args["command"], args["command_arguments"]) + print(getattr(client, command)(*args["command_arguments"])) + + # Call commands without arguments + # if args["command"] in COMMANDS_NO_ARGS: + # client._call_command_noargs(args["command"]) + + # if args["command"] in INFO_COMMANDS: + # client._call_info(args["command"], args["command_arguments"]) if __name__ == "__main__": From 122cf4c897268d8ba2ce7e8665f4f1a9989dda93 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:55:11 +0200 Subject: [PATCH 27/71] Default add to None for blacklist rpc calls --- freqtrade/rpc/rpc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 5b78c8356..048ebec63 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -470,7 +470,7 @@ class RPC(object): } return res - def _rpc_blacklist(self, add: List[str]) -> Dict: + def _rpc_blacklist(self, add: List[str] = None) -> Dict: """ Returns the currently active blacklist""" if add: stake_currency = self._freqtrade.config.get('stake_currency') From 3efdd55fb8526a3c1a771bcc1c89928d191f86db Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:55:36 +0200 Subject: [PATCH 28/71] Support blacklist adding --- freqtrade/rpc/api_server.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index d520fd255..1643bc535 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -115,14 +115,15 @@ class ApiServer(RPC): app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) - app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, methods=['GET']) - app.add_url_rule('/blacklist', 'blacklist', view_func=self._blacklist, methods=['GET']) + app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, + methods=['GET']) + app.add_url_rule('/blacklist', 'blacklist', view_func=self._blacklist, + methods=['GET', 'POST']) # TODO: Implement the following # performance # forcebuy # forcesell - # whitelist param - # balacklist params + # blacklist params # edge # help (?) @@ -296,5 +297,6 @@ class ApiServer(RPC): """ Handler for /blacklist. """ - results = self._rpc_blacklist() + add = request.json.get("blacklist", None) if request.method == 'POST' else None + results = self._rpc_blacklist(add) return self.rest_dump(results) From 0163edc868c3a8c2e9e4040387ea588415163d0f Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:55:52 +0200 Subject: [PATCH 29/71] rest-client more methods --- scripts/rest_client.py | 123 +++++++++++++++++++++++------------------ 1 file changed, 69 insertions(+), 54 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index eb6fb97a9..1958c1a07 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -11,6 +11,7 @@ import argparse import json import logging import inspect +from typing import List from urllib.parse import urlencode, urlparse, urlunparse from pathlib import Path @@ -24,32 +25,18 @@ logging.basicConfig( logger = logging.getLogger("ft_rest_client") -COMMANDS_NO_ARGS = ["start", - "stop", - "stopbuy", - "reload_conf", - ] -INFO_COMMANDS = {"version": [], - "count": [], - "daily": ["timescale"], - "profit": [], - "status": [], - "balance": [] - } - - class FtRestClient(): def __init__(self, serverurl): - self.serverurl = serverurl - self.session = requests.Session() + self._serverurl = serverurl + self._session = requests.Session() def _call(self, method, apipath, params: dict = None, data=None, files=None): if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'): raise ValueError('invalid method <{0}>'.format(method)) - basepath = f"{self.serverurl}/{apipath}" + basepath = f"{self._serverurl}/{apipath}" hd = {"Accept": "application/json", "Content-Type": "application/json" @@ -58,14 +45,14 @@ class FtRestClient(): # Split url schema, netloc, path, par, query, fragment = urlparse(basepath) # URLEncode query string - query = urlencode(params) + query = urlencode(params) if params else None # recombine url url = urlunparse((schema, netloc, path, par, query, fragment)) - print(url) + try: - resp = self.session.request(method, url, headers=hd, data=data, - # auth=self.session.auth - ) + resp = self._session.request(method, url, headers=hd, data=json.dumps(data), + # auth=self.session.auth + ) # return resp.text return resp.json() except ConnectionError: @@ -77,33 +64,12 @@ class FtRestClient(): def _post(self, apipath, params: dict = None, data: dict = None): return self._call("POST", apipath, params=params, data=data) - def _call_command_noargs(self, command): - logger.info(f"Running command `{command}` at {self.serverurl}") - r = self._call("POST", command) - logger.info(r) - - def _call_info(self, command, command_args): - logger.info( - f"Running command `{command}` with parameters `{command_args}` at {self.serverurl}") - args = INFO_COMMANDS[command] - if len(args) < len(command_args): - logger.error(f"Command {command} does only support {len(args)} arguments.") - return - params = {} - for idx, arg in enumerate(command_args): - params[args[idx]] = arg - - logger.debug(params) - r = self._call("GET", command, params) - - logger.info(r) - - def version(self): + def balance(self): """ - Returns the version of the bot - :returns: json object containing the version + get the account balance + :returns: json object """ - return self._get("version") + return self._get("balance") def count(self): """ @@ -119,12 +85,58 @@ class FtRestClient(): """ return self._get("daily", params={"timescale": days} if days else None) + def profit(self): + """ + Returns the profit summary + :returns: json object + """ + return self._get("profit") + + def status(self): + """ + Get the status of open trades + :returns: json object + """ + return self._get("status") + + def whitelist(self): + """ + Show the current whitelist + :returns: json object + """ + return self._get("whitelist") + + def blacklist(self, *args): + """ + Show the current blacklist + :param add: List of coins to add (example: "BNB/BTC") + :returns: json object + """ + if not args: + return self._get("blacklist") + else: + return self._post("blacklist", data={"blacklist": args}) + + def version(self): + """ + Returns the version of the bot + :returns: json object containing the version + """ + return self._get("version") + def add_arguments(): parser = argparse.ArgumentParser() parser.add_argument("command", help="Positional argument defining the command to execute.") + parser.add_argument('--show', + help='Show possible methods with this client', + dest='show', + action='store_true', + default=False + ) + parser.add_argument('-c', '--config', help='Specify configuration file (default: %(default)s). ', dest='config', @@ -160,6 +172,16 @@ def load_config(configfile): def main(args): + if args.get("show"): + # Print dynamic help for the different commands + client = FtRestClient(None) + print("Possible commands:") + for x, y in inspect.getmembers(client): + if not x.startswith('_'): + print(f"{x} {getattr(client, x).__doc__}") + + return + config = load_config(args["config"]) url = config.get("api_server", {}).get("server_url", "127.0.0.1") port = config.get("api_server", {}).get("listen_port", "8080") @@ -174,13 +196,6 @@ def main(args): print(getattr(client, command)(*args["command_arguments"])) - # Call commands without arguments - # if args["command"] in COMMANDS_NO_ARGS: - # client._call_command_noargs(args["command"]) - - # if args["command"] in INFO_COMMANDS: - # client._call_info(args["command"], args["command_arguments"]) - if __name__ == "__main__": args = add_arguments() From 393e4ac90e0c435a37be62060c144835dae0b853 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 09:59:08 +0200 Subject: [PATCH 30/71] Sort methods --- freqtrade/rpc/api_server.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 1643bc535..009ae7d68 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -109,16 +109,18 @@ class ApiServer(RPC): app.add_url_rule('/reload_conf', 'reload_conf', view_func=self._reload_conf, methods=['POST']) # Info commands - app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) + app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) - app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) - app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, - methods=['GET']) + app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) + + # Combined actions and infos app.add_url_rule('/blacklist', 'blacklist', view_func=self._blacklist, methods=['GET', 'POST']) + app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, + methods=['GET']) # TODO: Implement the following # performance # forcebuy From b1964851c9d9bc7153abf6b93a774bf2a4873fd1 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 10:03:54 +0200 Subject: [PATCH 31/71] Add performance handlers --- freqtrade/rpc/api_server.py | 18 ++++++++++++++++-- scripts/rest_client.py | 9 ++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 009ae7d68..f63c68bf1 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -113,6 +113,8 @@ class ApiServer(RPC): app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) + app.add_url_rule('/performance', 'performance', view_func=self._performance, + methods=['GET']) app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) @@ -122,10 +124,8 @@ class ApiServer(RPC): app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, methods=['GET']) # TODO: Implement the following - # performance # forcebuy # forcesell - # blacklist params # edge # help (?) @@ -266,6 +266,20 @@ class ApiServer(RPC): return self.rest_dump(stats) + @safe_rpc + def _performance(self): + """ + Handler for /performance. + + Returns a cumulative performance statistics + :return: stats + """ + logger.info("LocalRPC - performance Command Called") + + stats = self._rpc_performance() + + return self.rest_dump(stats) + @safe_rpc def _status(self): """ diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 1958c1a07..7dbed9bc5 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -45,7 +45,7 @@ class FtRestClient(): # Split url schema, netloc, path, par, query, fragment = urlparse(basepath) # URLEncode query string - query = urlencode(params) if params else None + query = urlencode(params) if params else "" # recombine url url = urlunparse((schema, netloc, path, par, query, fragment)) @@ -92,6 +92,13 @@ class FtRestClient(): """ return self._get("profit") + def performance(self): + """ + Returns the performance of the different coins + :returns: json object + """ + return self._get("performance") + def status(self): """ Get the status of open trades From ea8b8eec1ca178ca151796f19aaef7c48bae7624 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 10:06:46 +0200 Subject: [PATCH 32/71] Add edge handler --- freqtrade/rpc/api_server.py | 12 +++++++++++- scripts/rest_client.py | 21 ++++++++++++++------- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index f63c68bf1..bde28be73 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -112,6 +112,7 @@ class ApiServer(RPC): app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) + app.add_url_rule('/edge', 'edge', view_func=self._edge, methods=['GET']) app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) app.add_url_rule('/performance', 'performance', view_func=self._performance, methods=['GET']) @@ -126,7 +127,6 @@ class ApiServer(RPC): # TODO: Implement the following # forcebuy # forcesell - # edge # help (?) def run(self): @@ -250,6 +250,16 @@ class ApiServer(RPC): return self.rest_dump(stats) + @safe_rpc + def _edge(self): + """ + Returns information related to Edge. + :return: edge stats + """ + stats = self._rpc_edge() + + return self.rest_dump(stats) + @safe_rpc def _profit(self): """ diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 7dbed9bc5..efca8adfa 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -85,6 +85,13 @@ class FtRestClient(): """ return self._get("daily", params={"timescale": days} if days else None) + def edge(self): + """ + Returns information about edge + :returns: json object + """ + return self._get("edge") + def profit(self): """ Returns the profit summary @@ -106,6 +113,13 @@ class FtRestClient(): """ return self._get("status") + def version(self): + """ + Returns the version of the bot + :returns: json object containing the version + """ + return self._get("version") + def whitelist(self): """ Show the current whitelist @@ -124,13 +138,6 @@ class FtRestClient(): else: return self._post("blacklist", data={"blacklist": args}) - def version(self): - """ - Returns the version of the bot - :returns: json object containing the version - """ - return self._get("version") - def add_arguments(): parser = argparse.ArgumentParser() From cb271f51d1f288cebaacb45572b6948b8f763d22 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 10:10:01 +0200 Subject: [PATCH 33/71] Add client actions for actions --- scripts/rest_client.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index efca8adfa..c8f5823a1 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -64,6 +64,35 @@ class FtRestClient(): def _post(self, apipath, params: dict = None, data: dict = None): return self._call("POST", apipath, params=params, data=data) + def start(self): + """ + Start the bot if it's in stopped state. + :returns: json object + """ + return self._post("start") + + def stop(self): + """ + Stop the bot. Use start to restart + :returns: json object + """ + return self._post("stop") + + def stopbuy(self): + """ + Stop buying (but handle sells gracefully). + use reload_conf to reset + :returns: json object + """ + return self._post("stopbuy") + + def reload_conf(self): + """ + Reload configuration + :returns: json object + """ + return self._post("reload_conf") + def balance(self): """ get the account balance From bc4342b2d0119ba5b9baa97ffddabe1e5669557a Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 10:12:39 +0200 Subject: [PATCH 34/71] small cleanup --- freqtrade/rpc/api_server.py | 7 +++---- scripts/rest_client.py | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index bde28be73..e158df0be 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -101,7 +101,6 @@ class ApiServer(RPC): Label can be used as a shortcut when refactoring :return: """ - # TODO: actions should not be GET... # Actions to control the bot app.add_url_rule('/start', 'start', view_func=self._start, methods=['POST']) app.add_url_rule('/stop', 'stop', view_func=self._stop, methods=['POST']) @@ -114,7 +113,7 @@ class ApiServer(RPC): app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) app.add_url_rule('/edge', 'edge', view_func=self._edge, methods=['GET']) app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) - app.add_url_rule('/performance', 'performance', view_func=self._performance, + app.add_url_rule('/performance', 'performance', view_func=self._performance, methods=['GET']) app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) @@ -141,8 +140,8 @@ class ApiServer(RPC): logger.info('Starting HTTP Server at {}:{}'.format(rest_ip, rest_port)) if not IPv4Address(rest_ip).is_loopback: - logger.info("SECURITY WARNING - Local Rest Server listening to external connections") - logger.info("SECURITY WARNING - This is insecure please set to your loopback," + logger.warning("SECURITY WARNING - Local Rest Server listening to external connections") + logger.warning("SECURITY WARNING - This is insecure please set to your loopback," "e.g 127.0.0.1 in config.json") # Run the Server diff --git a/scripts/rest_client.py b/scripts/rest_client.py index c8f5823a1..4830d43b8 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -95,7 +95,7 @@ class FtRestClient(): def balance(self): """ - get the account balance + Get the account balance :returns: json object """ return self._get("balance") From 6e4b159611128bce19111b0141ff8d5b6da8f61a Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 26 Apr 2019 12:50:13 +0200 Subject: [PATCH 35/71] Add forcebuy and forcesell --- freqtrade/rpc/api_server.py | 25 +++++++++++++++++++++++-- scripts/rest_client.py | 21 +++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index e158df0be..d47def4a6 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -123,9 +123,10 @@ class ApiServer(RPC): methods=['GET', 'POST']) app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, methods=['GET']) + app.add_url_rule('/forcebuy', 'forcebuy', view_func=self._forcebuy, methods=['POST']) + app.add_url_rule('/forcesell', 'forcesell', view_func=self._forcesell, methods=['POST']) + # TODO: Implement the following - # forcebuy - # forcesell # help (?) def run(self): @@ -325,3 +326,23 @@ class ApiServer(RPC): add = request.json.get("blacklist", None) if request.method == 'POST' else None results = self._rpc_blacklist(add) return self.rest_dump(results) + + @safe_rpc + def _forcebuy(self): + """ + Handler for /forcebuy. + """ + asset = request.json.get("pair") + price = request.json.get("price", None) + trade = self._rpc_forcebuy(asset, price) + # TODO: Returns a trade, we need to jsonify that. + return self.rest_dump(trade) + + @safe_rpc + def _forcesell(self): + """ + Handler for /forcesell. + """ + tradeid = request.json.get("tradeid") + results = self._rpc_forcesell(tradeid) + return self.rest_dump(results) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 4830d43b8..81c4b66cc 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -167,6 +167,27 @@ class FtRestClient(): else: return self._post("blacklist", data={"blacklist": args}) + def forcebuy(self, pair, price=None): + """ + Buy an asset + :param pair: Pair to buy (ETH/BTC) + :param price: Optional - price to buy + :returns: json object of the trade + """ + data = {"pair": pair, + "price": price + } + return self._post("forcebuy", data=data) + + def forcesell(self, tradeid): + """ + Force-sell a trade + :param tradeid: Id of the trade (can be received via status command) + :returns: json object + """ + + return self._post("forcesell", data={"tradeid": tradeid}) + def add_arguments(): parser = argparse.ArgumentParser() From 0ac434da78613714dc27300fee7f5750ae872cff Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 8 May 2019 07:12:37 +0200 Subject: [PATCH 36/71] Add forcebuy jsonification --- freqtrade/rpc/api_server.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index d47def4a6..be2f02663 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -335,8 +335,7 @@ class ApiServer(RPC): asset = request.json.get("pair") price = request.json.get("price", None) trade = self._rpc_forcebuy(asset, price) - # TODO: Returns a trade, we need to jsonify that. - return self.rest_dump(trade) + return self.rest_dump(trade.to_json()) @safe_rpc def _forcesell(self): From e0486ea68eb5e2243dbc8ae7125013e4827935af Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 10 May 2019 07:07:14 +0200 Subject: [PATCH 37/71] Make app a instance object --- freqtrade/rpc/api_server.py | 56 ++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index be2f02663..be6b20ecb 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -26,10 +26,6 @@ class ArrowJSONEncoder(JSONEncoder): return JSONEncoder.default(self, obj) -app = Flask(__name__) -app.json_encoder = ArrowJSONEncoder - - class ApiServer(RPC): """ This class runs api server and provides rpc.rpc functionality to it @@ -58,6 +54,9 @@ class ApiServer(RPC): super().__init__(freqtrade) self._config = freqtrade.config + self.app = Flask(__name__) + + self.app.json_encoder = ArrowJSONEncoder # Register application handling self.register_rest_other() @@ -90,8 +89,8 @@ class ApiServer(RPC): Registers flask app URLs that are not calls to functionality in rpc.rpc. :return: """ - app.register_error_handler(404, self.page_not_found) - app.add_url_rule('/', 'hello', view_func=self.hello, methods=['GET']) + self.app.register_error_handler(404, self.page_not_found) + self.app.add_url_rule('/', 'hello', view_func=self.hello, methods=['GET']) def register_rest_rpc_urls(self): """ @@ -102,29 +101,30 @@ class ApiServer(RPC): :return: """ # Actions to control the bot - app.add_url_rule('/start', 'start', view_func=self._start, methods=['POST']) - app.add_url_rule('/stop', 'stop', view_func=self._stop, methods=['POST']) - app.add_url_rule('/stopbuy', 'stopbuy', view_func=self._stopbuy, methods=['POST']) - app.add_url_rule('/reload_conf', 'reload_conf', view_func=self._reload_conf, - methods=['POST']) + self.app.add_url_rule('/start', 'start', view_func=self._start, methods=['POST']) + self.app.add_url_rule('/stop', 'stop', view_func=self._stop, methods=['POST']) + self.app.add_url_rule('/stopbuy', 'stopbuy', view_func=self._stopbuy, methods=['POST']) + self.app.add_url_rule('/reload_conf', 'reload_conf', view_func=self._reload_conf, + methods=['POST']) # Info commands - app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) - app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) - app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) - app.add_url_rule('/edge', 'edge', view_func=self._edge, methods=['GET']) - app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) - app.add_url_rule('/performance', 'performance', view_func=self._performance, - methods=['GET']) - app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) - app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) + self.app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) + self.app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) + self.app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) + self.app.add_url_rule('/edge', 'edge', view_func=self._edge, methods=['GET']) + self.app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) + self.app.add_url_rule('/performance', 'performance', view_func=self._performance, + methods=['GET']) + self.app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) + self.app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) # Combined actions and infos - app.add_url_rule('/blacklist', 'blacklist', view_func=self._blacklist, - methods=['GET', 'POST']) - app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, - methods=['GET']) - app.add_url_rule('/forcebuy', 'forcebuy', view_func=self._forcebuy, methods=['POST']) - app.add_url_rule('/forcesell', 'forcesell', view_func=self._forcesell, methods=['POST']) + self.app.add_url_rule('/blacklist', 'blacklist', view_func=self._blacklist, + methods=['GET', 'POST']) + self.app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, + methods=['GET']) + self.app.add_url_rule('/forcebuy', 'forcebuy', view_func=self._forcebuy, methods=['POST']) + self.app.add_url_rule('/forcesell', 'forcesell', view_func=self._forcesell, + methods=['POST']) # TODO: Implement the following # help (?) @@ -143,12 +143,12 @@ class ApiServer(RPC): if not IPv4Address(rest_ip).is_loopback: logger.warning("SECURITY WARNING - Local Rest Server listening to external connections") logger.warning("SECURITY WARNING - This is insecure please set to your loopback," - "e.g 127.0.0.1 in config.json") + "e.g 127.0.0.1 in config.json") # Run the Server logger.info('Starting Local Rest Server') try: - app.run(host=rest_ip, port=rest_port) + self.app.run(host=rest_ip, port=rest_port) except Exception: logger.exception("Api server failed to start, exception message is:") logger.info('Starting Local Rest Server_end') From b1a14401c2ee83cd3f61ecc6c3a99dac6cd5e9ef Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 10 May 2019 07:07:38 +0200 Subject: [PATCH 38/71] Add some initial tests for apiserver --- freqtrade/tests/rpc/test_rpc_apiserver.py | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 14c35a38e..fae278028 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -4,11 +4,37 @@ Unit test file for rpc/api_server.py from unittest.mock import MagicMock +import pytest + from freqtrade.rpc.api_server import ApiServer from freqtrade.state import State from freqtrade.tests.conftest import get_patched_freqtradebot, patch_apiserver +@pytest.fixture +def client(default_conf, mocker): + apiserver = ApiServer(get_patched_freqtradebot(mocker, default_conf)) + yield apiserver.app.test_client() + # Cleanup ... ? + + +def response_success_assert(response): + assert response.status_code == 200 + assert response.content_type == "application/json" + + +def test_start(client): + rc = client.post("/start") + response_success_assert(rc) + assert rc.json == {'status': 'already running'} + + +def test_stop(client): + rc = client.post("/stop") + response_success_assert(rc) + assert rc.json == {'status': 'stopping trader ...'} + + def test__init__(default_conf, mocker): """ Test __init__() method From 6ea08958032d65efec043f5b1f395bb549977ad1 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 08:55:10 +0200 Subject: [PATCH 39/71] Fix docstrings --- freqtrade/rpc/api_server.py | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index be6b20ecb..18c68e797 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -130,9 +130,7 @@ class ApiServer(RPC): # help (?) def run(self): - """ Method that runs flask app in its own thread forever """ - - """ + """ Method that runs flask app in its own thread forever. Section to handle configuration and running of the Rest server also to check and warn if not bound to a loopback, warn on security risk. """ @@ -153,11 +151,6 @@ class ApiServer(RPC): logger.exception("Api server failed to start, exception message is:") logger.info('Starting Local Rest Server_end') - """ - Define the application methods here, called by app.add_url_rule - each Telegram command should have a like local substitute - """ - def page_not_found(self, error): """ Return "404 not found", 404. From 70a3c2c648f5aa3c0c09ea650241aed7dea63c84 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 08:55:21 +0200 Subject: [PATCH 40/71] Actions - Add tests --- freqtrade/tests/rpc/test_rpc_apiserver.py | 75 ++++++++++++----------- 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index fae278028..8062171c5 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -12,9 +12,10 @@ from freqtrade.tests.conftest import get_patched_freqtradebot, patch_apiserver @pytest.fixture -def client(default_conf, mocker): - apiserver = ApiServer(get_patched_freqtradebot(mocker, default_conf)) - yield apiserver.app.test_client() +def botclient(default_conf, mocker): + ftbot = get_patched_freqtradebot(mocker, default_conf) + apiserver = ApiServer(ftbot) + yield ftbot, apiserver.app.test_client() # Cleanup ... ? @@ -23,19 +24,32 @@ def response_success_assert(response): assert response.content_type == "application/json" -def test_start(client): +def test_api_stop_workflow(botclient): + ftbot, client = botclient + assert ftbot.state == State.RUNNING + rc = client.post("/stop") + response_success_assert(rc) + assert rc.json == {'status': 'stopping trader ...'} + assert ftbot.state == State.STOPPED + + # Stop bot again + rc = client.post("/stop") + response_success_assert(rc) + assert rc.json == {'status': 'already stopped'} + + # Start bot + rc = client.post("/start") + response_success_assert(rc) + assert rc.json == {'status': 'starting trader ...'} + assert ftbot.state == State.RUNNING + + # Call start again rc = client.post("/start") response_success_assert(rc) assert rc.json == {'status': 'already running'} -def test_stop(client): - rc = client.post("/stop") - response_success_assert(rc) - assert rc.json == {'status': 'stopping trader ...'} - - -def test__init__(default_conf, mocker): +def test_api__init__(default_conf, mocker): """ Test __init__() method """ @@ -46,33 +60,20 @@ def test__init__(default_conf, mocker): assert apiserver._config == default_conf -def test_start_endpoint(default_conf, mocker): - """Test /start endpoint""" - patch_apiserver(mocker) - bot = get_patched_freqtradebot(mocker, default_conf) - apiserver = ApiServer(bot) +def test_api_reloadconf(botclient): + ftbot, client = botclient - bot.state = State.STOPPED - assert bot.state == State.STOPPED - result = apiserver.start() - assert result == '{"status": "starting trader ..."}' - assert bot.state == State.RUNNING - - result = apiserver.start() - assert result == '{"status": "already running"}' + rc = client.post("/reload_conf") + response_success_assert(rc) + assert rc.json == {'status': 'reloading config ...'} + assert ftbot.state == State.RELOAD_CONF -def test_stop_endpoint(default_conf, mocker): - """Test /stop endpoint""" - patch_apiserver(mocker) - bot = get_patched_freqtradebot(mocker, default_conf) - apiserver = ApiServer(bot) +def test_api_stopbuy(botclient): + ftbot, client = botclient + assert ftbot.config['max_open_trades'] != 0 - bot.state = State.RUNNING - assert bot.state == State.RUNNING - result = apiserver.stop() - assert result == '{"status": "stopping trader ..."}' - assert bot.state == State.STOPPED - - result = apiserver.stop() - assert result == '{"status": "already stopped"}' + rc = client.post("/stopbuy") + response_success_assert(rc) + assert rc.json == {'status': 'No more buy will occur from now. Run /reload_conf to reset.'} + assert ftbot.config['max_open_trades'] == 0 From 6b426e78f60745fec291ecd192cb00837bee3374 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 09:10:54 +0200 Subject: [PATCH 41/71] Tests for balance --- freqtrade/tests/conftest.py | 36 ++++++++++++++++++++++ freqtrade/tests/rpc/test_rpc_apiserver.py | 37 +++++++++++++++++++++++ freqtrade/tests/rpc/test_rpc_telegram.py | 36 ++-------------------- 3 files changed, 75 insertions(+), 34 deletions(-) diff --git a/freqtrade/tests/conftest.py b/freqtrade/tests/conftest.py index 98563a374..a4eae4300 100644 --- a/freqtrade/tests/conftest.py +++ b/freqtrade/tests/conftest.py @@ -970,3 +970,39 @@ def edge_conf(default_conf): } return default_conf + + +@pytest.fixture +def rpc_balance(): + return { + 'BTC': { + 'total': 12.0, + 'free': 12.0, + 'used': 0.0 + }, + 'ETH': { + 'total': 0.0, + 'free': 0.0, + 'used': 0.0 + }, + 'USDT': { + 'total': 10000.0, + 'free': 10000.0, + 'used': 0.0 + }, + 'LTC': { + 'total': 10.0, + 'free': 10.0, + 'used': 0.0 + }, + 'XRP': { + 'total': 1.0, + 'free': 1.0, + 'used': 0.0 + }, + 'EUR': { + 'total': 10.0, + 'free': 10.0, + 'used': 0.0 + }, + } diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 8062171c5..7e99a9510 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -77,3 +77,40 @@ def test_api_stopbuy(botclient): response_success_assert(rc) assert rc.json == {'status': 'No more buy will occur from now. Run /reload_conf to reset.'} assert ftbot.config['max_open_trades'] == 0 + + +def test_api_balance(botclient, mocker, rpc_balance): + ftbot, client = botclient + + def mock_ticker(symbol, refresh): + if symbol == 'BTC/USDT': + return { + 'bid': 10000.00, + 'ask': 10000.00, + 'last': 10000.00, + } + elif symbol == 'XRP/BTC': + return { + 'bid': 0.00001, + 'ask': 0.00001, + 'last': 0.00001, + } + return { + 'bid': 0.1, + 'ask': 0.1, + 'last': 0.1, + } + mocker.patch('freqtrade.exchange.Exchange.get_balances', return_value=rpc_balance) + mocker.patch('freqtrade.exchange.Exchange.get_ticker', side_effect=mock_ticker) + + rc = client.get("/balance") + response_success_assert(rc) + assert "currencies" in rc.json + assert len(rc.json["currencies"]) == 5 + assert rc.json['currencies'][0] == { + 'currency': 'BTC', + 'available': 12.0, + 'balance': 12.0, + 'pending': 0.0, + 'est_btc': 12.0, + } diff --git a/freqtrade/tests/rpc/test_rpc_telegram.py b/freqtrade/tests/rpc/test_rpc_telegram.py index 69e3006cd..b8e57d092 100644 --- a/freqtrade/tests/rpc/test_rpc_telegram.py +++ b/freqtrade/tests/rpc/test_rpc_telegram.py @@ -496,39 +496,7 @@ def test_profit_handle(default_conf, update, ticker, ticker_sell_up, fee, assert '*Best Performing:* `ETH/BTC: 6.20%`' in msg_mock.call_args_list[-1][0][0] -def test_telegram_balance_handle(default_conf, update, mocker) -> None: - mock_balance = { - 'BTC': { - 'total': 12.0, - 'free': 12.0, - 'used': 0.0 - }, - 'ETH': { - 'total': 0.0, - 'free': 0.0, - 'used': 0.0 - }, - 'USDT': { - 'total': 10000.0, - 'free': 10000.0, - 'used': 0.0 - }, - 'LTC': { - 'total': 10.0, - 'free': 10.0, - 'used': 0.0 - }, - 'XRP': { - 'total': 1.0, - 'free': 1.0, - 'used': 0.0 - }, - 'EUR': { - 'total': 10.0, - 'free': 10.0, - 'used': 0.0 - } - } +def test_telegram_balance_handle(default_conf, update, mocker, rpc_balance) -> None: def mock_ticker(symbol, refresh): if symbol == 'BTC/USDT': @@ -549,7 +517,7 @@ def test_telegram_balance_handle(default_conf, update, mocker) -> None: 'last': 0.1, } - mocker.patch('freqtrade.exchange.Exchange.get_balances', return_value=mock_balance) + mocker.patch('freqtrade.exchange.Exchange.get_balances', return_value=rpc_balance) mocker.patch('freqtrade.exchange.Exchange.get_ticker', side_effect=mock_ticker) msg_mock = MagicMock() From 88dd18e045bc0bae78c3b7203674842d4485c484 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 09:42:30 +0200 Subject: [PATCH 42/71] Move patch_signal to conftest --- freqtrade/tests/conftest.py | 13 +++++++++++-- freqtrade/tests/rpc/test_rpc.py | 3 +-- freqtrade/tests/rpc/test_rpc_telegram.py | 3 +-- freqtrade/tests/test_freqtradebot.py | 11 +---------- 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/freqtrade/tests/conftest.py b/freqtrade/tests/conftest.py index a4eae4300..c9b98aacd 100644 --- a/freqtrade/tests/conftest.py +++ b/freqtrade/tests/conftest.py @@ -10,7 +10,7 @@ import arrow import pytest from telegram import Chat, Message, Update -from freqtrade import constants +from freqtrade import constants, persistence from freqtrade.data.converter import parse_ticker_dataframe from freqtrade.edge import Edge, PairInfo from freqtrade.exchange import Exchange @@ -96,7 +96,7 @@ def patch_freqtradebot(mocker, config) -> None: :return: None """ mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock()) - mocker.patch('freqtrade.freqtradebot.persistence.init', MagicMock()) + persistence.init(config) patch_exchange(mocker, None) mocker.patch('freqtrade.freqtradebot.RPCManager._init', MagicMock()) mocker.patch('freqtrade.freqtradebot.RPCManager.send_msg', MagicMock()) @@ -112,6 +112,15 @@ def get_patched_worker(mocker, config) -> Worker: return Worker(args=None, config=config) +def patch_get_signal(freqtrade: FreqtradeBot, value=(True, False)) -> None: + """ + :param mocker: mocker to patch IStrategy class + :param value: which value IStrategy.get_signal() must return + :return: None + """ + freqtrade.strategy.get_signal = lambda e, s, t: value + freqtrade.exchange.refresh_latest_ohlcv = lambda p: None + @pytest.fixture(autouse=True) def patch_coinmarketcap(mocker) -> None: """ diff --git a/freqtrade/tests/rpc/test_rpc.py b/freqtrade/tests/rpc/test_rpc.py index 6ce543f3d..f005041d9 100644 --- a/freqtrade/tests/rpc/test_rpc.py +++ b/freqtrade/tests/rpc/test_rpc.py @@ -14,8 +14,7 @@ from freqtrade.persistence import Trade from freqtrade.rpc import RPC, RPCException from freqtrade.rpc.fiat_convert import CryptoToFiatConverter from freqtrade.state import State -from freqtrade.tests.conftest import patch_exchange -from freqtrade.tests.test_freqtradebot import patch_get_signal +from freqtrade.tests.conftest import patch_exchange, patch_get_signal # Functions for recurrent object patching diff --git a/freqtrade/tests/rpc/test_rpc_telegram.py b/freqtrade/tests/rpc/test_rpc_telegram.py index b8e57d092..46ef15f56 100644 --- a/freqtrade/tests/rpc/test_rpc_telegram.py +++ b/freqtrade/tests/rpc/test_rpc_telegram.py @@ -22,8 +22,7 @@ from freqtrade.rpc.telegram import Telegram, authorized_only from freqtrade.state import State from freqtrade.strategy.interface import SellType from freqtrade.tests.conftest import (get_patched_freqtradebot, log_has, - patch_exchange) -from freqtrade.tests.test_freqtradebot import patch_get_signal + patch_exchange, patch_get_signal) class DummyCls(Telegram): diff --git a/freqtrade/tests/test_freqtradebot.py b/freqtrade/tests/test_freqtradebot.py index 67b05ac3e..946a9c819 100644 --- a/freqtrade/tests/test_freqtradebot.py +++ b/freqtrade/tests/test_freqtradebot.py @@ -19,7 +19,7 @@ from freqtrade.persistence import Trade from freqtrade.rpc import RPCMessageType from freqtrade.state import State from freqtrade.strategy.interface import SellCheckTuple, SellType -from freqtrade.tests.conftest import (log_has, log_has_re, patch_edge, +from freqtrade.tests.conftest import (log_has, log_has_re, patch_edge, patch_get_signal, patch_exchange, patch_wallet) from freqtrade.worker import Worker @@ -59,15 +59,6 @@ def get_patched_worker(mocker, config) -> Worker: return Worker(args=None, config=config) -def patch_get_signal(freqtrade: FreqtradeBot, value=(True, False)) -> None: - """ - :param mocker: mocker to patch IStrategy class - :param value: which value IStrategy.get_signal() must return - :return: None - """ - freqtrade.strategy.get_signal = lambda e, s, t: value - freqtrade.exchange.refresh_latest_ohlcv = lambda p: None - def patch_RPCManager(mocker) -> MagicMock: """ From 3c468701093e67f64b663dedbc36f56ac4531e64 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 09:44:39 +0200 Subject: [PATCH 43/71] Test /count for api-server --- freqtrade/tests/rpc/test_rpc_apiserver.py | 41 +++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 7e99a9510..3590b0dc8 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -2,18 +2,23 @@ Unit test file for rpc/api_server.py """ -from unittest.mock import MagicMock +from unittest.mock import MagicMock, PropertyMock import pytest +from freqtrade.__init__ import __version__ from freqtrade.rpc.api_server import ApiServer from freqtrade.state import State -from freqtrade.tests.conftest import get_patched_freqtradebot, patch_apiserver +from freqtrade.tests.conftest import get_patched_freqtradebot, patch_apiserver, patch_get_signal @pytest.fixture def botclient(default_conf, mocker): + default_conf.update({"api_server":{"enabled": True, + "listen_ip_address": "127.0.0.1", + "listen_port": "8080"}}) ftbot = get_patched_freqtradebot(mocker, default_conf) + mocker.patch('freqtrade.rpc.api_server.ApiServer.run', MagicMock()) apiserver = ApiServer(ftbot) yield ftbot, apiserver.app.test_client() # Cleanup ... ? @@ -79,6 +84,14 @@ def test_api_stopbuy(botclient): assert ftbot.config['max_open_trades'] == 0 +def test_api_version(botclient): + ftbot, client = botclient + + rc = client.get("/version") + response_success_assert(rc) + assert rc.json == {"version": __version__} + + def test_api_balance(botclient, mocker, rpc_balance): ftbot, client = botclient @@ -114,3 +127,27 @@ def test_api_balance(botclient, mocker, rpc_balance): 'pending': 0.0, 'est_btc': 12.0, } + + +def test_api_count(botclient, mocker, ticker, fee, markets): + ftbot, client = botclient + patch_get_signal(ftbot, (True, False)) + mocker.patch.multiple( + 'freqtrade.exchange.Exchange', + get_balances=MagicMock(return_value=ticker), + get_ticker=ticker, + get_fee=fee, + markets=PropertyMock(return_value=markets) + ) + rc = client.get("/count") + response_success_assert(rc) + + assert rc.json["current"] == 0 + assert rc.json["max"] == 1.0 + + # Create some test data + ftbot.create_trade() + rc = client.get("/count") + response_success_assert(rc) + assert rc.json["current"] == 1.0 + assert rc.json["max"] == 1.0 From 03dc6d92aeb1371ff80562971a82700c386fac4b Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 13:10:41 +0200 Subject: [PATCH 44/71] Remove hello() --- freqtrade/rpc/api_server.py | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 18c68e797..5b7da902d 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -90,7 +90,6 @@ class ApiServer(RPC): :return: """ self.app.register_error_handler(404, self.page_not_found) - self.app.add_url_rule('/', 'hello', view_func=self.hello, methods=['GET']) def register_rest_rpc_urls(self): """ @@ -161,24 +160,6 @@ class ApiServer(RPC): 'code': 404 }), 404 - def hello(self): - """ - None critical but helpful default index page. - - That lists URLs added to the flask server. - This may be deprecated at any time. - :return: index.html - """ - rest_cmds = ('Commands implemented:
' - 'Show 7 days of stats
' - 'Stop the Trade thread
' - 'Start the Traded thread
' - 'Show profit summary
' - 'Show status table - Open trades
' - ' 404 page does not exist
' - ) - return rest_cmds - def _start(self): """ Handler for /start. From 557f849519ef144693135f2f5f51404c28f3bd7f Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 13:18:11 +0200 Subject: [PATCH 45/71] Improve 404 handling --- freqtrade/rpc/api_server.py | 2 +- freqtrade/tests/rpc/test_rpc_apiserver.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 5b7da902d..573f89143 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -156,7 +156,7 @@ class ApiServer(RPC): """ return self.rest_dump({ 'status': 'error', - 'reason': '''There's no API call for %s''' % request.base_url, + 'reason': f"There's no API call for {request.base_url}.", 'code': 404 }), 404 diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 3590b0dc8..52a456d68 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -29,6 +29,18 @@ def response_success_assert(response): assert response.content_type == "application/json" +def test_api_not_found(botclient): + ftbot, client = botclient + + rc = client.post("/invalid_url") + assert rc.status_code == 404 + assert rc.content_type == "application/json" + assert rc.json == {'status': 'error', + 'reason': "There's no API call for http://localhost/invalid_url.", + 'code': 404 + } + + def test_api_stop_workflow(botclient): ftbot, client = botclient assert ftbot.state == State.RUNNING From a146c5bf7820402470440620eae26f4f145743e8 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 13:31:48 +0200 Subject: [PATCH 46/71] Improve jsonification --- freqtrade/rpc/api_server.py | 5 +++++ freqtrade/tests/rpc/test_rpc_apiserver.py | 22 ++++++++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 573f89143..4ddda307a 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -1,5 +1,6 @@ import logging import threading +from datetime import datetime, date from ipaddress import IPv4Address from typing import Dict @@ -18,6 +19,10 @@ class ArrowJSONEncoder(JSONEncoder): try: if isinstance(obj, Arrow): return obj.for_json() + elif isinstance(obj, date): + return obj.strftime("%Y-%m-%d") + elif isinstance(obj, datetime): + return obj.strftime("%Y-%m-%d %H:%M:%S") iterable = iter(obj) except TypeError: pass diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 52a456d68..cefbb9acd 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -2,6 +2,7 @@ Unit test file for rpc/api_server.py """ +from datetime import datetime from unittest.mock import MagicMock, PropertyMock import pytest @@ -9,12 +10,13 @@ import pytest from freqtrade.__init__ import __version__ from freqtrade.rpc.api_server import ApiServer from freqtrade.state import State -from freqtrade.tests.conftest import get_patched_freqtradebot, patch_apiserver, patch_get_signal +from freqtrade.tests.conftest import (get_patched_freqtradebot, + patch_apiserver, patch_get_signal) @pytest.fixture def botclient(default_conf, mocker): - default_conf.update({"api_server":{"enabled": True, + default_conf.update({"api_server": {"enabled": True, "listen_ip_address": "127.0.0.1", "listen_port": "8080"}}) ftbot = get_patched_freqtradebot(mocker, default_conf) @@ -163,3 +165,19 @@ def test_api_count(botclient, mocker, ticker, fee, markets): response_success_assert(rc) assert rc.json["current"] == 1.0 assert rc.json["max"] == 1.0 + + +def test_api_daily(botclient, mocker, ticker, fee, markets): + ftbot, client = botclient + patch_get_signal(ftbot, (True, False)) + mocker.patch.multiple( + 'freqtrade.exchange.Exchange', + get_balances=MagicMock(return_value=ticker), + get_ticker=ticker, + get_fee=fee, + markets=PropertyMock(return_value=markets) + ) + rc = client.get("/daily") + response_success_assert(rc) + assert len(rc.json) == 7 + assert rc.json[0][0] == str(datetime.utcnow().date()) From a7329e5cc945efb005e02685d66d7b8b65ed56cb Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 13:40:30 +0200 Subject: [PATCH 47/71] Test api-server start from manager --- freqtrade/tests/conftest.py | 9 ------- freqtrade/tests/rpc/test_rpc_apiserver.py | 7 +++--- freqtrade/tests/rpc/test_rpc_manager.py | 29 +++++++++++++++++++++++ 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/freqtrade/tests/conftest.py b/freqtrade/tests/conftest.py index c9b98aacd..bb8bd9c95 100644 --- a/freqtrade/tests/conftest.py +++ b/freqtrade/tests/conftest.py @@ -143,15 +143,6 @@ def patch_coinmarketcap(mocker) -> None: ) -def patch_apiserver(mocker) -> None: - mocker.patch.multiple( - 'freqtrade.rpc.api_server.ApiServer', - run=MagicMock(), - register_rest_other=MagicMock(), - register_rest_rpc_urls=MagicMock(), - ) - - @pytest.fixture(scope="function") def default_conf(): """ Returns validated configuration suitable for most tests """ diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index cefbb9acd..34fe558f8 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -10,15 +10,14 @@ import pytest from freqtrade.__init__ import __version__ from freqtrade.rpc.api_server import ApiServer from freqtrade.state import State -from freqtrade.tests.conftest import (get_patched_freqtradebot, - patch_apiserver, patch_get_signal) +from freqtrade.tests.conftest import (get_patched_freqtradebot, patch_get_signal) @pytest.fixture def botclient(default_conf, mocker): default_conf.update({"api_server": {"enabled": True, - "listen_ip_address": "127.0.0.1", - "listen_port": "8080"}}) + "listen_ip_address": "127.0.0.1", + "listen_port": "8080"}}) ftbot = get_patched_freqtradebot(mocker, default_conf) mocker.patch('freqtrade.rpc.api_server.ApiServer.run', MagicMock()) apiserver = ApiServer(ftbot) diff --git a/freqtrade/tests/rpc/test_rpc_manager.py b/freqtrade/tests/rpc/test_rpc_manager.py index 15d9c20c6..91fd2297f 100644 --- a/freqtrade/tests/rpc/test_rpc_manager.py +++ b/freqtrade/tests/rpc/test_rpc_manager.py @@ -135,3 +135,32 @@ def test_startupmessages_telegram_enabled(mocker, default_conf, caplog) -> None: rpc_manager.startup_messages(default_conf, freqtradebot.pairlists) assert telegram_mock.call_count == 3 assert "Dry run is enabled." in telegram_mock.call_args_list[0][0][0]['status'] + + +def test_init_apiserver_disabled(mocker, default_conf, caplog) -> None: + caplog.set_level(logging.DEBUG) + run_mock = MagicMock() + mocker.patch('freqtrade.rpc.api_server.ApiServer.run', run_mock) + default_conf['telegram']['enabled'] = False + rpc_manager = RPCManager(get_patched_freqtradebot(mocker, default_conf)) + + assert not log_has('Enabling rpc.api_server', caplog.record_tuples) + assert rpc_manager.registered_modules == [] + assert run_mock.call_count == 0 + + +def test_init_apiserver_enabled(mocker, default_conf, caplog) -> None: + caplog.set_level(logging.DEBUG) + run_mock = MagicMock() + mocker.patch('freqtrade.rpc.api_server.ApiServer.run', run_mock) + + default_conf["telegram"]["enabled"] = False + default_conf["api_server"] = {"enabled": True, + "listen_ip_address": "127.0.0.1", + "listen_port": "8080"} + rpc_manager = RPCManager(get_patched_freqtradebot(mocker, default_conf)) + + assert log_has('Enabling rpc.api_server', caplog.record_tuples) + assert len(rpc_manager.registered_modules) == 1 + assert 'apiserver' in [mod.name for mod in rpc_manager.registered_modules] + assert run_mock.call_count == 1 From b9435e3ceac2342e8aa853c7c9f1247f66a8790a Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 May 2019 14:05:25 +0200 Subject: [PATCH 48/71] Add more tests --- freqtrade/tests/conftest.py | 1 + freqtrade/tests/rpc/test_rpc_apiserver.py | 220 +++++++++++++++++++--- freqtrade/tests/test_freqtradebot.py | 10 +- 3 files changed, 203 insertions(+), 28 deletions(-) diff --git a/freqtrade/tests/conftest.py b/freqtrade/tests/conftest.py index bb8bd9c95..59989d604 100644 --- a/freqtrade/tests/conftest.py +++ b/freqtrade/tests/conftest.py @@ -121,6 +121,7 @@ def patch_get_signal(freqtrade: FreqtradeBot, value=(True, False)) -> None: freqtrade.strategy.get_signal = lambda e, s, t: value freqtrade.exchange.refresh_latest_ohlcv = lambda p: None + @pytest.fixture(autouse=True) def patch_coinmarketcap(mocker) -> None: """ diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 34fe558f8..95ad7dbc3 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -3,7 +3,7 @@ Unit test file for rpc/api_server.py """ from datetime import datetime -from unittest.mock import MagicMock, PropertyMock +from unittest.mock import ANY, MagicMock, PropertyMock import pytest @@ -11,6 +11,7 @@ from freqtrade.__init__ import __version__ from freqtrade.rpc.api_server import ApiServer from freqtrade.state import State from freqtrade.tests.conftest import (get_patched_freqtradebot, patch_get_signal) +from freqtrade.persistence import Trade @pytest.fixture @@ -25,8 +26,8 @@ def botclient(default_conf, mocker): # Cleanup ... ? -def response_success_assert(response): - assert response.status_code == 200 +def assert_response(response, expected_code=200): + assert response.status_code == expected_code assert response.content_type == "application/json" @@ -34,8 +35,7 @@ def test_api_not_found(botclient): ftbot, client = botclient rc = client.post("/invalid_url") - assert rc.status_code == 404 - assert rc.content_type == "application/json" + assert_response(rc, 404) assert rc.json == {'status': 'error', 'reason': "There's no API call for http://localhost/invalid_url.", 'code': 404 @@ -46,24 +46,24 @@ def test_api_stop_workflow(botclient): ftbot, client = botclient assert ftbot.state == State.RUNNING rc = client.post("/stop") - response_success_assert(rc) + assert_response(rc) assert rc.json == {'status': 'stopping trader ...'} assert ftbot.state == State.STOPPED # Stop bot again rc = client.post("/stop") - response_success_assert(rc) + assert_response(rc) assert rc.json == {'status': 'already stopped'} # Start bot rc = client.post("/start") - response_success_assert(rc) + assert_response(rc) assert rc.json == {'status': 'starting trader ...'} assert ftbot.state == State.RUNNING # Call start again rc = client.post("/start") - response_success_assert(rc) + assert_response(rc) assert rc.json == {'status': 'already running'} @@ -82,7 +82,7 @@ def test_api_reloadconf(botclient): ftbot, client = botclient rc = client.post("/reload_conf") - response_success_assert(rc) + assert_response(rc) assert rc.json == {'status': 'reloading config ...'} assert ftbot.state == State.RELOAD_CONF @@ -92,19 +92,11 @@ def test_api_stopbuy(botclient): assert ftbot.config['max_open_trades'] != 0 rc = client.post("/stopbuy") - response_success_assert(rc) + assert_response(rc) assert rc.json == {'status': 'No more buy will occur from now. Run /reload_conf to reset.'} assert ftbot.config['max_open_trades'] == 0 -def test_api_version(botclient): - ftbot, client = botclient - - rc = client.get("/version") - response_success_assert(rc) - assert rc.json == {"version": __version__} - - def test_api_balance(botclient, mocker, rpc_balance): ftbot, client = botclient @@ -130,7 +122,7 @@ def test_api_balance(botclient, mocker, rpc_balance): mocker.patch('freqtrade.exchange.Exchange.get_ticker', side_effect=mock_ticker) rc = client.get("/balance") - response_success_assert(rc) + assert_response(rc) assert "currencies" in rc.json assert len(rc.json["currencies"]) == 5 assert rc.json['currencies'][0] == { @@ -153,7 +145,7 @@ def test_api_count(botclient, mocker, ticker, fee, markets): markets=PropertyMock(return_value=markets) ) rc = client.get("/count") - response_success_assert(rc) + assert_response(rc) assert rc.json["current"] == 0 assert rc.json["max"] == 1.0 @@ -161,7 +153,7 @@ def test_api_count(botclient, mocker, ticker, fee, markets): # Create some test data ftbot.create_trade() rc = client.get("/count") - response_success_assert(rc) + assert_response(rc) assert rc.json["current"] == 1.0 assert rc.json["max"] == 1.0 @@ -177,6 +169,188 @@ def test_api_daily(botclient, mocker, ticker, fee, markets): markets=PropertyMock(return_value=markets) ) rc = client.get("/daily") - response_success_assert(rc) + assert_response(rc) assert len(rc.json) == 7 assert rc.json[0][0] == str(datetime.utcnow().date()) + + +def test_api_edge_disabled(botclient, mocker, ticker, fee, markets): + ftbot, client = botclient + patch_get_signal(ftbot, (True, False)) + mocker.patch.multiple( + 'freqtrade.exchange.Exchange', + get_balances=MagicMock(return_value=ticker), + get_ticker=ticker, + get_fee=fee, + markets=PropertyMock(return_value=markets) + ) + rc = client.get("/edge") + assert_response(rc, 502) + assert rc.json == {"error": "Error querying _edge: Edge is not enabled."} + + +def test_api_profit(botclient, mocker, ticker, fee, markets, limit_buy_order, limit_sell_order): + ftbot, client = botclient + patch_get_signal(ftbot, (True, False)) + mocker.patch.multiple( + 'freqtrade.exchange.Exchange', + get_balances=MagicMock(return_value=ticker), + get_ticker=ticker, + get_fee=fee, + markets=PropertyMock(return_value=markets) + ) + + rc = client.get("/profit") + assert_response(rc, 502) + assert len(rc.json) == 1 + assert rc.json == {"error": "Error querying _profit: no closed trade"} + + ftbot.create_trade() + trade = Trade.query.first() + + # Simulate fulfilled LIMIT_BUY order for trade + trade.update(limit_buy_order) + rc = client.get("/profit") + assert_response(rc, 502) + assert rc.json == {"error": "Error querying _profit: no closed trade"} + + trade.update(limit_sell_order) + + trade.close_date = datetime.utcnow() + trade.is_open = False + + rc = client.get("/profit") + assert_response(rc) + assert rc.json == {'avg_duration': '0:00:00', + 'best_pair': 'ETH/BTC', + 'best_rate': 6.2, + 'first_trade_date': 'just now', + 'latest_trade_date': 'just now', + 'profit_all_coin': 6.217e-05, + 'profit_all_fiat': 0, + 'profit_all_percent': 6.2, + 'profit_closed_coin': 6.217e-05, + 'profit_closed_fiat': 0, + 'profit_closed_percent': 6.2, + 'trade_count': 1 + } + + +def test_api_performance(botclient, mocker, ticker, fee, markets): + ftbot, client = botclient + patch_get_signal(ftbot, (True, False)) + + trade = Trade( + pair='LTC/ETH', + amount=1, + exchange='binance', + stake_amount=1, + open_rate=0.245441, + open_order_id="123456", + is_open=False, + fee_close=fee.return_value, + fee_open=fee.return_value, + close_rate=0.265441, + + ) + trade.close_profit = trade.calc_profit_percent() + Trade.session.add(trade) + + trade = Trade( + pair='XRP/ETH', + amount=5, + stake_amount=1, + exchange='binance', + open_rate=0.412, + open_order_id="123456", + is_open=False, + fee_close=fee.return_value, + fee_open=fee.return_value, + close_rate=0.391 + ) + trade.close_profit = trade.calc_profit_percent() + Trade.session.add(trade) + Trade.session.flush() + + rc = client.get("/performance") + assert_response(rc) + assert len(rc.json) == 2 + assert rc.json == [{'count': 1, 'pair': 'LTC/ETH', 'profit': 7.61}, + {'count': 1, 'pair': 'XRP/ETH', 'profit': -5.57}] + + +def test_api_status(botclient, mocker, ticker, fee, markets, limit_buy_order, limit_sell_order): + ftbot, client = botclient + patch_get_signal(ftbot, (True, False)) + mocker.patch.multiple( + 'freqtrade.exchange.Exchange', + get_balances=MagicMock(return_value=ticker), + get_ticker=ticker, + get_fee=fee, + markets=PropertyMock(return_value=markets) + ) + + rc = client.get("/status") + assert_response(rc, 502) + assert rc.json == {'error': 'Error querying _status: no active trade'} + + ftbot.create_trade() + rc = client.get("/status") + assert_response(rc) + assert len(rc.json) == 1 + assert rc.json == [{'amount': 90.99181074, + 'base_currency': 'BTC', + 'close_date': None, + 'close_date_hum': None, + 'close_profit': None, + 'close_rate': None, + 'current_profit': -0.59, + 'current_rate': 1.098e-05, + 'initial_stop_loss': 0.0, + 'initial_stop_loss_pct': None, + 'open_date': ANY, + 'open_date_hum': 'just now', + 'open_order': '(limit buy rem=0.00000000)', + 'open_rate': 1.099e-05, + 'pair': 'ETH/BTC', + 'stake_amount': 0.001, + 'stop_loss': 0.0, + 'stop_loss_pct': None, + 'trade_id': 1}] + + +def test_api_version(botclient): + ftbot, client = botclient + + rc = client.get("/version") + assert_response(rc) + assert rc.json == {"version": __version__} + + +def test_api_blacklist(botclient, mocker, ticker, fee, markets): + ftbot, client = botclient + + rc = client.get("/blacklist") + assert_response(rc) + assert rc.json == {"blacklist": ["DOGE/BTC", "HOT/BTC"], + "length": 2, + "method": "StaticPairList"} + + # Add ETH/BTC to blacklist + rc = client.post("/blacklist", data='{"blacklist": ["ETH/BTC"]}', + content_type='application/json') + assert_response(rc) + assert rc.json == {"blacklist": ["DOGE/BTC", "HOT/BTC", "ETH/BTC"], + "length": 3, + "method": "StaticPairList"} + + +def test_api_whitelist(botclient, mocker, ticker, fee, markets): + ftbot, client = botclient + + rc = client.get("/whitelist") + assert_response(rc) + assert rc.json == {"whitelist": ['ETH/BTC', 'LTC/BTC', 'XRP/BTC', 'NEO/BTC'], + "length": 4, + "method": "StaticPairList"} + diff --git a/freqtrade/tests/test_freqtradebot.py b/freqtrade/tests/test_freqtradebot.py index 946a9c819..4407859bf 100644 --- a/freqtrade/tests/test_freqtradebot.py +++ b/freqtrade/tests/test_freqtradebot.py @@ -11,16 +11,17 @@ import arrow import pytest import requests -from freqtrade import (DependencyException, OperationalException, - TemporaryError, InvalidOrderException, constants) +from freqtrade import (DependencyException, InvalidOrderException, + OperationalException, TemporaryError, constants) from freqtrade.data.dataprovider import DataProvider from freqtrade.freqtradebot import FreqtradeBot from freqtrade.persistence import Trade from freqtrade.rpc import RPCMessageType from freqtrade.state import State from freqtrade.strategy.interface import SellCheckTuple, SellType -from freqtrade.tests.conftest import (log_has, log_has_re, patch_edge, patch_get_signal, - patch_exchange, patch_wallet) +from freqtrade.tests.conftest import (log_has, log_has_re, patch_edge, + patch_exchange, patch_get_signal, + patch_wallet) from freqtrade.worker import Worker @@ -59,7 +60,6 @@ def get_patched_worker(mocker, config) -> Worker: return Worker(args=None, config=config) - def patch_RPCManager(mocker) -> MagicMock: """ This function mock RPC manager to avoid repeating this code in almost every tests From 39afe4c7bd5cd92d14e728051f4b27409c9fda81 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 May 2019 07:07:51 +0200 Subject: [PATCH 49/71] Test flask app .run() --- freqtrade/rpc/api_server.py | 2 +- freqtrade/tests/rpc/test_rpc_apiserver.py | 49 +++++++++++++++++++++-- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 4ddda307a..c2d83d1fb 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -141,7 +141,7 @@ class ApiServer(RPC): rest_ip = self._config['api_server']['listen_ip_address'] rest_port = self._config['api_server']['listen_port'] - logger.info('Starting HTTP Server at {}:{}'.format(rest_ip, rest_port)) + logger.info(f'Starting HTTP Server at {rest_ip}:{rest_port}') if not IPv4Address(rest_ip).is_loopback: logger.warning("SECURITY WARNING - Local Rest Server listening to external connections") logger.warning("SECURITY WARNING - This is insecure please set to your loopback," diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 95ad7dbc3..41d682d2d 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -8,10 +8,11 @@ from unittest.mock import ANY, MagicMock, PropertyMock import pytest from freqtrade.__init__ import __version__ +from freqtrade.persistence import Trade from freqtrade.rpc.api_server import ApiServer from freqtrade.state import State -from freqtrade.tests.conftest import (get_patched_freqtradebot, patch_get_signal) -from freqtrade.persistence import Trade +from freqtrade.tests.conftest import (get_patched_freqtradebot, log_has, + patch_get_signal) @pytest.fixture @@ -78,6 +79,49 @@ def test_api__init__(default_conf, mocker): assert apiserver._config == default_conf +def test_api_run(default_conf, mocker, caplog): + default_conf.update({"api_server": {"enabled": True, + "listen_ip_address": "127.0.0.1", + "listen_port": "8080"}}) + mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) + mocker.patch('freqtrade.rpc.api_server.threading.Thread', MagicMock()) + + apiserver = ApiServer(get_patched_freqtradebot(mocker, default_conf)) + + # Monkey patch flask app + run_mock = MagicMock() + apiserver.app = MagicMock() + apiserver.app.run = run_mock + + assert apiserver._config == default_conf + apiserver.run() + assert run_mock.call_count == 1 + assert run_mock.call_args_list[0][1]["host"] == "127.0.0.1" + assert run_mock.call_args_list[0][1]["port"] == "8080" + + assert log_has("Starting HTTP Server at 127.0.0.1:8080", caplog.record_tuples) + assert log_has("Starting Local Rest Server", caplog.record_tuples) + + # Test binding to public + caplog.clear() + run_mock.reset_mock() + apiserver._config.update({"api_server": {"enabled": True, + "listen_ip_address": "0.0.0.0", + "listen_port": "8089"}}) + apiserver.run() + + assert run_mock.call_count == 1 + assert run_mock.call_args_list[0][1]["host"] == "0.0.0.0" + assert run_mock.call_args_list[0][1]["port"] == "8089" + assert log_has("Starting HTTP Server at 0.0.0.0:8089", caplog.record_tuples) + assert log_has("Starting Local Rest Server", caplog.record_tuples) + assert log_has("SECURITY WARNING - Local Rest Server listening to external connections", + caplog.record_tuples) + assert log_has("SECURITY WARNING - This is insecure please set to your loopback," + "e.g 127.0.0.1 in config.json", + caplog.record_tuples) + + def test_api_reloadconf(botclient): ftbot, client = botclient @@ -353,4 +397,3 @@ def test_api_whitelist(botclient, mocker, ticker, fee, markets): assert rc.json == {"whitelist": ['ETH/BTC', 'LTC/BTC', 'XRP/BTC', 'NEO/BTC'], "length": 4, "method": "StaticPairList"} - From 350c9037930406691fc5091fd1138d583dca33da Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 May 2019 06:24:22 +0200 Subject: [PATCH 50/71] Test falsk crash --- freqtrade/tests/rpc/test_rpc_apiserver.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 41d682d2d..8752207d0 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -121,6 +121,13 @@ def test_api_run(default_conf, mocker, caplog): "e.g 127.0.0.1 in config.json", caplog.record_tuples) + # Test crashing flask + caplog.clear() + apiserver.app.run = MagicMock(side_effect=Exception) + apiserver.run() + assert log_has("Api server failed to start, exception message is:", + caplog.record_tuples) + def test_api_reloadconf(botclient): ftbot, client = botclient From b700c64dc26cc25c6393930770479982c2cec447 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 May 2019 06:51:23 +0200 Subject: [PATCH 51/71] Test forcebuy - cleanup some tests --- freqtrade/rpc/api_server.py | 5 +- freqtrade/tests/rpc/test_rpc_apiserver.py | 68 +++++++++++++++++++++-- 2 files changed, 68 insertions(+), 5 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index c2d83d1fb..e7b64969f 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -314,7 +314,10 @@ class ApiServer(RPC): asset = request.json.get("pair") price = request.json.get("price", None) trade = self._rpc_forcebuy(asset, price) - return self.rest_dump(trade.to_json()) + if trade: + return self.rest_dump(trade.to_json()) + else: + return self.rest_dump({"status": f"Error buying pair {asset}."}) @safe_rpc def _forcesell(self): diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 8752207d0..31a56321d 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -287,7 +287,7 @@ def test_api_profit(botclient, mocker, ticker, fee, markets, limit_buy_order, li } -def test_api_performance(botclient, mocker, ticker, fee, markets): +def test_api_performance(botclient, mocker, ticker, fee): ftbot, client = botclient patch_get_signal(ftbot, (True, False)) @@ -330,7 +330,7 @@ def test_api_performance(botclient, mocker, ticker, fee, markets): {'count': 1, 'pair': 'XRP/ETH', 'profit': -5.57}] -def test_api_status(botclient, mocker, ticker, fee, markets, limit_buy_order, limit_sell_order): +def test_api_status(botclient, mocker, ticker, fee, markets): ftbot, client = botclient patch_get_signal(ftbot, (True, False)) mocker.patch.multiple( @@ -378,7 +378,7 @@ def test_api_version(botclient): assert rc.json == {"version": __version__} -def test_api_blacklist(botclient, mocker, ticker, fee, markets): +def test_api_blacklist(botclient, mocker): ftbot, client = botclient rc = client.get("/blacklist") @@ -396,7 +396,7 @@ def test_api_blacklist(botclient, mocker, ticker, fee, markets): "method": "StaticPairList"} -def test_api_whitelist(botclient, mocker, ticker, fee, markets): +def test_api_whitelist(botclient): ftbot, client = botclient rc = client.get("/whitelist") @@ -404,3 +404,63 @@ def test_api_whitelist(botclient, mocker, ticker, fee, markets): assert rc.json == {"whitelist": ['ETH/BTC', 'LTC/BTC', 'XRP/BTC', 'NEO/BTC'], "length": 4, "method": "StaticPairList"} + + +def test_api_forcebuy(botclient, mocker, fee): + ftbot, client = botclient + + rc = client.post("/forcebuy", content_type='application/json', + data='{"pair": "ETH/BTC"}') + assert_response(rc, 502) + assert rc.json == {"error": "Error querying _forcebuy: Forcebuy not enabled."} + + # enable forcebuy + ftbot.config["forcebuy_enable"] = True + + fbuy_mock = MagicMock(return_value=None) + mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) + rc = client.post("/forcebuy", content_type="application/json", + data='{"pair": "ETH/BTC"}') + assert_response(rc) + assert rc.json == {"status": "Error buying pair ETH/BTC."} + + # Test creating trae + fbuy_mock = MagicMock(return_value=Trade( + pair='ETH/ETH', + amount=1, + exchange='bittrex', + stake_amount=1, + open_rate=0.245441, + open_order_id="123456", + open_date=datetime.utcnow(), + is_open=False, + fee_close=fee.return_value, + fee_open=fee.return_value, + close_rate=0.265441, + )) + mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) + + rc = client.post("/forcebuy", content_type="application/json", + data='{"pair": "ETH/BTC"}') + assert_response(rc) + assert rc.json == {'amount': 1, + 'close_date': None, + 'close_date_hum': None, + 'close_rate': 0.265441, + 'initial_stop_loss': None, + 'initial_stop_loss_pct': None, + 'open_date': ANY, + 'open_date_hum': 'just now', + 'open_rate': 0.245441, + 'pair': 'ETH/ETH', + 'stake_amount': 1, + 'stop_loss': None, + 'stop_loss_pct': None, + 'trade_id': None} + + +# def test_api_sellbuy(botclient): + # TODO +# ftbot, client = botclient + + # rc = client.get("/forcesell ") From 01cd68a5aa2dbef6844845cef25c6d4a5eefc2ac Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 May 2019 07:00:17 +0200 Subject: [PATCH 52/71] Test forcesell --- freqtrade/tests/rpc/test_rpc_apiserver.py | 25 +++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 31a56321d..c3a8ab27a 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -459,8 +459,25 @@ def test_api_forcebuy(botclient, mocker, fee): 'trade_id': None} -# def test_api_sellbuy(botclient): - # TODO -# ftbot, client = botclient +def test_api_forcesell(botclient, mocker, ticker, fee, markets): + ftbot, client = botclient + mocker.patch.multiple( + 'freqtrade.exchange.Exchange', + get_balances=MagicMock(return_value=ticker), + get_ticker=ticker, + get_fee=fee, + markets=PropertyMock(return_value=markets) + ) + patch_get_signal(ftbot, (True, False)) - # rc = client.get("/forcesell ") + rc = client.post("/forcesell", content_type="application/json", + data='{"tradeid": "1"}') + assert_response(rc, 502) + assert rc.json == {"error": "Error querying _forcesell: invalid argument"} + + ftbot.create_trade() + + rc = client.post("/forcesell", content_type="application/json", + data='{"tradeid": "1"}') + assert_response(rc) + assert rc.json == {'result': 'Created sell order for trade 1.'} From 5149ff7b120bbc431426566a708c48273c06d3b5 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 May 2019 07:12:33 +0200 Subject: [PATCH 53/71] Move api to /api/v1 --- freqtrade/rpc/api_server.py | 47 ++++++++++------- freqtrade/tests/rpc/test_rpc_apiserver.py | 62 +++++++++++------------ scripts/rest_client.py | 2 +- 3 files changed, 60 insertions(+), 51 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index e7b64969f..6213256a4 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -7,12 +7,15 @@ from typing import Dict from arrow import Arrow from flask import Flask, jsonify, request from flask.json import JSONEncoder +from werkzeug.wsgi import DispatcherMiddleware from freqtrade.__init__ import __version__ from freqtrade.rpc.rpc import RPC, RPCException logger = logging.getLogger(__name__) +BASE_URI = "/api/v1" + class ArrowJSONEncoder(JSONEncoder): def default(self, obj): @@ -60,7 +63,6 @@ class ApiServer(RPC): self._config = freqtrade.config self.app = Flask(__name__) - self.app.json_encoder = ArrowJSONEncoder # Register application handling @@ -105,29 +107,36 @@ class ApiServer(RPC): :return: """ # Actions to control the bot - self.app.add_url_rule('/start', 'start', view_func=self._start, methods=['POST']) - self.app.add_url_rule('/stop', 'stop', view_func=self._stop, methods=['POST']) - self.app.add_url_rule('/stopbuy', 'stopbuy', view_func=self._stopbuy, methods=['POST']) - self.app.add_url_rule('/reload_conf', 'reload_conf', view_func=self._reload_conf, - methods=['POST']) + self.app.add_url_rule(f'{BASE_URI}/start', 'start', + view_func=self._start, methods=['POST']) + self.app.add_url_rule(f'{BASE_URI}/stop', 'stop', view_func=self._stop, methods=['POST']) + self.app.add_url_rule(f'{BASE_URI}/stopbuy', 'stopbuy', + view_func=self._stopbuy, methods=['POST']) + self.app.add_url_rule(f'{BASE_URI}/reload_conf', 'reload_conf', + view_func=self._reload_conf, methods=['POST']) # Info commands - self.app.add_url_rule('/balance', 'balance', view_func=self._balance, methods=['GET']) - self.app.add_url_rule('/count', 'count', view_func=self._count, methods=['GET']) - self.app.add_url_rule('/daily', 'daily', view_func=self._daily, methods=['GET']) - self.app.add_url_rule('/edge', 'edge', view_func=self._edge, methods=['GET']) - self.app.add_url_rule('/profit', 'profit', view_func=self._profit, methods=['GET']) - self.app.add_url_rule('/performance', 'performance', view_func=self._performance, - methods=['GET']) - self.app.add_url_rule('/status', 'status', view_func=self._status, methods=['GET']) - self.app.add_url_rule('/version', 'version', view_func=self._version, methods=['GET']) + self.app.add_url_rule(f'{BASE_URI}/balance', 'balance', + view_func=self._balance, methods=['GET']) + self.app.add_url_rule(f'{BASE_URI}/count', 'count', view_func=self._count, methods=['GET']) + self.app.add_url_rule(f'{BASE_URI}/daily', 'daily', view_func=self._daily, methods=['GET']) + self.app.add_url_rule(f'{BASE_URI}/edge', 'edge', view_func=self._edge, methods=['GET']) + self.app.add_url_rule(f'{BASE_URI}/profit', 'profit', + view_func=self._profit, methods=['GET']) + self.app.add_url_rule(f'{BASE_URI}/performance', 'performance', + view_func=self._performance, methods=['GET']) + self.app.add_url_rule(f'{BASE_URI}/status', 'status', + view_func=self._status, methods=['GET']) + self.app.add_url_rule(f'{BASE_URI}/version', 'version', + view_func=self._version, methods=['GET']) # Combined actions and infos - self.app.add_url_rule('/blacklist', 'blacklist', view_func=self._blacklist, + self.app.add_url_rule(f'{BASE_URI}/blacklist', 'blacklist', view_func=self._blacklist, methods=['GET', 'POST']) - self.app.add_url_rule('/whitelist', 'whitelist', view_func=self._whitelist, + self.app.add_url_rule(f'{BASE_URI}/whitelist', 'whitelist', view_func=self._whitelist, methods=['GET']) - self.app.add_url_rule('/forcebuy', 'forcebuy', view_func=self._forcebuy, methods=['POST']) - self.app.add_url_rule('/forcesell', 'forcesell', view_func=self._forcesell, + self.app.add_url_rule(f'{BASE_URI}/forcebuy', 'forcebuy', + view_func=self._forcebuy, methods=['POST']) + self.app.add_url_rule(f'{BASE_URI}/forcesell', 'forcesell', view_func=self._forcesell, methods=['POST']) # TODO: Implement the following diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index c3a8ab27a..6233811fd 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -9,7 +9,7 @@ import pytest from freqtrade.__init__ import __version__ from freqtrade.persistence import Trade -from freqtrade.rpc.api_server import ApiServer +from freqtrade.rpc.api_server import ApiServer, BASE_URI from freqtrade.state import State from freqtrade.tests.conftest import (get_patched_freqtradebot, log_has, patch_get_signal) @@ -35,35 +35,35 @@ def assert_response(response, expected_code=200): def test_api_not_found(botclient): ftbot, client = botclient - rc = client.post("/invalid_url") + rc = client.post(f"{BASE_URI}/invalid_url") assert_response(rc, 404) - assert rc.json == {'status': 'error', - 'reason': "There's no API call for http://localhost/invalid_url.", - 'code': 404 + assert rc.json == {"status": "error", + "reason": f"There's no API call for http://localhost{BASE_URI}/invalid_url.", + "code": 404 } def test_api_stop_workflow(botclient): ftbot, client = botclient assert ftbot.state == State.RUNNING - rc = client.post("/stop") + rc = client.post(f"{BASE_URI}/stop") assert_response(rc) assert rc.json == {'status': 'stopping trader ...'} assert ftbot.state == State.STOPPED # Stop bot again - rc = client.post("/stop") + rc = client.post(f"{BASE_URI}/stop") assert_response(rc) assert rc.json == {'status': 'already stopped'} # Start bot - rc = client.post("/start") + rc = client.post(f"{BASE_URI}/start") assert_response(rc) assert rc.json == {'status': 'starting trader ...'} assert ftbot.state == State.RUNNING # Call start again - rc = client.post("/start") + rc = client.post(f"{BASE_URI}/start") assert_response(rc) assert rc.json == {'status': 'already running'} @@ -132,7 +132,7 @@ def test_api_run(default_conf, mocker, caplog): def test_api_reloadconf(botclient): ftbot, client = botclient - rc = client.post("/reload_conf") + rc = client.post(f"{BASE_URI}/reload_conf") assert_response(rc) assert rc.json == {'status': 'reloading config ...'} assert ftbot.state == State.RELOAD_CONF @@ -142,7 +142,7 @@ def test_api_stopbuy(botclient): ftbot, client = botclient assert ftbot.config['max_open_trades'] != 0 - rc = client.post("/stopbuy") + rc = client.post(f"{BASE_URI}/stopbuy") assert_response(rc) assert rc.json == {'status': 'No more buy will occur from now. Run /reload_conf to reset.'} assert ftbot.config['max_open_trades'] == 0 @@ -172,7 +172,7 @@ def test_api_balance(botclient, mocker, rpc_balance): mocker.patch('freqtrade.exchange.Exchange.get_balances', return_value=rpc_balance) mocker.patch('freqtrade.exchange.Exchange.get_ticker', side_effect=mock_ticker) - rc = client.get("/balance") + rc = client.get(f"{BASE_URI}/balance") assert_response(rc) assert "currencies" in rc.json assert len(rc.json["currencies"]) == 5 @@ -195,7 +195,7 @@ def test_api_count(botclient, mocker, ticker, fee, markets): get_fee=fee, markets=PropertyMock(return_value=markets) ) - rc = client.get("/count") + rc = client.get(f"{BASE_URI}/count") assert_response(rc) assert rc.json["current"] == 0 @@ -203,7 +203,7 @@ def test_api_count(botclient, mocker, ticker, fee, markets): # Create some test data ftbot.create_trade() - rc = client.get("/count") + rc = client.get(f"{BASE_URI}/count") assert_response(rc) assert rc.json["current"] == 1.0 assert rc.json["max"] == 1.0 @@ -219,7 +219,7 @@ def test_api_daily(botclient, mocker, ticker, fee, markets): get_fee=fee, markets=PropertyMock(return_value=markets) ) - rc = client.get("/daily") + rc = client.get(f"{BASE_URI}/daily") assert_response(rc) assert len(rc.json) == 7 assert rc.json[0][0] == str(datetime.utcnow().date()) @@ -235,7 +235,7 @@ def test_api_edge_disabled(botclient, mocker, ticker, fee, markets): get_fee=fee, markets=PropertyMock(return_value=markets) ) - rc = client.get("/edge") + rc = client.get(f"{BASE_URI}/edge") assert_response(rc, 502) assert rc.json == {"error": "Error querying _edge: Edge is not enabled."} @@ -251,7 +251,7 @@ def test_api_profit(botclient, mocker, ticker, fee, markets, limit_buy_order, li markets=PropertyMock(return_value=markets) ) - rc = client.get("/profit") + rc = client.get(f"{BASE_URI}/profit") assert_response(rc, 502) assert len(rc.json) == 1 assert rc.json == {"error": "Error querying _profit: no closed trade"} @@ -261,7 +261,7 @@ def test_api_profit(botclient, mocker, ticker, fee, markets, limit_buy_order, li # Simulate fulfilled LIMIT_BUY order for trade trade.update(limit_buy_order) - rc = client.get("/profit") + rc = client.get(f"{BASE_URI}/profit") assert_response(rc, 502) assert rc.json == {"error": "Error querying _profit: no closed trade"} @@ -270,7 +270,7 @@ def test_api_profit(botclient, mocker, ticker, fee, markets, limit_buy_order, li trade.close_date = datetime.utcnow() trade.is_open = False - rc = client.get("/profit") + rc = client.get(f"{BASE_URI}/profit") assert_response(rc) assert rc.json == {'avg_duration': '0:00:00', 'best_pair': 'ETH/BTC', @@ -323,7 +323,7 @@ def test_api_performance(botclient, mocker, ticker, fee): Trade.session.add(trade) Trade.session.flush() - rc = client.get("/performance") + rc = client.get(f"{BASE_URI}/performance") assert_response(rc) assert len(rc.json) == 2 assert rc.json == [{'count': 1, 'pair': 'LTC/ETH', 'profit': 7.61}, @@ -341,12 +341,12 @@ def test_api_status(botclient, mocker, ticker, fee, markets): markets=PropertyMock(return_value=markets) ) - rc = client.get("/status") + rc = client.get(f"{BASE_URI}/status") assert_response(rc, 502) assert rc.json == {'error': 'Error querying _status: no active trade'} ftbot.create_trade() - rc = client.get("/status") + rc = client.get(f"{BASE_URI}/status") assert_response(rc) assert len(rc.json) == 1 assert rc.json == [{'amount': 90.99181074, @@ -373,7 +373,7 @@ def test_api_status(botclient, mocker, ticker, fee, markets): def test_api_version(botclient): ftbot, client = botclient - rc = client.get("/version") + rc = client.get(f"{BASE_URI}/version") assert_response(rc) assert rc.json == {"version": __version__} @@ -381,14 +381,14 @@ def test_api_version(botclient): def test_api_blacklist(botclient, mocker): ftbot, client = botclient - rc = client.get("/blacklist") + rc = client.get(f"{BASE_URI}/blacklist") assert_response(rc) assert rc.json == {"blacklist": ["DOGE/BTC", "HOT/BTC"], "length": 2, "method": "StaticPairList"} # Add ETH/BTC to blacklist - rc = client.post("/blacklist", data='{"blacklist": ["ETH/BTC"]}', + rc = client.post(f"{BASE_URI}/blacklist", data='{"blacklist": ["ETH/BTC"]}', content_type='application/json') assert_response(rc) assert rc.json == {"blacklist": ["DOGE/BTC", "HOT/BTC", "ETH/BTC"], @@ -399,7 +399,7 @@ def test_api_blacklist(botclient, mocker): def test_api_whitelist(botclient): ftbot, client = botclient - rc = client.get("/whitelist") + rc = client.get(f"{BASE_URI}/whitelist") assert_response(rc) assert rc.json == {"whitelist": ['ETH/BTC', 'LTC/BTC', 'XRP/BTC', 'NEO/BTC'], "length": 4, @@ -409,7 +409,7 @@ def test_api_whitelist(botclient): def test_api_forcebuy(botclient, mocker, fee): ftbot, client = botclient - rc = client.post("/forcebuy", content_type='application/json', + rc = client.post(f"{BASE_URI}/forcebuy", content_type='application/json', data='{"pair": "ETH/BTC"}') assert_response(rc, 502) assert rc.json == {"error": "Error querying _forcebuy: Forcebuy not enabled."} @@ -419,7 +419,7 @@ def test_api_forcebuy(botclient, mocker, fee): fbuy_mock = MagicMock(return_value=None) mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) - rc = client.post("/forcebuy", content_type="application/json", + rc = client.post(f"{BASE_URI}/forcebuy", content_type="application/json", data='{"pair": "ETH/BTC"}') assert_response(rc) assert rc.json == {"status": "Error buying pair ETH/BTC."} @@ -440,7 +440,7 @@ def test_api_forcebuy(botclient, mocker, fee): )) mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) - rc = client.post("/forcebuy", content_type="application/json", + rc = client.post(f"{BASE_URI}/forcebuy", content_type="application/json", data='{"pair": "ETH/BTC"}') assert_response(rc) assert rc.json == {'amount': 1, @@ -470,14 +470,14 @@ def test_api_forcesell(botclient, mocker, ticker, fee, markets): ) patch_get_signal(ftbot, (True, False)) - rc = client.post("/forcesell", content_type="application/json", + rc = client.post(f"{BASE_URI}/forcesell", content_type="application/json", data='{"tradeid": "1"}') assert_response(rc, 502) assert rc.json == {"error": "Error querying _forcesell: invalid argument"} ftbot.create_trade() - rc = client.post("/forcesell", content_type="application/json", + rc = client.post(f"{BASE_URI}/forcesell", content_type="application/json", data='{"tradeid": "1"}') assert_response(rc) assert rc.json == {'result': 'Created sell order for trade 1.'} diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 81c4b66cc..54b08a03a 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -36,7 +36,7 @@ class FtRestClient(): if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'): raise ValueError('invalid method <{0}>'.format(method)) - basepath = f"{self._serverurl}/{apipath}" + basepath = f"{self._serverurl}/api/v1/{apipath}" hd = {"Accept": "application/json", "Content-Type": "application/json" From 540d4bef1e146920dce1215441e951f8a70992cc Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 09:50:19 +0200 Subject: [PATCH 54/71] gracefully shutdown flask --- freqtrade/rpc/api_server.py | 51 +++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 6213256a4..3e1bf6195 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -7,7 +7,7 @@ from typing import Dict from arrow import Arrow from flask import Flask, jsonify, request from flask.json import JSONEncoder -from werkzeug.wsgi import DispatcherMiddleware +from werkzeug.serving import make_server from freqtrade.__init__ import __version__ from freqtrade.rpc.rpc import RPC, RPCException @@ -74,8 +74,31 @@ class ApiServer(RPC): def cleanup(self) -> None: logger.info("Stopping API Server") - # TODO: Gracefully shutdown - right now it'll fail on /reload_conf - # since it's not terminated correctly. + self.srv.shutdown() + + def run(self): + """ + Method that runs flask app in its own thread forever. + Section to handle configuration and running of the Rest server + also to check and warn if not bound to a loopback, warn on security risk. + """ + rest_ip = self._config['api_server']['listen_ip_address'] + rest_port = self._config['api_server']['listen_port'] + + logger.info(f'Starting HTTP Server at {rest_ip}:{rest_port}') + if not IPv4Address(rest_ip).is_loopback: + logger.warning("SECURITY WARNING - Local Rest Server listening to external connections") + logger.warning("SECURITY WARNING - This is insecure please set to your loopback," + "e.g 127.0.0.1 in config.json") + + # Run the Server + logger.info('Starting Local Rest Server') + try: + self.srv = make_server(rest_ip, rest_port, self.app) + self.srv.serve_forever() + except Exception: + logger.exception("Api server failed to start, exception message is:") + logger.info('Starting Local Rest Server_end') def send_msg(self, msg: Dict[str, str]) -> None: """ @@ -142,28 +165,6 @@ class ApiServer(RPC): # TODO: Implement the following # help (?) - def run(self): - """ Method that runs flask app in its own thread forever. - Section to handle configuration and running of the Rest server - also to check and warn if not bound to a loopback, warn on security risk. - """ - rest_ip = self._config['api_server']['listen_ip_address'] - rest_port = self._config['api_server']['listen_port'] - - logger.info(f'Starting HTTP Server at {rest_ip}:{rest_port}') - if not IPv4Address(rest_ip).is_loopback: - logger.warning("SECURITY WARNING - Local Rest Server listening to external connections") - logger.warning("SECURITY WARNING - This is insecure please set to your loopback," - "e.g 127.0.0.1 in config.json") - - # Run the Server - logger.info('Starting Local Rest Server') - try: - self.app.run(host=rest_ip, port=rest_port) - except Exception: - logger.exception("Api server failed to start, exception message is:") - logger.info('Starting Local Rest Server_end') - def page_not_found(self, error): """ Return "404 not found", 404. From bfc57a6f6d3e076ebd02ec0bd68459429604d632 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 09:50:29 +0200 Subject: [PATCH 55/71] Adapt tests to new method of starting flask --- freqtrade/tests/rpc/test_rpc_apiserver.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 6233811fd..1842d8828 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -6,10 +6,11 @@ from datetime import datetime from unittest.mock import ANY, MagicMock, PropertyMock import pytest +from flask import Flask from freqtrade.__init__ import __version__ from freqtrade.persistence import Trade -from freqtrade.rpc.api_server import ApiServer, BASE_URI +from freqtrade.rpc.api_server import BASE_URI, ApiServer from freqtrade.state import State from freqtrade.tests.conftest import (get_patched_freqtradebot, log_has, patch_get_signal) @@ -86,18 +87,17 @@ def test_api_run(default_conf, mocker, caplog): mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) mocker.patch('freqtrade.rpc.api_server.threading.Thread', MagicMock()) - apiserver = ApiServer(get_patched_freqtradebot(mocker, default_conf)) - - # Monkey patch flask app run_mock = MagicMock() - apiserver.app = MagicMock() - apiserver.app.run = run_mock + mocker.patch('freqtrade.rpc.api_server.make_server', run_mock) + + apiserver = ApiServer(get_patched_freqtradebot(mocker, default_conf)) assert apiserver._config == default_conf apiserver.run() assert run_mock.call_count == 1 - assert run_mock.call_args_list[0][1]["host"] == "127.0.0.1" - assert run_mock.call_args_list[0][1]["port"] == "8080" + assert run_mock.call_args_list[0][0][0] == "127.0.0.1" + assert run_mock.call_args_list[0][0][1] == "8080" + assert isinstance(run_mock.call_args_list[0][0][2], Flask) assert log_has("Starting HTTP Server at 127.0.0.1:8080", caplog.record_tuples) assert log_has("Starting Local Rest Server", caplog.record_tuples) @@ -111,8 +111,9 @@ def test_api_run(default_conf, mocker, caplog): apiserver.run() assert run_mock.call_count == 1 - assert run_mock.call_args_list[0][1]["host"] == "0.0.0.0" - assert run_mock.call_args_list[0][1]["port"] == "8089" + assert run_mock.call_args_list[0][0][0] == "0.0.0.0" + assert run_mock.call_args_list[0][0][1] == "8089" + assert isinstance(run_mock.call_args_list[0][0][2], Flask) assert log_has("Starting HTTP Server at 0.0.0.0:8089", caplog.record_tuples) assert log_has("Starting Local Rest Server", caplog.record_tuples) assert log_has("SECURITY WARNING - Local Rest Server listening to external connections", @@ -123,7 +124,7 @@ def test_api_run(default_conf, mocker, caplog): # Test crashing flask caplog.clear() - apiserver.app.run = MagicMock(side_effect=Exception) + mocker.patch('freqtrade.rpc.api_server.make_server', MagicMock(side_effect=Exception)) apiserver.run() assert log_has("Api server failed to start, exception message is:", caplog.record_tuples) From fd5012c04e4c92cdfab04102d85099abb30e282e Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 09:54:36 +0200 Subject: [PATCH 56/71] Add test for api cleanup --- freqtrade/tests/rpc/test_rpc_apiserver.py | 42 +++++++++++++++++------ 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 1842d8828..123988288 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -87,33 +87,34 @@ def test_api_run(default_conf, mocker, caplog): mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) mocker.patch('freqtrade.rpc.api_server.threading.Thread', MagicMock()) - run_mock = MagicMock() - mocker.patch('freqtrade.rpc.api_server.make_server', run_mock) + server_mock = MagicMock() + mocker.patch('freqtrade.rpc.api_server.make_server', server_mock) apiserver = ApiServer(get_patched_freqtradebot(mocker, default_conf)) assert apiserver._config == default_conf apiserver.run() - assert run_mock.call_count == 1 - assert run_mock.call_args_list[0][0][0] == "127.0.0.1" - assert run_mock.call_args_list[0][0][1] == "8080" - assert isinstance(run_mock.call_args_list[0][0][2], Flask) + assert server_mock.call_count == 1 + assert server_mock.call_args_list[0][0][0] == "127.0.0.1" + assert server_mock.call_args_list[0][0][1] == "8080" + assert isinstance(server_mock.call_args_list[0][0][2], Flask) + assert hasattr(apiserver, "srv") assert log_has("Starting HTTP Server at 127.0.0.1:8080", caplog.record_tuples) assert log_has("Starting Local Rest Server", caplog.record_tuples) # Test binding to public caplog.clear() - run_mock.reset_mock() + server_mock.reset_mock() apiserver._config.update({"api_server": {"enabled": True, "listen_ip_address": "0.0.0.0", "listen_port": "8089"}}) apiserver.run() - assert run_mock.call_count == 1 - assert run_mock.call_args_list[0][0][0] == "0.0.0.0" - assert run_mock.call_args_list[0][0][1] == "8089" - assert isinstance(run_mock.call_args_list[0][0][2], Flask) + assert server_mock.call_count == 1 + assert server_mock.call_args_list[0][0][0] == "0.0.0.0" + assert server_mock.call_args_list[0][0][1] == "8089" + assert isinstance(server_mock.call_args_list[0][0][2], Flask) assert log_has("Starting HTTP Server at 0.0.0.0:8089", caplog.record_tuples) assert log_has("Starting Local Rest Server", caplog.record_tuples) assert log_has("SECURITY WARNING - Local Rest Server listening to external connections", @@ -130,6 +131,25 @@ def test_api_run(default_conf, mocker, caplog): caplog.record_tuples) +def test_api_cleanup(default_conf, mocker, caplog): + default_conf.update({"api_server": {"enabled": True, + "listen_ip_address": "127.0.0.1", + "listen_port": "8080"}}) + mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) + mocker.patch('freqtrade.rpc.api_server.threading.Thread', MagicMock()) + mocker.patch('freqtrade.rpc.api_server.make_server', MagicMock()) + + apiserver = ApiServer(get_patched_freqtradebot(mocker, default_conf)) + apiserver.run() + stop_mock = MagicMock() + stop_mock.shutdown = MagicMock() + apiserver.srv = stop_mock + + apiserver.cleanup() + assert stop_mock.shutdown.call_count == 1 + assert log_has("Stopping API Server", caplog.record_tuples) + + def test_api_reloadconf(botclient): ftbot, client = botclient From c272e1ccdf1d94bee785e211713bae2aedda84d6 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 10:24:01 +0200 Subject: [PATCH 57/71] Add default rest config --- config_full.json.example | 5 +++++ scripts/rest_client.py | 21 ++++++++++++--------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/config_full.json.example b/config_full.json.example index 4c4ad3c58..6603540cf 100644 --- a/config_full.json.example +++ b/config_full.json.example @@ -109,6 +109,11 @@ "token": "your_telegram_token", "chat_id": "your_telegram_chat_id" }, + "api_server": { + "enabled": false, + "listen_ip_address": "127.0.0.1", + "listen_port": 8080 + }, "db_url": "sqlite:///tradesv3.sqlite", "initial_state": "running", "forcebuy_enable": false, diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 54b08a03a..4bf46e6fd 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -234,17 +234,19 @@ def load_config(configfile): return {} +def print_commands(): + # Print dynamic help for the different commands + client = FtRestClient(None) + print("Possible commands:") + for x, y in inspect.getmembers(client): + if not x.startswith('_'): + print(f"{x} {getattr(client, x).__doc__}") + + def main(args): - if args.get("show"): - # Print dynamic help for the different commands - client = FtRestClient(None) - print("Possible commands:") - for x, y in inspect.getmembers(client): - if not x.startswith('_'): - print(f"{x} {getattr(client, x).__doc__}") - - return + if args.get("help"): + print_commands() config = load_config(args["config"]) url = config.get("api_server", {}).get("server_url", "127.0.0.1") @@ -256,6 +258,7 @@ def main(args): command = args["command"] if command not in m: logger.error(f"Command {command} not defined") + print_commands() return print(getattr(client, command)(*args["command_arguments"])) From 70fabebcb324f38e80ce15dae7b197c2f75c3d5a Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 10:24:22 +0200 Subject: [PATCH 58/71] Document rest api --- docs/rest-api.md | 184 +++++++++++++++++++++++++++++++++++++++++++++++ mkdocs.yml | 1 + 2 files changed, 185 insertions(+) create mode 100644 docs/rest-api.md diff --git a/docs/rest-api.md b/docs/rest-api.md new file mode 100644 index 000000000..aeb1421c1 --- /dev/null +++ b/docs/rest-api.md @@ -0,0 +1,184 @@ +# REST API Usage + +## Configuration + +Enable the rest API by adding the api_server section to your configuration and setting `api_server.enabled` to `true`. + +Sample configuration: + +``` json + "api_server": { + "enabled": true, + "listen_ip_address": "127.0.0.1", + "listen_port": 8080 + }, +``` + +!!! Danger: Security warning + By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet, since others will be able to control your bot. + +You can then access the API by going to `http://127.0.0.1:8080/api/v1/version` to check if the API is running correctly. + + +### Configuration with docker + +If you run your bot using docker, you'll need to have the bot listen to incomming connections. The security is then handled by docker. + +``` json + "api_server": { + "enabled": true, + "listen_ip_address": "0.0.0.0", + "listen_port": 8080 + }, +``` + +Add the following to your docker command: + +``` bash + -p 127.0.0.1:8080:8080 +``` + +A complete sample-command may then look as follows: + +```bash +docker run -d \ + --name freqtrade \ + -v ~/.freqtrade/config.json:/freqtrade/config.json \ + -v ~/.freqtrade/user_data/:/freqtrade/user_data \ + -v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \ + -p 127.0.0.1:8080:8080 \ + freqtrade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy +``` + +!!! Danger "Security warning" + By using `-p 8080:8080` the API is available to everyone connecting to the server under the correct port, so others will be able to control your bot. + +## Consuming the API + +You can consume the API by using the script `scripts/rest_client.py`. +The client script only requires the `requests` module, so FreqTrade does not need to be installed on the system. + +``` bash +python3 scripts/rest_client.py [optional parameters] +``` + +By default, the script assumes `127.0.0.1` (localhost) and port `8080` to be used, however you can specify a configuration file to override this behaviour. + +### Minimalistic client config + +``` json +{ + "api_server": { + "enabled": true, + "listen_ip_address": "0.0.0.0", + "listen_port": 8080 + } +} +``` + +``` bash +python3 scripts/rest_client.py --config rest_config.json [optional parameters] +``` + +## Available commands + +| Command | Default | Description | +|----------|---------|-------------| +| `start` | | Starts the trader +| `stop` | | Stops the trader +| `stopbuy` | | Stops the trader from opening new trades. Gracefully closes open trades according to their rules. +| `reload_conf` | | Reloads the configuration file +| `status` | | Lists all open trades +| `status table` | | List all open trades in a table format +| `count` | | Displays number of trades used and available +| `profit` | | Display a summary of your profit/loss from close trades and some stats about your performance +| `forcesell ` | | Instantly sells the given trade (Ignoring `minimum_roi`). +| `forcesell all` | | Instantly sells all open trades (Ignoring `minimum_roi`). +| `forcebuy [rate]` | | Instantly buys the given pair. Rate is optional. (`forcebuy_enable` must be set to True) +| `performance` | | Show performance of each finished trade grouped by pair +| `balance` | | Show account balance per currency +| `daily ` | 7 | Shows profit or loss per day, over the last n days +| `whitelist` | | Show the current whitelist +| `blacklist [pair]` | | Show the current blacklist, or adds a pair to the blacklist. +| `edge` | | Show validated pairs by Edge if it is enabled. +| `version` | | Show version + +Possible commands can be listed from the rest-client script using the `help` command. + +``` bash +python3 scripts/rest_client.py help +``` + +``` output +Possible commands: +balance + Get the account balance + :returns: json object + +blacklist + Show the current blacklist + :param add: List of coins to add (example: "BNB/BTC") + :returns: json object + +count + Returns the amount of open trades + :returns: json object + +daily + Returns the amount of open trades + :returns: json object + +edge + Returns information about edge + :returns: json object + +forcebuy + Buy an asset + :param pair: Pair to buy (ETH/BTC) + :param price: Optional - price to buy + :returns: json object of the trade + +forcesell + Force-sell a trade + :param tradeid: Id of the trade (can be received via status command) + :returns: json object + +performance + Returns the performance of the different coins + :returns: json object + +profit + Returns the profit summary + :returns: json object + +reload_conf + Reload configuration + :returns: json object + +start + Start the bot if it's in stopped state. + :returns: json object + +status + Get the status of open trades + :returns: json object + +stop + Stop the bot. Use start to restart + :returns: json object + +stopbuy + Stop buying (but handle sells gracefully). + use reload_conf to reset + :returns: json object + +version + Returns the version of the bot + :returns: json object containing the version + +whitelist + Show the current whitelist + :returns: json object + + +``` diff --git a/mkdocs.yml b/mkdocs.yml index ecac265c1..547c527a5 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -9,6 +9,7 @@ nav: - Control the bot: - Telegram: telegram-usage.md - Web Hook: webhook-config.md + - REST API: rest-api.md - Backtesting: backtesting.md - Hyperopt: hyperopt.md - Edge positioning: edge.md From f2e4689d0c0fb4afb007233752c9587c581288b1 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 10:29:38 +0200 Subject: [PATCH 59/71] Cleanup script --- docs/rest-api.md | 3 --- scripts/rest_client.py | 8 +------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/docs/rest-api.md b/docs/rest-api.md index aeb1421c1..728941c88 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -19,7 +19,6 @@ Sample configuration: You can then access the API by going to `http://127.0.0.1:8080/api/v1/version` to check if the API is running correctly. - ### Configuration with docker If you run your bot using docker, you'll need to have the bot listen to incomming connections. The security is then handled by docker. @@ -179,6 +178,4 @@ version whitelist Show the current whitelist :returns: json object - - ``` diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 4bf46e6fd..0669feb8c 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -216,12 +216,6 @@ def add_arguments(): ) args = parser.parse_args() - # if len(argv) == 1: - # print('\nThis script accepts the following arguments') - # print('- daily (int) - Where int is the number of days to report back. daily 3') - # print('- start - this will start the trading thread') - # print('- stop - this will start the trading thread') - # print('- there will be more....\n') return vars(args) @@ -235,7 +229,7 @@ def load_config(configfile): def print_commands(): - # Print dynamic help for the different commands + # Print dynamic help for the different commands using the commands doc-strings client = FtRestClient(None) print("Possible commands:") for x, y in inspect.getmembers(client): From 9385a27ff031d9f461a47f2d12ef3a6b95b85dec Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 10:34:30 +0200 Subject: [PATCH 60/71] Sort imports --- freqtrade/rpc/api_server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 3e1bf6195..fca7fa702 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -1,6 +1,6 @@ import logging import threading -from datetime import datetime, date +from datetime import date, datetime from ipaddress import IPv4Address from typing import Dict From 79cac36b34d0dde28a0bc6d56a0735f8cedf3b52 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 10:36:40 +0200 Subject: [PATCH 61/71] Reference reest api in main documentation page --- docs/index.md | 12 ++++++++---- scripts/rest_client.py | 1 - 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/index.md b/docs/index.md index 9abc71747..9fbc0519c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -21,8 +21,8 @@ Freqtrade is a cryptocurrency trading bot written in Python. We strongly recommend you to have basic coding skills and Python knowledge. Do not hesitate to read the source code and understand the mechanisms of this bot, algorithms and techniques implemented in it. - ## Features + - Based on Python 3.6+: For botting on any operating system — Windows, macOS and Linux. - Persistence: Persistence is achieved through sqlite database. - Dry-run mode: Run the bot without playing money. @@ -31,17 +31,19 @@ Freqtrade is a cryptocurrency trading bot written in Python. - Edge position sizing: Calculate your win rate, risk reward ratio, the best stoploss and adjust your position size before taking a position for each specific market. - Whitelist crypto-currencies: Select which crypto-currency you want to trade or use dynamic whitelists based on market (pair) trade volume. - Blacklist crypto-currencies: Select which crypto-currency you want to avoid. - - Manageable via Telegram: Manage the bot with Telegram. + - Manageable via Telegram or REST APi: Manage the bot with Telegram or via the builtin REST API. - Display profit/loss in fiat: Display your profit/loss in any of 33 fiat currencies supported. - Daily summary of profit/loss: Receive the daily summary of your profit/loss. - Performance status report: Receive the performance status of your current trades. - ## Requirements + ### Up to date clock + The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges. ### Hardware requirements + To run this bot we recommend you a cloud instance with a minimum of: - 2GB RAM @@ -49,6 +51,7 @@ To run this bot we recommend you a cloud instance with a minimum of: - 2vCPU ### Software requirements + - Python 3.6.x - pip (pip3) - git @@ -56,12 +59,13 @@ To run this bot we recommend you a cloud instance with a minimum of: - virtualenv (Recommended) - Docker (Recommended) - ## Support + Help / Slack For any questions not covered by the documentation or for further information about the bot, we encourage you to join our Slack channel. Click [here](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) to join Slack channel. ## Ready to try? + Begin by reading our installation guide [here](installation). diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 0669feb8c..b31a1de50 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -11,7 +11,6 @@ import argparse import json import logging import inspect -from typing import List from urllib.parse import urlencode, urlparse, urlunparse from pathlib import Path From e6ae890defcbf32ddfe1fb990e5ed3f5a948c6eb Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 13:36:51 +0200 Subject: [PATCH 62/71] small adjustments after first feedback --- docs/rest-api.md | 4 ++-- freqtrade/rpc/api_server.py | 16 +++++----------- freqtrade/tests/rpc/test_rpc_apiserver.py | 6 +++--- 3 files changed, 10 insertions(+), 16 deletions(-) diff --git a/docs/rest-api.md b/docs/rest-api.md index 728941c88..95eec3020 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -15,7 +15,7 @@ Sample configuration: ``` !!! Danger: Security warning - By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet, since others will be able to control your bot. + By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet, since others will potentially be able to control your bot. You can then access the API by going to `http://127.0.0.1:8080/api/v1/version` to check if the API is running correctly. @@ -50,7 +50,7 @@ docker run -d \ ``` !!! Danger "Security warning" - By using `-p 8080:8080` the API is available to everyone connecting to the server under the correct port, so others will be able to control your bot. + By using `-p 8080:8080` the API is available to everyone connecting to the server under the correct port, so others may be able to control your bot. ## Consuming the API diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index fca7fa702..923605e7b 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -66,7 +66,6 @@ class ApiServer(RPC): self.app.json_encoder = ArrowJSONEncoder # Register application handling - self.register_rest_other() self.register_rest_rpc_urls() thread = threading.Thread(target=self.run, daemon=True) @@ -92,13 +91,13 @@ class ApiServer(RPC): "e.g 127.0.0.1 in config.json") # Run the Server - logger.info('Starting Local Rest Server') + logger.info('Starting Local Rest Server.') try: self.srv = make_server(rest_ip, rest_port, self.app) self.srv.serve_forever() except Exception: - logger.exception("Api server failed to start, exception message is:") - logger.info('Starting Local Rest Server_end') + logger.exception("Api server failed to start.") + logger.info('Local Rest Server started.') def send_msg(self, msg: Dict[str, str]) -> None: """ @@ -114,13 +113,6 @@ class ApiServer(RPC): def rest_error(self, error_msg): return jsonify({"error": error_msg}), 502 - def register_rest_other(self): - """ - Registers flask app URLs that are not calls to functionality in rpc.rpc. - :return: - """ - self.app.register_error_handler(404, self.page_not_found) - def register_rest_rpc_urls(self): """ Registers flask app URLs that are calls to functonality in rpc.rpc. @@ -129,6 +121,8 @@ class ApiServer(RPC): Label can be used as a shortcut when refactoring :return: """ + self.app.register_error_handler(404, self.page_not_found) + # Actions to control the bot self.app.add_url_rule(f'{BASE_URI}/start', 'start', view_func=self._start, methods=['POST']) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 123988288..5b9e538b5 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -101,7 +101,7 @@ def test_api_run(default_conf, mocker, caplog): assert hasattr(apiserver, "srv") assert log_has("Starting HTTP Server at 127.0.0.1:8080", caplog.record_tuples) - assert log_has("Starting Local Rest Server", caplog.record_tuples) + assert log_has("Starting Local Rest Server.", caplog.record_tuples) # Test binding to public caplog.clear() @@ -116,7 +116,7 @@ def test_api_run(default_conf, mocker, caplog): assert server_mock.call_args_list[0][0][1] == "8089" assert isinstance(server_mock.call_args_list[0][0][2], Flask) assert log_has("Starting HTTP Server at 0.0.0.0:8089", caplog.record_tuples) - assert log_has("Starting Local Rest Server", caplog.record_tuples) + assert log_has("Starting Local Rest Server.", caplog.record_tuples) assert log_has("SECURITY WARNING - Local Rest Server listening to external connections", caplog.record_tuples) assert log_has("SECURITY WARNING - This is insecure please set to your loopback," @@ -127,7 +127,7 @@ def test_api_run(default_conf, mocker, caplog): caplog.clear() mocker.patch('freqtrade.rpc.api_server.make_server', MagicMock(side_effect=Exception)) apiserver.run() - assert log_has("Api server failed to start, exception message is:", + assert log_has("Api server failed to start.", caplog.record_tuples) From 2cf07e218590182530f2614d96ac245e682e6064 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 May 2019 13:39:12 +0200 Subject: [PATCH 63/71] rename exception handlers --- freqtrade/rpc/api_server.py | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 923605e7b..6792cc9a0 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -41,7 +41,7 @@ class ApiServer(RPC): This class starts a none blocking thread the api server runs within """ - def safe_rpc(func): + def rpc_catch_errors(func): def func_wrapper(self, *args, **kwargs): @@ -169,6 +169,7 @@ class ApiServer(RPC): 'code': 404 }), 404 + @rpc_catch_errors def _start(self): """ Handler for /start. @@ -177,6 +178,7 @@ class ApiServer(RPC): msg = self._rpc_start() return self.rest_dump(msg) + @rpc_catch_errors def _stop(self): """ Handler for /stop. @@ -185,6 +187,7 @@ class ApiServer(RPC): msg = self._rpc_stop() return self.rest_dump(msg) + @rpc_catch_errors def _stopbuy(self): """ Handler for /stopbuy. @@ -193,12 +196,14 @@ class ApiServer(RPC): msg = self._rpc_stopbuy() return self.rest_dump(msg) + @rpc_catch_errors def _version(self): """ Prints the bot's version """ return self.rest_dump({"version": __version__}) + @rpc_catch_errors def _reload_conf(self): """ Handler for /reload_conf. @@ -207,7 +212,7 @@ class ApiServer(RPC): msg = self._rpc_reload_conf() return self.rest_dump(msg) - @safe_rpc + @rpc_catch_errors def _count(self): """ Handler for /count. @@ -216,7 +221,7 @@ class ApiServer(RPC): msg = self._rpc_count() return self.rest_dump(msg) - @safe_rpc + @rpc_catch_errors def _daily(self): """ Returns the last X days trading stats summary. @@ -233,7 +238,7 @@ class ApiServer(RPC): return self.rest_dump(stats) - @safe_rpc + @rpc_catch_errors def _edge(self): """ Returns information related to Edge. @@ -243,7 +248,7 @@ class ApiServer(RPC): return self.rest_dump(stats) - @safe_rpc + @rpc_catch_errors def _profit(self): """ Handler for /profit. @@ -259,7 +264,7 @@ class ApiServer(RPC): return self.rest_dump(stats) - @safe_rpc + @rpc_catch_errors def _performance(self): """ Handler for /performance. @@ -273,7 +278,7 @@ class ApiServer(RPC): return self.rest_dump(stats) - @safe_rpc + @rpc_catch_errors def _status(self): """ Handler for /status. @@ -283,7 +288,7 @@ class ApiServer(RPC): results = self._rpc_trade_status() return self.rest_dump(results) - @safe_rpc + @rpc_catch_errors def _balance(self): """ Handler for /balance. @@ -293,7 +298,7 @@ class ApiServer(RPC): results = self._rpc_balance(self._config.get('fiat_display_currency', '')) return self.rest_dump(results) - @safe_rpc + @rpc_catch_errors def _whitelist(self): """ Handler for /whitelist. @@ -301,7 +306,7 @@ class ApiServer(RPC): results = self._rpc_whitelist() return self.rest_dump(results) - @safe_rpc + @rpc_catch_errors def _blacklist(self): """ Handler for /blacklist. @@ -310,7 +315,7 @@ class ApiServer(RPC): results = self._rpc_blacklist(add) return self.rest_dump(results) - @safe_rpc + @rpc_catch_errors def _forcebuy(self): """ Handler for /forcebuy. @@ -323,7 +328,7 @@ class ApiServer(RPC): else: return self.rest_dump({"status": f"Error buying pair {asset}."}) - @safe_rpc + @rpc_catch_errors def _forcesell(self): """ Handler for /forcesell. From 7e952b028a6d047f0da4ce83cf0bcea2272bf582 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 May 2019 14:11:30 +0200 Subject: [PATCH 64/71] Add basic auth to rest-api --- config_full.json.example | 4 +++- freqtrade/rpc/api_server.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/config_full.json.example b/config_full.json.example index 6603540cf..acecfb649 100644 --- a/config_full.json.example +++ b/config_full.json.example @@ -112,7 +112,9 @@ "api_server": { "enabled": false, "listen_ip_address": "127.0.0.1", - "listen_port": 8080 + "listen_port": 8080, + "username": "freqtrader", + "password": "SuperSecurePassword" }, "db_url": "sqlite:///tradesv3.sqlite", "initial_state": "running", diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 6792cc9a0..5e76e148c 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -53,6 +53,19 @@ class ApiServer(RPC): return func_wrapper + def require_login(func): + + def func_wrapper(self, *args, **kwargs): + # Also works if no username/password is specified + if (request.headers.get('username') == self._config['api_server'].get('username') + and request.headers.get('password') == self._config['api_server'].get('password')): + + return func(self, *args, **kwargs) + else: + return jsonify({"error": "Unauthorized"}), 401 + + return func_wrapper + def __init__(self, freqtrade) -> None: """ Init the api server, and init the super class RPC @@ -159,6 +172,7 @@ class ApiServer(RPC): # TODO: Implement the following # help (?) + @require_login def page_not_found(self, error): """ Return "404 not found", 404. @@ -169,6 +183,7 @@ class ApiServer(RPC): 'code': 404 }), 404 + @require_login @rpc_catch_errors def _start(self): """ @@ -178,6 +193,7 @@ class ApiServer(RPC): msg = self._rpc_start() return self.rest_dump(msg) + @require_login @rpc_catch_errors def _stop(self): """ @@ -187,6 +203,7 @@ class ApiServer(RPC): msg = self._rpc_stop() return self.rest_dump(msg) + @require_login @rpc_catch_errors def _stopbuy(self): """ @@ -196,6 +213,7 @@ class ApiServer(RPC): msg = self._rpc_stopbuy() return self.rest_dump(msg) + @require_login @rpc_catch_errors def _version(self): """ @@ -203,6 +221,7 @@ class ApiServer(RPC): """ return self.rest_dump({"version": __version__}) + @require_login @rpc_catch_errors def _reload_conf(self): """ @@ -212,6 +231,7 @@ class ApiServer(RPC): msg = self._rpc_reload_conf() return self.rest_dump(msg) + @require_login @rpc_catch_errors def _count(self): """ @@ -221,6 +241,7 @@ class ApiServer(RPC): msg = self._rpc_count() return self.rest_dump(msg) + @require_login @rpc_catch_errors def _daily(self): """ @@ -238,6 +259,7 @@ class ApiServer(RPC): return self.rest_dump(stats) + @require_login @rpc_catch_errors def _edge(self): """ @@ -248,6 +270,7 @@ class ApiServer(RPC): return self.rest_dump(stats) + @require_login @rpc_catch_errors def _profit(self): """ @@ -264,6 +287,7 @@ class ApiServer(RPC): return self.rest_dump(stats) + @require_login @rpc_catch_errors def _performance(self): """ @@ -278,6 +302,7 @@ class ApiServer(RPC): return self.rest_dump(stats) + @require_login @rpc_catch_errors def _status(self): """ @@ -288,6 +313,7 @@ class ApiServer(RPC): results = self._rpc_trade_status() return self.rest_dump(results) + @require_login @rpc_catch_errors def _balance(self): """ @@ -298,6 +324,7 @@ class ApiServer(RPC): results = self._rpc_balance(self._config.get('fiat_display_currency', '')) return self.rest_dump(results) + @require_login @rpc_catch_errors def _whitelist(self): """ @@ -306,6 +333,7 @@ class ApiServer(RPC): results = self._rpc_whitelist() return self.rest_dump(results) + @require_login @rpc_catch_errors def _blacklist(self): """ @@ -315,6 +343,7 @@ class ApiServer(RPC): results = self._rpc_blacklist(add) return self.rest_dump(results) + @require_login @rpc_catch_errors def _forcebuy(self): """ @@ -328,6 +357,7 @@ class ApiServer(RPC): else: return self.rest_dump({"status": f"Error buying pair {asset}."}) + @require_login @rpc_catch_errors def _forcesell(self): """ From 04c35b465ed20284763227c0d28a0f6471e6713b Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 May 2019 14:13:59 +0200 Subject: [PATCH 65/71] Add authorization to tests --- freqtrade/tests/rpc/test_rpc_apiserver.py | 111 ++++++++++++++++------ 1 file changed, 82 insertions(+), 29 deletions(-) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 5b9e538b5..620a7c34b 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -16,11 +16,19 @@ from freqtrade.tests.conftest import (get_patched_freqtradebot, log_has, patch_get_signal) +_TEST_USER = "FreqTrader" +_TEST_PASS = "SuperSecurePassword1!" + + @pytest.fixture def botclient(default_conf, mocker): default_conf.update({"api_server": {"enabled": True, "listen_ip_address": "127.0.0.1", - "listen_port": "8080"}}) + "listen_port": "8080", + "username": _TEST_USER, + "password": _TEST_PASS, + }}) + ftbot = get_patched_freqtradebot(mocker, default_conf) mocker.patch('freqtrade.rpc.api_server.ApiServer.run', MagicMock()) apiserver = ApiServer(ftbot) @@ -28,6 +36,21 @@ def botclient(default_conf, mocker): # Cleanup ... ? +def client_post(client, url, data={}): + headers = {"username": _TEST_USER, + "password": _TEST_PASS} + return client.post(url, + content_type="application/json", + data=data, + headers=headers) + + +def client_get(client, url): + headers = {"username": _TEST_USER, + "password": _TEST_PASS} + return client.get(url, headers=headers) + + def assert_response(response, expected_code=200): assert response.status_code == expected_code assert response.content_type == "application/json" @@ -36,7 +59,7 @@ def assert_response(response, expected_code=200): def test_api_not_found(botclient): ftbot, client = botclient - rc = client.post(f"{BASE_URI}/invalid_url") + rc = client_post(client, f"{BASE_URI}/invalid_url") assert_response(rc, 404) assert rc.json == {"status": "error", "reason": f"There's no API call for http://localhost{BASE_URI}/invalid_url.", @@ -44,27 +67,57 @@ def test_api_not_found(botclient): } +def test_api_unauthorized(botclient): + ftbot, client = botclient + # Don't send user/pass information + rc = client.get(f"{BASE_URI}/version") + assert_response(rc, 401) + assert rc.json == {'error': 'Unauthorized'} + + # Change only username + ftbot.config['api_server']['username'] = "Ftrader" + rc = client_get(client, f"{BASE_URI}/version") + assert_response(rc, 401) + assert rc.json == {'error': 'Unauthorized'} + + # Change only password + ftbot.config['api_server']['username'] = _TEST_USER + ftbot.config['api_server']['password'] = "WrongPassword" + rc = client_get(client, f"{BASE_URI}/version") + assert_response(rc, 401) + assert rc.json == {'error': 'Unauthorized'} + + ftbot.config['api_server']['username'] = "Ftrader" + ftbot.config['api_server']['password'] = "WrongPassword" + + rc = client_get(client, f"{BASE_URI}/version") + assert_response(rc, 401) + assert rc.json == {'error': 'Unauthorized'} + + + + def test_api_stop_workflow(botclient): ftbot, client = botclient assert ftbot.state == State.RUNNING - rc = client.post(f"{BASE_URI}/stop") + rc = client_post(client, f"{BASE_URI}/stop") assert_response(rc) assert rc.json == {'status': 'stopping trader ...'} assert ftbot.state == State.STOPPED # Stop bot again - rc = client.post(f"{BASE_URI}/stop") + rc = client_post(client, f"{BASE_URI}/stop") assert_response(rc) assert rc.json == {'status': 'already stopped'} # Start bot - rc = client.post(f"{BASE_URI}/start") + rc = client_post(client, f"{BASE_URI}/start") assert_response(rc) assert rc.json == {'status': 'starting trader ...'} assert ftbot.state == State.RUNNING # Call start again - rc = client.post(f"{BASE_URI}/start") + rc = client_post(client, f"{BASE_URI}/start") assert_response(rc) assert rc.json == {'status': 'already running'} @@ -153,7 +206,7 @@ def test_api_cleanup(default_conf, mocker, caplog): def test_api_reloadconf(botclient): ftbot, client = botclient - rc = client.post(f"{BASE_URI}/reload_conf") + rc = client_post(client, f"{BASE_URI}/reload_conf") assert_response(rc) assert rc.json == {'status': 'reloading config ...'} assert ftbot.state == State.RELOAD_CONF @@ -163,7 +216,7 @@ def test_api_stopbuy(botclient): ftbot, client = botclient assert ftbot.config['max_open_trades'] != 0 - rc = client.post(f"{BASE_URI}/stopbuy") + rc = client_post(client, f"{BASE_URI}/stopbuy") assert_response(rc) assert rc.json == {'status': 'No more buy will occur from now. Run /reload_conf to reset.'} assert ftbot.config['max_open_trades'] == 0 @@ -193,7 +246,7 @@ def test_api_balance(botclient, mocker, rpc_balance): mocker.patch('freqtrade.exchange.Exchange.get_balances', return_value=rpc_balance) mocker.patch('freqtrade.exchange.Exchange.get_ticker', side_effect=mock_ticker) - rc = client.get(f"{BASE_URI}/balance") + rc = client_get(client, f"{BASE_URI}/balance") assert_response(rc) assert "currencies" in rc.json assert len(rc.json["currencies"]) == 5 @@ -216,7 +269,7 @@ def test_api_count(botclient, mocker, ticker, fee, markets): get_fee=fee, markets=PropertyMock(return_value=markets) ) - rc = client.get(f"{BASE_URI}/count") + rc = client_get(client, f"{BASE_URI}/count") assert_response(rc) assert rc.json["current"] == 0 @@ -224,7 +277,7 @@ def test_api_count(botclient, mocker, ticker, fee, markets): # Create some test data ftbot.create_trade() - rc = client.get(f"{BASE_URI}/count") + rc = client_get(client, f"{BASE_URI}/count") assert_response(rc) assert rc.json["current"] == 1.0 assert rc.json["max"] == 1.0 @@ -240,7 +293,7 @@ def test_api_daily(botclient, mocker, ticker, fee, markets): get_fee=fee, markets=PropertyMock(return_value=markets) ) - rc = client.get(f"{BASE_URI}/daily") + rc = client_get(client, f"{BASE_URI}/daily") assert_response(rc) assert len(rc.json) == 7 assert rc.json[0][0] == str(datetime.utcnow().date()) @@ -256,7 +309,7 @@ def test_api_edge_disabled(botclient, mocker, ticker, fee, markets): get_fee=fee, markets=PropertyMock(return_value=markets) ) - rc = client.get(f"{BASE_URI}/edge") + rc = client_get(client, f"{BASE_URI}/edge") assert_response(rc, 502) assert rc.json == {"error": "Error querying _edge: Edge is not enabled."} @@ -272,7 +325,7 @@ def test_api_profit(botclient, mocker, ticker, fee, markets, limit_buy_order, li markets=PropertyMock(return_value=markets) ) - rc = client.get(f"{BASE_URI}/profit") + rc = client_get(client, f"{BASE_URI}/profit") assert_response(rc, 502) assert len(rc.json) == 1 assert rc.json == {"error": "Error querying _profit: no closed trade"} @@ -282,7 +335,7 @@ def test_api_profit(botclient, mocker, ticker, fee, markets, limit_buy_order, li # Simulate fulfilled LIMIT_BUY order for trade trade.update(limit_buy_order) - rc = client.get(f"{BASE_URI}/profit") + rc = client_get(client, f"{BASE_URI}/profit") assert_response(rc, 502) assert rc.json == {"error": "Error querying _profit: no closed trade"} @@ -291,7 +344,7 @@ def test_api_profit(botclient, mocker, ticker, fee, markets, limit_buy_order, li trade.close_date = datetime.utcnow() trade.is_open = False - rc = client.get(f"{BASE_URI}/profit") + rc = client_get(client, f"{BASE_URI}/profit") assert_response(rc) assert rc.json == {'avg_duration': '0:00:00', 'best_pair': 'ETH/BTC', @@ -344,7 +397,7 @@ def test_api_performance(botclient, mocker, ticker, fee): Trade.session.add(trade) Trade.session.flush() - rc = client.get(f"{BASE_URI}/performance") + rc = client_get(client, f"{BASE_URI}/performance") assert_response(rc) assert len(rc.json) == 2 assert rc.json == [{'count': 1, 'pair': 'LTC/ETH', 'profit': 7.61}, @@ -362,12 +415,12 @@ def test_api_status(botclient, mocker, ticker, fee, markets): markets=PropertyMock(return_value=markets) ) - rc = client.get(f"{BASE_URI}/status") + rc = client_get(client, f"{BASE_URI}/status") assert_response(rc, 502) assert rc.json == {'error': 'Error querying _status: no active trade'} ftbot.create_trade() - rc = client.get(f"{BASE_URI}/status") + rc = client_get(client, f"{BASE_URI}/status") assert_response(rc) assert len(rc.json) == 1 assert rc.json == [{'amount': 90.99181074, @@ -394,7 +447,7 @@ def test_api_status(botclient, mocker, ticker, fee, markets): def test_api_version(botclient): ftbot, client = botclient - rc = client.get(f"{BASE_URI}/version") + rc = client_get(client, f"{BASE_URI}/version") assert_response(rc) assert rc.json == {"version": __version__} @@ -402,15 +455,15 @@ def test_api_version(botclient): def test_api_blacklist(botclient, mocker): ftbot, client = botclient - rc = client.get(f"{BASE_URI}/blacklist") + rc = client_get(client, f"{BASE_URI}/blacklist") assert_response(rc) assert rc.json == {"blacklist": ["DOGE/BTC", "HOT/BTC"], "length": 2, "method": "StaticPairList"} # Add ETH/BTC to blacklist - rc = client.post(f"{BASE_URI}/blacklist", data='{"blacklist": ["ETH/BTC"]}', - content_type='application/json') + rc = client_post(client, f"{BASE_URI}/blacklist", + data='{"blacklist": ["ETH/BTC"]}') assert_response(rc) assert rc.json == {"blacklist": ["DOGE/BTC", "HOT/BTC", "ETH/BTC"], "length": 3, @@ -420,7 +473,7 @@ def test_api_blacklist(botclient, mocker): def test_api_whitelist(botclient): ftbot, client = botclient - rc = client.get(f"{BASE_URI}/whitelist") + rc = client_get(client, f"{BASE_URI}/whitelist") assert_response(rc) assert rc.json == {"whitelist": ['ETH/BTC', 'LTC/BTC', 'XRP/BTC', 'NEO/BTC'], "length": 4, @@ -430,7 +483,7 @@ def test_api_whitelist(botclient): def test_api_forcebuy(botclient, mocker, fee): ftbot, client = botclient - rc = client.post(f"{BASE_URI}/forcebuy", content_type='application/json', + rc = client_post(client, f"{BASE_URI}/forcebuy", data='{"pair": "ETH/BTC"}') assert_response(rc, 502) assert rc.json == {"error": "Error querying _forcebuy: Forcebuy not enabled."} @@ -440,7 +493,7 @@ def test_api_forcebuy(botclient, mocker, fee): fbuy_mock = MagicMock(return_value=None) mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) - rc = client.post(f"{BASE_URI}/forcebuy", content_type="application/json", + rc = client_post(client, f"{BASE_URI}/forcebuy", data='{"pair": "ETH/BTC"}') assert_response(rc) assert rc.json == {"status": "Error buying pair ETH/BTC."} @@ -461,7 +514,7 @@ def test_api_forcebuy(botclient, mocker, fee): )) mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) - rc = client.post(f"{BASE_URI}/forcebuy", content_type="application/json", + rc = client_post(client, f"{BASE_URI}/forcebuy", data='{"pair": "ETH/BTC"}') assert_response(rc) assert rc.json == {'amount': 1, @@ -491,14 +544,14 @@ def test_api_forcesell(botclient, mocker, ticker, fee, markets): ) patch_get_signal(ftbot, (True, False)) - rc = client.post(f"{BASE_URI}/forcesell", content_type="application/json", + rc = client_post(client, f"{BASE_URI}/forcesell", data='{"tradeid": "1"}') assert_response(rc, 502) assert rc.json == {"error": "Error querying _forcesell: invalid argument"} ftbot.create_trade() - rc = client.post(f"{BASE_URI}/forcesell", content_type="application/json", + rc = client_post(client, f"{BASE_URI}/forcesell", data='{"tradeid": "1"}') assert_response(rc) assert rc.json == {'result': 'Created sell order for trade 1.'} From 1fab884a2fcae07293a2d3139889d7dcb4462fe0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 May 2019 14:14:09 +0200 Subject: [PATCH 66/71] use Authorization for client --- scripts/rest_client.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index b31a1de50..ca3da737e 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -26,10 +26,12 @@ logger = logging.getLogger("ft_rest_client") class FtRestClient(): - def __init__(self, serverurl): + def __init__(self, serverurl, username=None, password=None): self._serverurl = serverurl self._session = requests.Session() + self._username = username + self._password = password def _call(self, method, apipath, params: dict = None, data=None, files=None): @@ -41,6 +43,12 @@ class FtRestClient(): "Content-Type": "application/json" } + if self._username: + hd.update({"username": self._username}) + + if self._password: + hd.update({"password": self._password}) + # Split url schema, netloc, path, par, query, fragment = urlparse(basepath) # URLEncode query string @@ -244,8 +252,11 @@ def main(args): config = load_config(args["config"]) url = config.get("api_server", {}).get("server_url", "127.0.0.1") port = config.get("api_server", {}).get("listen_port", "8080") + username = config.get("api_server", {}).get("username") + password = config.get("api_server", {}).get("password") + server_url = f"http://{url}:{port}" - client = FtRestClient(server_url) + client = FtRestClient(server_url, username, password) m = [x for x, y in inspect.getmembers(client) if not x.startswith('_')] command = args["command"] From 5bbd3c61581cac89741fdc65b8786078610afd75 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 May 2019 14:16:59 +0200 Subject: [PATCH 67/71] Add documentation --- docs/rest-api.md | 9 +++++++-- freqtrade/rpc/api_server.py | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/rest-api.md b/docs/rest-api.md index 95eec3020..535163da4 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -10,12 +10,17 @@ Sample configuration: "api_server": { "enabled": true, "listen_ip_address": "127.0.0.1", - "listen_port": 8080 + "listen_port": 8080, + "username": "Freqtrader", + "password": "SuperSecret1!" }, ``` !!! Danger: Security warning - By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet, since others will potentially be able to control your bot. + By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot. + +!!! Danger: Password selection + Please make sure to select a very strong, unique password to protect your bot from unauthorized access. You can then access the API by going to `http://127.0.0.1:8080/api/v1/version` to check if the API is running correctly. diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 5e76e148c..d2001e91a 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -56,7 +56,7 @@ class ApiServer(RPC): def require_login(func): def func_wrapper(self, *args, **kwargs): - # Also works if no username/password is specified + # Also accepts empty username/password if it's missing in both config and request if (request.headers.get('username') == self._config['api_server'].get('username') and request.headers.get('password') == self._config['api_server'].get('password')): From 2da7145132956d4c0f02488e28133b9e35d16772 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 May 2019 14:25:16 +0200 Subject: [PATCH 68/71] Switch auth to real basic auth --- freqtrade/rpc/api_server.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index d2001e91a..14b15a3df 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -53,13 +53,16 @@ class ApiServer(RPC): return func_wrapper + def check_auth(self, username, password): + return (username == self._config['api_server'].get('username') and + password == self._config['api_server'].get('password')) + def require_login(func): def func_wrapper(self, *args, **kwargs): - # Also accepts empty username/password if it's missing in both config and request - if (request.headers.get('username') == self._config['api_server'].get('username') - and request.headers.get('password') == self._config['api_server'].get('password')): + auth = request.authorization + if auth and self.check_auth(auth.username, auth.password): return func(self, *args, **kwargs) else: return jsonify({"error": "Unauthorized"}), 401 From febcc3dddc043b568f9d067ca6ad1dc5c60bed7f Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 May 2019 14:25:36 +0200 Subject: [PATCH 69/71] Adapt tests and rest_client to basic_auth --- freqtrade/tests/rpc/test_rpc_apiserver.py | 11 +++-------- scripts/rest_client.py | 13 ++----------- 2 files changed, 5 insertions(+), 19 deletions(-) diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 620a7c34b..4c3aea89a 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -7,6 +7,7 @@ from unittest.mock import ANY, MagicMock, PropertyMock import pytest from flask import Flask +from requests.auth import _basic_auth_str from freqtrade.__init__ import __version__ from freqtrade.persistence import Trade @@ -37,18 +38,14 @@ def botclient(default_conf, mocker): def client_post(client, url, data={}): - headers = {"username": _TEST_USER, - "password": _TEST_PASS} return client.post(url, content_type="application/json", data=data, - headers=headers) + headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS)}) def client_get(client, url): - headers = {"username": _TEST_USER, - "password": _TEST_PASS} - return client.get(url, headers=headers) + return client.get(url, headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS)}) def assert_response(response, expected_code=200): @@ -95,8 +92,6 @@ def test_api_unauthorized(botclient): assert rc.json == {'error': 'Unauthorized'} - - def test_api_stop_workflow(botclient): ftbot, client = botclient assert ftbot.state == State.RUNNING diff --git a/scripts/rest_client.py b/scripts/rest_client.py index ca3da737e..2261fba0b 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -30,8 +30,7 @@ class FtRestClient(): self._serverurl = serverurl self._session = requests.Session() - self._username = username - self._password = password + self._session.auth = (username, password) def _call(self, method, apipath, params: dict = None, data=None, files=None): @@ -43,12 +42,6 @@ class FtRestClient(): "Content-Type": "application/json" } - if self._username: - hd.update({"username": self._username}) - - if self._password: - hd.update({"password": self._password}) - # Split url schema, netloc, path, par, query, fragment = urlparse(basepath) # URLEncode query string @@ -57,9 +50,7 @@ class FtRestClient(): url = urlunparse((schema, netloc, path, par, query, fragment)) try: - resp = self._session.request(method, url, headers=hd, data=json.dumps(data), - # auth=self.session.auth - ) + resp = self._session.request(method, url, headers=hd, data=json.dumps(data)) # return resp.text return resp.json() except ConnectionError: From 90ece09ee98900b62e29562d4ccdd6f5d77d777e Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 May 2019 14:42:13 +0200 Subject: [PATCH 70/71] require username/password for API server --- freqtrade/constants.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 1b06eb726..4772952fc 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -166,8 +166,10 @@ CONF_SCHEMA = { "minimum": 1024, "maximum": 65535 }, + 'username': {'type': 'string'}, + 'password': {'type': 'string'}, }, - 'required': ['enabled', 'listen_ip_address', 'listen_port'] + 'required': ['enabled', 'listen_ip_address', 'listen_port', 'username', 'password'] }, 'db_url': {'type': 'string'}, 'initial_state': {'type': 'string', 'enum': ['running', 'stopped']}, From dab4307e04dd3ccbe3f860113a4ace43463d4fb9 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 26 May 2019 14:40:03 +0200 Subject: [PATCH 71/71] Add secure way to genreate password, warn if no password is defined --- docs/rest-api.md | 7 +++++++ freqtrade/rpc/api_server.py | 4 ++++ freqtrade/tests/rpc/test_rpc_apiserver.py | 10 +++++++--- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/docs/rest-api.md b/docs/rest-api.md index 535163da4..0508f83e4 100644 --- a/docs/rest-api.md +++ b/docs/rest-api.md @@ -24,6 +24,13 @@ Sample configuration: You can then access the API by going to `http://127.0.0.1:8080/api/v1/version` to check if the API is running correctly. +To generate a secure password, either use a password manager, or use the below code snipped. + +``` python +import secrets +secrets.token_hex() +``` + ### Configuration with docker If you run your bot using docker, you'll need to have the bot listen to incomming connections. The security is then handled by docker. diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index 14b15a3df..711202b27 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -106,6 +106,10 @@ class ApiServer(RPC): logger.warning("SECURITY WARNING - This is insecure please set to your loopback," "e.g 127.0.0.1 in config.json") + if not self._config['api_server'].get('password'): + logger.warning("SECURITY WARNING - No password for local REST Server defined. " + "Please make sure that this is intentional!") + # Run the Server logger.info('Starting Local Rest Server.') try: diff --git a/freqtrade/tests/rpc/test_rpc_apiserver.py b/freqtrade/tests/rpc/test_rpc_apiserver.py index 4c3aea89a..b7721fd8e 100644 --- a/freqtrade/tests/rpc/test_rpc_apiserver.py +++ b/freqtrade/tests/rpc/test_rpc_apiserver.py @@ -156,7 +156,9 @@ def test_api_run(default_conf, mocker, caplog): server_mock.reset_mock() apiserver._config.update({"api_server": {"enabled": True, "listen_ip_address": "0.0.0.0", - "listen_port": "8089"}}) + "listen_port": "8089", + "password": "", + }}) apiserver.run() assert server_mock.call_count == 1 @@ -170,13 +172,15 @@ def test_api_run(default_conf, mocker, caplog): assert log_has("SECURITY WARNING - This is insecure please set to your loopback," "e.g 127.0.0.1 in config.json", caplog.record_tuples) + assert log_has("SECURITY WARNING - No password for local REST Server defined. " + "Please make sure that this is intentional!", + caplog.record_tuples) # Test crashing flask caplog.clear() mocker.patch('freqtrade.rpc.api_server.make_server', MagicMock(side_effect=Exception)) apiserver.run() - assert log_has("Api server failed to start.", - caplog.record_tuples) + assert log_has("Api server failed to start.", caplog.record_tuples) def test_api_cleanup(default_conf, mocker, caplog):