Merge pull request #958 from creslinux/feature/flask-rest
Feature/flask rest
This commit is contained in:
commit
b059ee192d
@ -6,7 +6,6 @@ from typing import Dict
|
|||||||
|
|
||||||
from flask import Flask, request
|
from flask import Flask, request
|
||||||
# from flask_restful import Resource, Api
|
# from flask_restful import Resource, Api
|
||||||
from json import dumps
|
|
||||||
from freqtrade.rpc.rpc import RPC, RPCException
|
from freqtrade.rpc.rpc import RPC, RPCException
|
||||||
from ipaddress import IPv4Address
|
from ipaddress import IPv4Address
|
||||||
|
|
||||||
@ -17,8 +16,11 @@ app = Flask(__name__)
|
|||||||
|
|
||||||
class ApiServer(RPC):
|
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:
|
def __init__(self, freqtrade) -> None:
|
||||||
"""
|
"""
|
||||||
Init the api server, and init the super class RPC
|
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('/stop', 'stop', view_func=self.stop, methods=['GET'])
|
||||||
app.add_url_rule('/start', 'start', view_func=self.start, 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('/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):
|
def run(self):
|
||||||
""" Method that runs flask app in its own thread forever """
|
""" Method that runs flask app in its own thread forever """
|
||||||
@ -109,11 +114,19 @@ class ApiServer(RPC):
|
|||||||
:return: index.html
|
:return: index.html
|
||||||
"""
|
"""
|
||||||
rest_cmds = 'Commands implemented: <br>' \
|
rest_cmds = 'Commands implemented: <br>' \
|
||||||
'<a href=/daily?timescale=7>/daily?timescale=7</a>' \
|
'<a href=/daily?timescale=7>Show 7 days of stats</a>' \
|
||||||
'<br>' \
|
'<br>' \
|
||||||
'<a href=/stop>/stop</a>' \
|
'<a href=/stop>Stop the Trade thread</a>' \
|
||||||
'<br>' \
|
'<br>' \
|
||||||
'<a href=/start>/start</a>'
|
'<a href=/start>Start the Traded thread</a>' \
|
||||||
|
'<br>' \
|
||||||
|
'<a href=/profit>Show profit summary</a>' \
|
||||||
|
'<br>' \
|
||||||
|
'<a href=/status_table>Show status table - Open trades</a>' \
|
||||||
|
'<br>' \
|
||||||
|
'<a href=/paypal> 404 page does not exist</a>' \
|
||||||
|
'<br>'
|
||||||
|
|
||||||
return rest_cmds
|
return rest_cmds
|
||||||
|
|
||||||
def daily(self):
|
def daily(self):
|
||||||
@ -132,10 +145,44 @@ class ApiServer(RPC):
|
|||||||
self._config['fiat_display_currency']
|
self._config['fiat_display_currency']
|
||||||
)
|
)
|
||||||
|
|
||||||
stats = dumps(stats, indent=4, sort_keys=True, default=str)
|
return json.dumps(stats, indent=4, sort_keys=True, default=str)
|
||||||
return stats
|
|
||||||
except RPCException as e:
|
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):
|
def start(self):
|
||||||
"""
|
"""
|
||||||
|
74
freqtrade/rpc/api_server_common.py
Normal file
74
freqtrade/rpc/api_server_common.py
Normal file
@ -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: <br>' \
|
||||||
|
'<a href=/daily?timescale=7>Show 7 days of stats</a>' \
|
||||||
|
'<br>' \
|
||||||
|
'<a href=/stop>Stop the Trade thread</a>' \
|
||||||
|
'<br>' \
|
||||||
|
'<a href=/start>Start the Traded thread</a>' \
|
||||||
|
'<br>' \
|
||||||
|
'<a href=/paypal> 404 page does not exist</a>' \
|
||||||
|
'<br>' \
|
||||||
|
'<br>' \
|
||||||
|
'<a href=/stop_api>Shut down the api server - be sure</a>'
|
||||||
|
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
|
@ -155,6 +155,9 @@ class RPC(object):
|
|||||||
""" Returns cumulative profit statistics """
|
""" Returns cumulative profit statistics """
|
||||||
trades = Trade.query.order_by(Trade.id).all()
|
trades = Trade.query.order_by(Trade.id).all()
|
||||||
|
|
||||||
|
if not trades:
|
||||||
|
raise RPCException('No trades found')
|
||||||
|
|
||||||
profit_all_coin = []
|
profit_all_coin = []
|
||||||
profit_all_percent = []
|
profit_all_percent = []
|
||||||
profit_closed_coin = []
|
profit_closed_coin = []
|
||||||
|
Loading…
Reference in New Issue
Block a user