diff --git a/freqtrade/rpc/api_server.py b/freqtrade/rpc/api_server.py index af1d76c87..1055a0553 100644 --- a/freqtrade/rpc/api_server.py +++ b/freqtrade/rpc/api_server.py @@ -6,7 +6,6 @@ from typing import Dict from flask import Flask, request # from flask_restful import Resource, Api -from json import dumps from freqtrade.rpc.rpc import RPC, RPCException from ipaddress import IPv4Address @@ -17,8 +16,11 @@ app = Flask(__name__) class ApiServer(RPC): """ - This class is for REST calls across api server + 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 @@ -55,6 +57,9 @@ class ApiServer(RPC): 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 """ @@ -109,11 +114,19 @@ class ApiServer(RPC): :return: index.html """ rest_cmds = 'Commands implemented:
' \ - '/daily?timescale=7' \ + 'Show 7 days of stats' \ '
' \ - '/stop' \ + 'Stop the Trade thread' \ '
' \ - '/start' + 'Start the Traded thread' \ + '
' \ + 'Show profit summary' \ + '
' \ + 'Show status table - Open trades' \ + '
' \ + ' 404 page does not exist' \ + '
' + return rest_cmds def daily(self): @@ -132,10 +145,44 @@ class ApiServer(RPC): self._config['fiat_display_currency'] ) - stats = dumps(stats, indent=4, sort_keys=True, default=str) - return stats + return json.dumps(stats, indent=4, sort_keys=True, default=str) except RPCException as e: - return 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): """ 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/rpc.py b/freqtrade/rpc/rpc.py index 754c511d4..ce3d62ed7 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -155,6 +155,9 @@ class RPC(object): """ Returns cumulative profit statistics """ trades = Trade.query.order_by(Trade.id).all() + if not trades: + raise RPCException('No trades found') + profit_all_coin = [] profit_all_percent = [] profit_closed_coin = []