stable/tests/rpc/test_rpc_apiserver.py

1398 lines
48 KiB
Python
Raw Normal View History

2019-04-04 05:12:58 +00:00
"""
Unit test file for rpc/api_server.py
"""
2021-04-01 17:59:49 +00:00
import json
2020-10-26 06:36:25 +00:00
from datetime import datetime, timedelta, timezone
2020-09-17 05:53:22 +00:00
from pathlib import Path
2019-05-11 12:05:25 +00:00
from unittest.mock import ANY, MagicMock, PropertyMock
2019-04-04 05:12:58 +00:00
2019-05-10 05:07:38 +00:00
import pytest
2020-12-31 10:01:50 +00:00
import uvicorn
2020-12-27 09:56:19 +00:00
from fastapi import FastAPI
2020-12-31 10:01:50 +00:00
from fastapi.exceptions import HTTPException
2020-12-27 09:59:17 +00:00
from fastapi.testclient import TestClient
2021-02-22 11:11:27 +00:00
from numpy import isnan
from requests.auth import _basic_auth_str
2019-05-10 05:07:38 +00:00
2019-05-11 07:44:39 +00:00
from freqtrade.__init__ import __version__
2021-06-08 19:20:35 +00:00
from freqtrade.enums import RunMode, State
from freqtrade.exceptions import DependencyException, ExchangeError, OperationalException
2020-08-14 17:36:12 +00:00
from freqtrade.loggers import setup_logging, setup_logging_pre
2020-10-25 09:54:30 +00:00
from freqtrade.persistence import PairLocks, Trade
from freqtrade.rpc import RPC
2020-12-31 10:01:50 +00:00
from freqtrade.rpc.api_server import ApiServer
from freqtrade.rpc.api_server.api_auth import create_token, get_user_from_token
from freqtrade.rpc.api_server.uvicorn_threaded import UvicornServer
from tests.conftest import (CURRENT_TEST_STRATEGY, create_mock_trades, get_mock_coro,
get_patched_freqtradebot, log_has, log_has_re, patch_get_signal)
2020-09-28 17:43:15 +00:00
2019-04-04 05:12:58 +00:00
2020-12-27 09:59:17 +00:00
BASE_URI = "/api/v1"
2019-05-25 12:13:59 +00:00
_TEST_USER = "FreqTrader"
_TEST_PASS = "SuperSecurePassword1!"
2019-05-10 05:07:38 +00:00
@pytest.fixture
2019-05-11 06:55:21 +00:00
def botclient(default_conf, mocker):
2020-08-14 17:36:12 +00:00
setup_logging_pre()
setup_logging(default_conf)
default_conf['runmode'] = RunMode.DRY_RUN
2019-05-11 11:31:48 +00:00
default_conf.update({"api_server": {"enabled": True,
2019-05-11 11:40:30 +00:00
"listen_ip_address": "127.0.0.1",
2019-11-23 14:20:53 +00:00
"listen_port": 8080,
2020-06-24 18:32:35 +00:00
"CORS_origins": ['http://example.com'],
2019-05-25 12:13:59 +00:00
"username": _TEST_USER,
"password": _TEST_PASS,
}})
2021-07-23 11:34:18 +00:00
ftbot = get_patched_freqtradebot(mocker, default_conf)
rpc = RPC(ftbot)
2020-12-31 10:01:50 +00:00
mocker.patch('freqtrade.rpc.api_server.ApiServer.start_api', MagicMock())
2021-01-02 15:12:10 +00:00
try:
apiserver = ApiServer(default_conf)
apiserver.add_rpc_handler(rpc)
2021-07-23 11:34:18 +00:00
yield ftbot, TestClient(apiserver.app)
2021-01-02 15:12:10 +00:00
# Cleanup ... ?
finally:
ApiServer.shutdown()
2019-05-10 05:07:38 +00:00
2019-05-25 12:13:59 +00:00
def client_post(client, url, data={}):
return client.post(url,
data=data,
2020-05-20 17:43:52 +00:00
headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS),
2020-12-26 15:33:13 +00:00
'Origin': 'http://example.com',
'content-type': 'application/json'
})
2019-05-25 12:13:59 +00:00
def client_get(client, url):
2020-05-20 17:43:52 +00:00
# Add fake Origin to ensure CORS kicks in
return client.get(url, headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS),
2020-06-24 18:32:35 +00:00
'Origin': 'http://example.com'})
2019-05-25 12:13:59 +00:00
2020-08-04 12:41:38 +00:00
def client_delete(client, url):
# Add fake Origin to ensure CORS kicks in
return client.delete(url, headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS),
'Origin': 'http://example.com'})
2020-05-20 17:43:52 +00:00
def assert_response(response, expected_code=200, needs_cors=True):
2019-05-11 12:05:25 +00:00
assert response.status_code == expected_code
2020-12-26 15:33:13 +00:00
assert response.headers.get('content-type') == "application/json"
2020-05-20 17:43:52 +00:00
if needs_cors:
2020-12-26 15:33:13 +00:00
assert ('access-control-allow-credentials', 'true') in response.headers.items()
assert ('access-control-allow-origin', 'http://example.com') in response.headers.items()
2019-05-10 05:07:38 +00:00
2019-05-11 11:18:11 +00:00
def test_api_not_found(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-05-11 11:18:11 +00:00
2021-01-10 09:31:05 +00:00
rc = client_get(client, f"{BASE_URI}/invalid_url")
2019-05-11 12:05:25 +00:00
assert_response(rc, 404)
2020-12-26 16:48:19 +00:00
assert rc.json() == {"detail": "Not Found"}
2019-05-11 11:18:11 +00:00
2021-01-31 14:27:00 +00:00
def test_api_ui_fallback(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2021-01-31 14:27:00 +00:00
rc = client_get(client, "/favicon.ico")
assert rc.status_code == 200
rc = client_get(client, "/fallback_file.html")
assert rc.status_code == 200
assert '`freqtrade install-ui`' in rc.text
# Forwarded to fallback_html or index.html (depending if it's installed or not)
rc = client_get(client, "/something")
assert rc.status_code == 200
# Test directory traversal
2021-08-16 04:38:36 +00:00
rc = client_get(client, '%2F%2F%2Fetc/passwd')
assert rc.status_code == 200
assert '`freqtrade install-ui`' in rc.text
2021-01-31 14:27:00 +00:00
2021-07-06 05:20:05 +00:00
def test_api_ui_version(botclient, mocker):
ftbot, client = botclient
mocker.patch('freqtrade.commands.deploy_commands.read_ui_version', return_value='0.1.2')
rc = client_get(client, "/ui_version")
assert rc.status_code == 200
assert rc.json()['version'] == '0.1.2'
2020-12-27 13:57:01 +00:00
def test_api_auth():
with pytest.raises(ValueError):
create_token({'identity': {'u': 'Freqtrade'}}, 'secret1234', token_type="NotATokenType")
2020-12-27 13:57:01 +00:00
token = create_token({'identity': {'u': 'Freqtrade'}}, 'secret1234')
2021-01-08 18:27:51 +00:00
assert isinstance(token, str)
2020-12-27 13:57:01 +00:00
2020-12-27 14:24:49 +00:00
u = get_user_from_token(token, 'secret1234')
2020-12-27 13:57:01 +00:00
assert u == 'Freqtrade'
with pytest.raises(HTTPException):
2020-12-27 14:24:49 +00:00
get_user_from_token(token, 'secret1234', token_type='refresh')
2020-12-27 13:57:01 +00:00
# Create invalid token
token = create_token({'identity': {'u1': 'Freqrade'}}, 'secret1234')
2020-12-27 13:57:01 +00:00
with pytest.raises(HTTPException):
2020-12-27 14:24:49 +00:00
get_user_from_token(token, 'secret1234')
2020-12-27 13:57:01 +00:00
with pytest.raises(HTTPException):
2020-12-27 14:24:49 +00:00
get_user_from_token(b'not_a_token', 'secret1234')
2020-12-27 13:57:01 +00:00
2019-05-25 12:13:59 +00:00
def test_api_unauthorized(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-11-11 19:09:58 +00:00
rc = client.get(f"{BASE_URI}/ping")
2020-05-20 17:43:52 +00:00
assert_response(rc, needs_cors=False)
2020-12-26 15:33:13 +00:00
assert rc.json() == {'status': 'pong'}
2019-11-11 19:09:58 +00:00
2019-05-25 12:13:59 +00:00
# Don't send user/pass information
rc = client.get(f"{BASE_URI}/version")
2020-05-20 17:43:52 +00:00
assert_response(rc, 401, needs_cors=False)
2020-12-27 13:57:01 +00:00
assert rc.json() == {'detail': 'Unauthorized'}
2019-05-25 12:13:59 +00:00
# Change only username
2021-07-23 11:34:18 +00:00
ftbot.config['api_server']['username'] = 'Ftrader'
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/version")
assert_response(rc, 401)
2020-12-27 13:57:01 +00:00
assert rc.json() == {'detail': 'Unauthorized'}
2019-05-25 12:13:59 +00:00
# Change only password
2021-07-23 11:34:18 +00:00
ftbot.config['api_server']['username'] = _TEST_USER
ftbot.config['api_server']['password'] = 'WrongPassword'
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/version")
assert_response(rc, 401)
2020-12-27 13:57:01 +00:00
assert rc.json() == {'detail': 'Unauthorized'}
2019-05-25 12:13:59 +00:00
2021-07-23 11:34:18 +00:00
ftbot.config['api_server']['username'] = 'Ftrader'
ftbot.config['api_server']['password'] = 'WrongPassword'
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/version")
assert_response(rc, 401)
2020-12-27 13:57:01 +00:00
assert rc.json() == {'detail': 'Unauthorized'}
2019-05-25 12:13:59 +00:00
2020-05-10 08:43:13 +00:00
def test_api_token_login(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-12-27 13:57:01 +00:00
rc = client.post(f"{BASE_URI}/token/login",
data=None,
headers={'Authorization': _basic_auth_str('WRONG_USER', 'WRONG_PASS'),
'Origin': 'http://example.com'})
assert_response(rc, 401)
2020-05-10 08:43:13 +00:00
rc = client_post(client, f"{BASE_URI}/token/login")
assert_response(rc)
2020-12-26 15:33:13 +00:00
assert 'access_token' in rc.json()
assert 'refresh_token' in rc.json()
2020-05-10 08:43:13 +00:00
# test Authentication is working with JWT tokens too
rc = client.get(f"{BASE_URI}/count",
2020-12-26 15:33:13 +00:00
headers={'Authorization': f'Bearer {rc.json()["access_token"]}',
2020-06-24 18:32:35 +00:00
'Origin': 'http://example.com'})
2020-05-10 08:43:13 +00:00
assert_response(rc)
def test_api_token_refresh(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-05-10 08:43:13 +00:00
rc = client_post(client, f"{BASE_URI}/token/login")
assert_response(rc)
rc = client.post(f"{BASE_URI}/token/refresh",
data=None,
2020-12-26 16:48:19 +00:00
headers={'Authorization': f'Bearer {rc.json()["refresh_token"]}',
2020-06-24 18:32:35 +00:00
'Origin': 'http://example.com'})
2020-05-10 08:43:13 +00:00
assert_response(rc)
2020-12-26 16:48:19 +00:00
assert 'access_token' in rc.json()
assert 'refresh_token' not in rc.json()
2020-05-10 08:43:13 +00:00
2019-05-11 06:55:21 +00:00
def test_api_stop_workflow(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
assert ftbot.state == State.RUNNING
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/stop")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 16:48:19 +00:00
assert rc.json() == {'status': 'stopping trader ...'}
2021-07-23 11:34:18 +00:00
assert ftbot.state == State.STOPPED
2019-05-10 05:07:38 +00:00
2019-05-11 06:55:21 +00:00
# Stop bot again
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/stop")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 16:48:19 +00:00
assert rc.json() == {'status': 'already stopped'}
2019-05-11 06:55:21 +00:00
# Start bot
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/start")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 16:48:19 +00:00
assert rc.json() == {'status': 'starting trader ...'}
2021-07-23 11:34:18 +00:00
assert ftbot.state == State.RUNNING
2019-05-11 06:55:21 +00:00
# Call start again
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/start")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 16:48:19 +00:00
assert rc.json() == {'status': 'already running'}
2019-05-10 05:07:38 +00:00
2019-05-11 06:55:21 +00:00
def test_api__init__(default_conf, mocker):
2019-04-04 05:12:58 +00:00
"""
Test __init__() method
"""
2020-05-10 18:00:19 +00:00
default_conf.update({"api_server": {"enabled": True,
"listen_ip_address": "127.0.0.1",
"listen_port": 8080,
"username": "TestUser",
"password": "testPass",
}})
2019-04-04 05:12:58 +00:00
mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock())
2020-12-31 10:01:50 +00:00
mocker.patch('freqtrade.rpc.api_server.webserver.ApiServer.start_api', MagicMock())
2021-01-02 15:12:10 +00:00
apiserver = ApiServer(default_conf)
apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf)))
2019-04-04 05:12:58 +00:00
assert apiserver._config == default_conf
2021-07-06 19:04:52 +00:00
with pytest.raises(OperationalException, match="RPC Handler already attached."):
apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf)))
2021-01-02 15:12:10 +00:00
ApiServer.shutdown()
2019-04-04 05:12:58 +00:00
2021-03-13 14:36:34 +00:00
def test_api_UvicornServer(mocker):
2020-12-31 10:01:50 +00:00
thread_mock = mocker.patch('freqtrade.rpc.api_server.uvicorn_threaded.threading.Thread')
2020-12-27 13:57:01 +00:00
s = UvicornServer(uvicorn.Config(MagicMock(), port=8080, host='127.0.0.1'))
assert thread_mock.call_count == 0
s.install_signal_handlers()
# Original implementation starts a thread - make sure that's not the case
assert thread_mock.call_count == 0
# Fake started to avoid sleeping forever
s.started = True
s.run_in_thread()
assert thread_mock.call_count == 1
s.cleanup()
assert s.should_exit is True
2021-03-13 14:36:34 +00:00
def test_api_UvicornServer_run(mocker):
serve_mock = mocker.patch('freqtrade.rpc.api_server.uvicorn_threaded.UvicornServer.serve',
get_mock_coro(None))
s = UvicornServer(uvicorn.Config(MagicMock(), port=8080, host='127.0.0.1'))
assert serve_mock.call_count == 0
s.install_signal_handlers()
# Original implementation starts a thread - make sure that's not the case
assert serve_mock.call_count == 0
# Fake started to avoid sleeping forever
s.started = True
s.run()
assert serve_mock.call_count == 1
def test_api_UvicornServer_run_no_uvloop(mocker, import_fails):
serve_mock = mocker.patch('freqtrade.rpc.api_server.uvicorn_threaded.UvicornServer.serve',
get_mock_coro(None))
s = UvicornServer(uvicorn.Config(MagicMock(), port=8080, host='127.0.0.1'))
assert serve_mock.call_count == 0
s.install_signal_handlers()
# Original implementation starts a thread - make sure that's not the case
assert serve_mock.call_count == 0
# Fake started to avoid sleeping forever
s.started = True
s.run()
assert serve_mock.call_count == 1
2019-05-14 05:07:51 +00:00
def test_api_run(default_conf, mocker, caplog):
default_conf.update({"api_server": {"enabled": True,
"listen_ip_address": "127.0.0.1",
2019-11-23 14:20:53 +00:00
"listen_port": 8080,
"username": "TestUser",
"password": "testPass",
}})
2019-05-14 05:07:51 +00:00
mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock())
server_inst_mock = MagicMock()
server_inst_mock.run_in_thread = MagicMock()
server_inst_mock.run = MagicMock()
server_mock = MagicMock(return_value=server_inst_mock)
2020-12-31 10:01:50 +00:00
mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer', server_mock)
2021-01-02 15:12:10 +00:00
apiserver = ApiServer(default_conf)
apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf)))
2019-05-14 05:07:51 +00:00
2019-05-18 07:54:36 +00:00
assert server_mock.call_count == 1
2020-12-27 09:56:19 +00:00
assert apiserver._config == default_conf
apiserver.start_api()
assert server_mock.call_count == 2
assert server_inst_mock.run_in_thread.call_count == 2
assert server_inst_mock.run.call_count == 0
2020-12-27 09:56:19 +00:00
assert server_mock.call_args_list[0][0][0].host == "127.0.0.1"
assert server_mock.call_args_list[0][0][0].port == 8080
assert isinstance(server_mock.call_args_list[0][0][0].app, FastAPI)
2019-05-14 05:07:51 +00:00
2019-08-11 18:17:22 +00:00
assert log_has("Starting HTTP Server at 127.0.0.1:8080", caplog)
assert log_has("Starting Local Rest Server.", caplog)
2019-05-14 05:07:51 +00:00
# Test binding to public
caplog.clear()
2019-05-18 07:54:36 +00:00
server_mock.reset_mock()
2019-05-14 05:07:51 +00:00
apiserver._config.update({"api_server": {"enabled": True,
"listen_ip_address": "0.0.0.0",
2019-11-23 14:20:53 +00:00
"listen_port": 8089,
"password": "",
}})
2020-12-27 09:56:19 +00:00
apiserver.start_api()
2019-05-14 05:07:51 +00:00
2019-05-18 07:54:36 +00:00
assert server_mock.call_count == 1
assert server_inst_mock.run_in_thread.call_count == 1
assert server_inst_mock.run.call_count == 0
2020-12-27 09:56:19 +00:00
assert server_mock.call_args_list[0][0][0].host == "0.0.0.0"
assert server_mock.call_args_list[0][0][0].port == 8089
assert isinstance(server_mock.call_args_list[0][0][0].app, FastAPI)
2019-08-11 18:17:22 +00:00
assert log_has("Starting HTTP Server at 0.0.0.0:8089", caplog)
assert log_has("Starting Local Rest Server.", caplog)
2019-05-14 05:07:51 +00:00
assert log_has("SECURITY WARNING - Local Rest Server listening to external connections",
2019-08-11 18:17:22 +00:00
caplog)
2019-05-14 05:07:51 +00:00
assert log_has("SECURITY WARNING - This is insecure please set to your loopback,"
2019-08-11 18:17:22 +00:00
"e.g 127.0.0.1 in config.json", caplog)
assert log_has("SECURITY WARNING - No password for local REST Server defined. "
2019-08-11 18:17:22 +00:00
"Please make sure that this is intentional!", caplog)
2020-12-27 14:24:49 +00:00
assert log_has_re("SECURITY WARNING - `jwt_secret_key` seems to be default.*", caplog)
server_mock.reset_mock()
apiserver._standalone = True
apiserver.start_api()
assert server_inst_mock.run_in_thread.call_count == 0
assert server_inst_mock.run.call_count == 1
apiserver1 = ApiServer(default_conf)
assert id(apiserver1) == id(apiserver)
apiserver._standalone = False
# Test crashing API server
2019-05-15 04:24:22 +00:00
caplog.clear()
2020-12-31 10:01:50 +00:00
mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer',
MagicMock(side_effect=Exception))
2020-12-27 09:56:19 +00:00
apiserver.start_api()
2019-08-11 18:17:22 +00:00
assert log_has("Api server failed to start.", caplog)
2021-01-02 15:12:10 +00:00
ApiServer.shutdown()
2019-05-15 04:24:22 +00:00
2019-05-14 05:07:51 +00:00
2019-05-18 07:54:36 +00:00
def test_api_cleanup(default_conf, mocker, caplog):
default_conf.update({"api_server": {"enabled": True,
"listen_ip_address": "127.0.0.1",
2019-11-23 14:20:53 +00:00
"listen_port": 8080,
"username": "TestUser",
"password": "testPass",
}})
2019-05-18 07:54:36 +00:00
mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock())
2020-12-27 09:56:19 +00:00
server_mock = MagicMock()
server_mock.cleanup = MagicMock()
2020-12-31 10:01:50 +00:00
mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer', server_mock)
2019-05-18 07:54:36 +00:00
2021-01-02 15:12:10 +00:00
apiserver = ApiServer(default_conf)
apiserver.add_rpc_handler(RPC(get_patched_freqtradebot(mocker, default_conf)))
2019-05-18 07:54:36 +00:00
apiserver.cleanup()
2020-12-27 09:56:19 +00:00
assert apiserver._server.cleanup.call_count == 1
2019-08-11 18:17:22 +00:00
assert log_has("Stopping API Server", caplog)
2021-01-02 15:12:10 +00:00
ApiServer.shutdown()
2019-05-18 07:54:36 +00:00
2019-05-11 06:55:21 +00:00
def test_api_reloadconf(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-04-04 05:12:58 +00:00
rc = client_post(client, f"{BASE_URI}/reload_config")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 15:33:13 +00:00
assert rc.json() == {'status': 'Reloading config ...'}
2021-07-23 11:34:18 +00:00
assert ftbot.state == State.RELOAD_CONFIG
2019-04-04 05:12:58 +00:00
2019-05-11 06:55:21 +00:00
def test_api_stopbuy(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
assert ftbot.config['max_open_trades'] != 0
2019-04-04 05:12:58 +00:00
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/stopbuy")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 15:33:13 +00:00
assert rc.json() == {'status': 'No more buy will occur from now. Run /reload_config to reset.'}
2021-07-23 11:34:18 +00:00
assert ftbot.config['max_open_trades'] == 0
2019-05-11 07:10:54 +00:00
2021-09-19 23:44:12 +00:00
def test_api_balance(botclient, mocker, rpc_balance, tickers):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-05-11 07:10:54 +00:00
2021-07-23 11:34:18 +00:00
ftbot.config['dry_run'] = False
2019-05-11 07:10:54 +00:00
mocker.patch('freqtrade.exchange.Exchange.get_balances', return_value=rpc_balance)
2021-09-19 23:44:12 +00:00
mocker.patch('freqtrade.exchange.Exchange.get_tickers', tickers)
2019-07-03 18:07:26 +00:00
mocker.patch('freqtrade.exchange.Exchange.get_valid_pair_combination',
side_effect=lambda a, b: f"{a}/{b}")
2021-07-23 11:34:18 +00:00
ftbot.wallets.update()
2019-05-11 07:10:54 +00:00
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/balance")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2021-09-19 23:44:12 +00:00
response = rc.json()
assert "currencies" in response
assert len(response["currencies"]) == 5
assert response['currencies'][0] == {
2019-05-11 07:10:54 +00:00
'currency': 'BTC',
'free': 12.0,
2019-05-11 07:10:54 +00:00
'balance': 12.0,
'used': 0.0,
2019-11-15 05:33:07 +00:00
'est_stake': 12.0,
'stake': 'BTC',
2019-05-11 07:10:54 +00:00
}
2021-09-19 23:44:12 +00:00
assert 'starting_capital' in response
assert 'starting_capital_fiat' in response
assert 'starting_capital_pct' in response
assert 'starting_capital_ratio' in response
2019-05-11 07:44:39 +00:00
2021-09-20 02:24:22 +00:00
@pytest.mark.parametrize('is_short', [True, False])
def test_api_count(botclient, mocker, ticker, fee, markets, is_short):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2019-05-11 07:44:39 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
get_balances=MagicMock(return_value=ticker),
2019-12-18 15:34:30 +00:00
fetch_ticker=ticker,
2019-05-11 07:44:39 +00:00
get_fee=fee,
markets=PropertyMock(return_value=markets)
)
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/count")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2019-05-11 07:44:39 +00:00
2020-12-26 15:33:13 +00:00
assert rc.json()["current"] == 0
assert rc.json()["max"] == 1
2019-05-11 07:44:39 +00:00
# Create some test data
2021-09-20 02:24:22 +00:00
create_mock_trades(fee, is_short)
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/count")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2021-04-10 17:53:00 +00:00
assert rc.json()["current"] == 4
assert rc.json()["max"] == 1
2021-07-23 11:34:18 +00:00
ftbot.config['max_open_trades'] = float('inf')
rc = client_get(client, f"{BASE_URI}/count")
assert rc.json()["max"] == -1
2019-05-11 11:31:48 +00:00
2020-10-17 15:58:07 +00:00
def test_api_locks(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-10-17 15:58:07 +00:00
rc = client_get(client, f"{BASE_URI}/locks")
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert 'locks' in rc.json()
2020-10-17 15:58:07 +00:00
2020-12-26 16:33:27 +00:00
assert rc.json()['lock_count'] == 0
assert rc.json()['lock_count'] == len(rc.json()['locks'])
2020-10-17 15:58:07 +00:00
2020-10-26 06:36:25 +00:00
PairLocks.lock_pair('ETH/BTC', datetime.now(timezone.utc) + timedelta(minutes=4), 'randreason')
PairLocks.lock_pair('XRP/BTC', datetime.now(timezone.utc) + timedelta(minutes=20), 'deadbeef')
2020-10-17 15:58:07 +00:00
rc = client_get(client, f"{BASE_URI}/locks")
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json()['lock_count'] == 2
assert rc.json()['lock_count'] == len(rc.json()['locks'])
assert 'ETH/BTC' in (rc.json()['locks'][0]['pair'], rc.json()['locks'][1]['pair'])
assert 'randreason' in (rc.json()['locks'][0]['reason'], rc.json()['locks'][1]['reason'])
assert 'deadbeef' in (rc.json()['locks'][0]['reason'], rc.json()['locks'][1]['reason'])
2020-10-17 15:58:07 +00:00
2021-03-01 18:50:39 +00:00
# Test deletions
rc = client_delete(client, f"{BASE_URI}/locks/1")
assert_response(rc)
assert rc.json()['lock_count'] == 1
rc = client_post(client, f"{BASE_URI}/locks/delete",
data='{"pair": "XRP/BTC"}')
assert_response(rc)
assert rc.json()['lock_count'] == 0
2020-10-17 15:58:07 +00:00
2019-11-17 13:56:08 +00:00
def test_api_show_config(botclient, mocker):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2019-11-17 13:56:08 +00:00
rc = client_get(client, f"{BASE_URI}/show_config")
assert_response(rc)
2020-12-26 15:33:13 +00:00
assert 'dry_run' in rc.json()
2021-04-20 10:54:22 +00:00
assert rc.json()['exchange'] == 'binance'
2020-12-26 15:33:13 +00:00
assert rc.json()['timeframe'] == '5m'
assert rc.json()['timeframe_ms'] == 300000
assert rc.json()['timeframe_min'] == 5
assert rc.json()['state'] == 'running'
assert rc.json()['bot_name'] == 'freqtrade'
2020-12-26 15:33:13 +00:00
assert not rc.json()['trailing_stop']
assert 'bid_strategy' in rc.json()
assert 'ask_strategy' in rc.json()
2019-11-17 13:56:08 +00:00
2019-05-11 11:31:48 +00:00
def test_api_daily(botclient, mocker, ticker, fee, markets):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2019-05-11 11:31:48 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
get_balances=MagicMock(return_value=ticker),
2019-12-18 15:34:30 +00:00
fetch_ticker=ticker,
2019-05-11 11:31:48 +00:00
get_fee=fee,
markets=PropertyMock(return_value=markets)
)
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/daily")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert len(rc.json()['data']) == 7
assert rc.json()['stake_currency'] == 'BTC'
assert rc.json()['fiat_display_currency'] == 'USD'
assert rc.json()['data'][0]['date'] == str(datetime.utcnow().date())
2019-05-11 12:05:25 +00:00
2021-09-20 02:24:22 +00:00
@pytest.mark.parametrize('is_short', [True, False])
def test_api_trades(botclient, mocker, fee, markets, is_short):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2020-04-07 17:50:13 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
markets=PropertyMock(return_value=markets)
)
rc = client_get(client, f"{BASE_URI}/trades")
assert_response(rc)
assert len(rc.json()) == 3
2020-12-26 16:33:27 +00:00
assert rc.json()['trades_count'] == 0
2021-04-20 19:28:13 +00:00
assert rc.json()['total_trades'] == 0
2020-04-07 17:50:13 +00:00
2021-09-20 02:24:22 +00:00
create_mock_trades(fee, is_short)
Trade.query.session.flush()
2020-04-07 17:50:13 +00:00
rc = client_get(client, f"{BASE_URI}/trades")
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert len(rc.json()['trades']) == 2
assert rc.json()['trades_count'] == 2
2021-04-20 19:28:13 +00:00
assert rc.json()['total_trades'] == 2
rc = client_get(client, f"{BASE_URI}/trades?limit=1")
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert len(rc.json()['trades']) == 1
assert rc.json()['trades_count'] == 1
2021-04-20 19:28:13 +00:00
assert rc.json()['total_trades'] == 2
2020-04-07 17:50:13 +00:00
2021-09-20 02:24:22 +00:00
# TODO-lev: @pytest.mark.parametrize('is_short', [True, False])
def test_api_trade_single(botclient, mocker, fee, ticker, markets):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
markets=PropertyMock(return_value=markets),
fetch_ticker=ticker,
)
rc = client_get(client, f"{BASE_URI}/trade/3")
assert_response(rc, 404)
assert rc.json()['detail'] == 'Trade not found.'
2021-09-20 02:24:22 +00:00
create_mock_trades(fee, False)
Trade.query.session.flush()
rc = client_get(client, f"{BASE_URI}/trade/3")
assert_response(rc)
assert rc.json()['trade_id'] == 3
2021-09-20 02:24:22 +00:00
# TODO-lev: @pytest.mark.parametrize('is_short', [True, False])
2020-08-04 12:41:38 +00:00
def test_api_delete_trade(botclient, mocker, fee, markets):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2020-08-04 17:43:05 +00:00
stoploss_mock = MagicMock()
cancel_mock = MagicMock()
2020-08-04 12:41:38 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
2020-08-04 17:43:05 +00:00
markets=PropertyMock(return_value=markets),
cancel_order=cancel_mock,
cancel_stoploss_order=stoploss_mock,
2020-08-04 12:41:38 +00:00
)
rc = client_delete(client, f"{BASE_URI}/trades/1")
# Error - trade won't exist yet.
assert_response(rc, 502)
2021-09-20 02:24:22 +00:00
create_mock_trades(fee, False)
Trade.query.session.flush()
2021-07-23 11:34:18 +00:00
ftbot.strategy.order_types['stoploss_on_exchange'] = True
2020-08-04 12:41:38 +00:00
trades = Trade.query.all()
2020-08-04 17:43:05 +00:00
trades[1].stoploss_order_id = '1234'
2020-08-04 12:41:38 +00:00
assert len(trades) > 2
rc = client_delete(client, f"{BASE_URI}/trades/1")
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json()['result_msg'] == 'Deleted trade 1. Closed 1 open orders.'
2020-08-04 12:41:38 +00:00
assert len(trades) - 1 == len(Trade.query.all())
2020-08-04 17:43:05 +00:00
assert cancel_mock.call_count == 1
2020-08-04 12:41:38 +00:00
2020-08-04 17:43:05 +00:00
cancel_mock.reset_mock()
2020-08-04 12:41:38 +00:00
rc = client_delete(client, f"{BASE_URI}/trades/1")
# Trade is gone now.
assert_response(rc, 502)
2020-08-04 17:43:05 +00:00
assert cancel_mock.call_count == 0
2020-08-04 12:41:38 +00:00
assert len(trades) - 1 == len(Trade.query.all())
rc = client_delete(client, f"{BASE_URI}/trades/2")
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json()['result_msg'] == 'Deleted trade 2. Closed 2 open orders.'
2020-08-04 12:41:38 +00:00
assert len(trades) - 2 == len(Trade.query.all())
2020-08-04 17:43:05 +00:00
assert stoploss_mock.call_count == 1
2020-04-07 17:50:13 +00:00
2020-08-14 17:36:12 +00:00
def test_api_logs(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-08-14 17:36:12 +00:00
rc = client_get(client, f"{BASE_URI}/logs")
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert len(rc.json()) == 2
assert 'logs' in rc.json()
2020-08-14 17:36:12 +00:00
# Using a fixed comparison here would make this test fail!
2020-12-26 16:33:27 +00:00
assert rc.json()['log_count'] > 1
assert len(rc.json()['logs']) == rc.json()['log_count']
2020-08-14 17:36:12 +00:00
2020-12-26 16:33:27 +00:00
assert isinstance(rc.json()['logs'][0], list)
2020-08-14 17:36:12 +00:00
# date
2020-12-26 16:33:27 +00:00
assert isinstance(rc.json()['logs'][0][0], str)
2020-08-14 17:36:12 +00:00
# created_timestamp
2020-12-26 16:33:27 +00:00
assert isinstance(rc.json()['logs'][0][1], float)
assert isinstance(rc.json()['logs'][0][2], str)
assert isinstance(rc.json()['logs'][0][3], str)
assert isinstance(rc.json()['logs'][0][4], str)
2020-08-14 17:36:12 +00:00
2021-01-16 09:01:31 +00:00
rc1 = client_get(client, f"{BASE_URI}/logs?limit=5")
assert_response(rc1)
assert len(rc1.json()) == 2
assert 'logs' in rc1.json()
2020-08-14 18:12:59 +00:00
# Using a fixed comparison here would make this test fail!
if rc1.json()['log_count'] < 5:
2021-01-16 09:01:31 +00:00
# Help debugging random test failure
2021-01-16 09:05:47 +00:00
print(f"rc={rc.json()}")
print(f"rc1={rc1.json()}")
assert rc1.json()['log_count'] > 2
2021-01-16 09:01:31 +00:00
assert len(rc1.json()['logs']) == rc1.json()['log_count']
2020-08-14 18:12:59 +00:00
2020-08-14 17:36:12 +00:00
2019-05-11 12:05:25 +00:00
def test_api_edge_disabled(botclient, mocker, ticker, fee, markets):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2019-05-11 12:05:25 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
get_balances=MagicMock(return_value=ticker),
2019-12-18 15:34:30 +00:00
fetch_ticker=ticker,
2019-05-11 12:05:25 +00:00
get_fee=fee,
markets=PropertyMock(return_value=markets)
)
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/edge")
2019-05-11 12:05:25 +00:00
assert_response(rc, 502)
2020-12-26 16:33:27 +00:00
assert rc.json() == {"error": "Error querying /api/v1/edge: Edge is not enabled."}
2019-05-11 12:05:25 +00:00
@pytest.mark.usefixtures("init_persistence")
2021-09-20 02:24:22 +00:00
# TODO-lev: @pytest.mark.parametrize('is_short', [True, False])
2021-04-10 17:53:00 +00:00
def test_api_profit(botclient, mocker, ticker, fee, markets):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2019-05-11 12:05:25 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
get_balances=MagicMock(return_value=ticker),
2019-12-18 15:34:30 +00:00
fetch_ticker=ticker,
2019-05-11 12:05:25 +00:00
get_fee=fee,
markets=PropertyMock(return_value=markets)
)
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/profit")
assert_response(rc, 200)
2020-12-26 15:43:15 +00:00
assert rc.json()['trade_count'] == 0
2019-05-11 12:05:25 +00:00
2021-09-20 02:24:22 +00:00
create_mock_trades(fee, False)
2019-05-11 12:05:25 +00:00
# Simulate fulfilled LIMIT_BUY order for trade
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/profit")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2021-01-30 09:20:40 +00:00
assert rc.json() == {'avg_duration': ANY,
2021-04-10 17:53:00 +00:00
'best_pair': 'XRP/BTC',
'best_rate': 1.0,
'first_trade_date': ANY,
2020-12-26 15:43:15 +00:00
'first_trade_timestamp': ANY,
2021-04-10 17:53:00 +00:00
'latest_trade_date': '5 minutes ago',
2020-12-26 15:43:15 +00:00
'latest_trade_timestamp': ANY,
2021-04-10 17:53:00 +00:00
'profit_all_coin': -44.0631579,
'profit_all_fiat': -543959.6842755,
'profit_all_percent_mean': -66.41,
'profit_all_ratio_mean': -0.6641100666666667,
'profit_all_percent_sum': -398.47,
'profit_all_ratio_sum': -3.9846604,
2021-07-14 18:59:47 +00:00
'profit_all_percent': -4.41,
'profit_all_ratio': -0.044063014216106644,
2021-04-10 17:53:00 +00:00
'profit_closed_coin': 0.00073913,
'profit_closed_fiat': 9.124559849999999,
'profit_closed_ratio_mean': 0.0075,
'profit_closed_percent_mean': 0.75,
'profit_closed_ratio_sum': 0.015,
'profit_closed_percent_sum': 1.5,
2021-07-14 18:59:47 +00:00
'profit_closed_ratio': 7.391275897987988e-07,
'profit_closed_percent': 0.0,
2021-04-10 17:53:00 +00:00
'trade_count': 6,
'closed_trade_count': 2,
'winning_trades': 2,
2020-12-26 15:43:15 +00:00
'losing_trades': 0,
}
2019-05-11 12:05:25 +00:00
2020-12-07 14:07:08 +00:00
@pytest.mark.usefixtures("init_persistence")
2021-09-20 02:24:22 +00:00
# TODO-lev: @pytest.mark.parametrize('is_short', [True, False])
def test_api_stats(botclient, mocker, ticker, fee, markets):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2020-12-07 14:07:08 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
get_balances=MagicMock(return_value=ticker),
fetch_ticker=ticker,
get_fee=fee,
markets=PropertyMock(return_value=markets)
)
rc = client_get(client, f"{BASE_URI}/stats")
assert_response(rc, 200)
2020-12-26 15:43:15 +00:00
assert 'durations' in rc.json()
assert 'sell_reasons' in rc.json()
2020-12-07 14:07:08 +00:00
2021-09-20 02:24:22 +00:00
create_mock_trades(fee, False)
2020-12-07 14:07:08 +00:00
rc = client_get(client, f"{BASE_URI}/stats")
assert_response(rc, 200)
2020-12-26 15:43:15 +00:00
assert 'durations' in rc.json()
assert 'sell_reasons' in rc.json()
2020-12-07 14:07:08 +00:00
2020-12-26 15:43:15 +00:00
assert 'wins' in rc.json()['durations']
assert 'losses' in rc.json()['durations']
assert 'draws' in rc.json()['durations']
2020-12-07 14:07:08 +00:00
2021-05-15 17:39:46 +00:00
def test_api_performance(botclient, fee):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2019-05-11 12:05:25 +00:00
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_ratio()
2021-05-15 17:39:46 +00:00
trade.close_profit_abs = trade.calc_profit()
Trade.query.session.add(trade)
2019-05-11 12:05:25 +00:00
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_ratio()
2021-05-15 17:39:46 +00:00
trade.close_profit_abs = trade.calc_profit()
Trade.query.session.add(trade)
Trade.query.session.flush()
2019-05-11 12:05:25 +00:00
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/performance")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 15:43:15 +00:00
assert len(rc.json()) == 2
2021-05-15 17:39:46 +00:00
assert rc.json() == [{'count': 1, 'pair': 'LTC/ETH', 'profit': 7.61, 'profit_abs': 0.01872279},
{'count': 1, 'pair': 'XRP/ETH', 'profit': -5.57, 'profit_abs': -0.1150375}]
2019-05-11 12:05:25 +00:00
2021-09-20 02:24:22 +00:00
# TODO-lev: @pytest.mark.parametrize('is_short,side', [
# (True, "short"),
# (False, "long")
# ])
2019-05-15 04:51:23 +00:00
def test_api_status(botclient, mocker, ticker, fee, markets):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
patch_get_signal(ftbot)
2019-05-11 12:05:25 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
get_balances=MagicMock(return_value=ticker),
2019-12-18 15:34:30 +00:00
fetch_ticker=ticker,
2019-05-11 12:05:25 +00:00
get_fee=fee,
2021-04-07 15:10:20 +00:00
markets=PropertyMock(return_value=markets),
fetch_order=MagicMock(return_value={}),
2019-05-11 12:05:25 +00:00
)
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/status")
assert_response(rc, 200)
2020-12-26 16:33:27 +00:00
assert rc.json() == []
2021-09-20 02:24:22 +00:00
create_mock_trades(fee, False)
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/status")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2021-04-07 15:10:20 +00:00
assert len(rc.json()) == 4
assert rc.json()[0] == {
'amount': 123.0,
'amount_requested': 123.0,
2020-12-26 16:33:27 +00:00
'close_date': None,
'close_timestamp': None,
'close_profit': None,
'close_profit_pct': None,
'close_profit_abs': None,
'close_rate': None,
2021-04-07 15:10:20 +00:00
'current_profit': ANY,
'current_profit_pct': ANY,
'current_profit_abs': ANY,
'profit_ratio': ANY,
'profit_pct': ANY,
'profit_abs': ANY,
'profit_fiat': ANY,
2020-12-26 16:33:27 +00:00
'current_rate': 1.099e-05,
'open_date': ANY,
'open_timestamp': ANY,
'open_order': None,
2021-04-07 15:10:20 +00:00
'open_rate': 0.123,
2020-12-26 16:33:27 +00:00
'pair': 'ETH/BTC',
'stake_amount': 0.001,
2021-04-07 15:10:20 +00:00
'stop_loss_abs': ANY,
'stop_loss_pct': ANY,
'stop_loss_ratio': ANY,
2020-12-26 16:33:27 +00:00
'stoploss_order_id': None,
'stoploss_last_update': ANY,
'stoploss_last_update_timestamp': ANY,
2021-04-07 15:10:20 +00:00
'initial_stop_loss_abs': 0.0,
'initial_stop_loss_pct': ANY,
'initial_stop_loss_ratio': ANY,
'stoploss_current_dist': ANY,
'stoploss_current_dist_ratio': ANY,
'stoploss_current_dist_pct': ANY,
'stoploss_entry_dist': ANY,
'stoploss_entry_dist_ratio': ANY,
2020-12-26 16:33:27 +00:00
'trade_id': 1,
2021-04-07 15:10:20 +00:00
'close_rate_requested': ANY,
2020-12-26 16:33:27 +00:00
'fee_close': 0.0025,
'fee_close_cost': None,
'fee_close_currency': None,
'fee_open': 0.0025,
'fee_open_cost': None,
'fee_open_currency': None,
'is_open': True,
2021-04-07 15:10:20 +00:00
'max_rate': ANY,
'min_rate': ANY,
2021-09-20 02:24:22 +00:00
'open_order_id': 'dry_run_buy_long_12345',
2021-04-07 15:10:20 +00:00
'open_rate_requested': ANY,
'open_trade_value': 15.1668225,
2020-12-26 16:33:27 +00:00
'sell_reason': None,
'sell_order_status': None,
'strategy': CURRENT_TEST_STRATEGY,
2021-07-22 06:09:05 +00:00
'buy_tag': None,
2020-12-26 16:33:27 +00:00
'timeframe': 5,
2021-04-20 10:54:22 +00:00
'exchange': 'binance',
2021-04-07 15:10:20 +00:00
}
2019-05-11 12:05:25 +00:00
2021-07-18 03:58:54 +00:00
mocker.patch('freqtrade.exchange.Exchange.get_rate',
2021-02-22 10:44:39 +00:00
MagicMock(side_effect=ExchangeError("Pair 'ETH/BTC' not available")))
rc = client_get(client, f"{BASE_URI}/status")
assert_response(rc)
resp_values = rc.json()
2021-04-07 15:10:20 +00:00
assert len(resp_values) == 4
2021-02-22 11:11:27 +00:00
assert isnan(resp_values[0]['profit_abs'])
2021-02-22 10:44:39 +00:00
2019-05-11 12:05:25 +00:00
def test_api_version(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-05-11 12:05:25 +00:00
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/version")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 15:33:13 +00:00
assert rc.json() == {"version": __version__}
2019-05-11 12:05:25 +00:00
2019-05-15 04:51:23 +00:00
def test_api_blacklist(botclient, mocker):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-05-11 12:05:25 +00:00
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/blacklist")
2019-05-11 12:05:25 +00:00
assert_response(rc)
# DOGE and HOT are not in the markets mock!
2020-12-26 16:33:27 +00:00
assert rc.json() == {"blacklist": ["DOGE/BTC", "HOT/BTC"],
"blacklist_expanded": [],
"length": 2,
"method": ["StaticPairList"],
"errors": {},
}
2019-05-11 12:05:25 +00:00
# Add ETH/BTC to blacklist
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/blacklist",
data='{"blacklist": ["ETH/BTC"]}')
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json() == {"blacklist": ["DOGE/BTC", "HOT/BTC", "ETH/BTC"],
"blacklist_expanded": ["ETH/BTC"],
"length": 3,
"method": ["StaticPairList"],
"errors": {},
}
2019-05-11 12:05:25 +00:00
rc = client_post(client, f"{BASE_URI}/blacklist",
data='{"blacklist": ["XRP/.*"]}')
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json() == {"blacklist": ["DOGE/BTC", "HOT/BTC", "ETH/BTC", "XRP/.*"],
2021-10-01 09:10:43 +00:00
"blacklist_expanded": ["ETH/BTC", "XRP/BTC", "XRP/USDT"],
2020-12-26 16:33:27 +00:00
"length": 4,
"method": ["StaticPairList"],
"errors": {},
}
2019-05-11 12:05:25 +00:00
2019-05-15 04:51:23 +00:00
def test_api_whitelist(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-05-11 12:05:25 +00:00
2019-05-25 12:13:59 +00:00
rc = client_get(client, f"{BASE_URI}/whitelist")
2019-05-11 12:05:25 +00:00
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json() == {
"whitelist": ['ETH/BTC', 'LTC/BTC', 'XRP/BTC', 'NEO/BTC'],
"length": 4,
"method": ["StaticPairList"]
2021-08-06 22:19:36 +00:00
}
2019-05-15 04:51:23 +00:00
def test_api_forcebuy(botclient, mocker, fee):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-05-15 04:51:23 +00:00
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/forcebuy",
2019-05-15 04:51:23 +00:00
data='{"pair": "ETH/BTC"}')
assert_response(rc, 502)
2020-12-26 16:33:27 +00:00
assert rc.json() == {"error": "Error querying /api/v1/forcebuy: Forcebuy not enabled."}
2019-05-15 04:51:23 +00:00
# enable forcebuy
2021-07-23 11:34:18 +00:00
ftbot.config['forcebuy_enable'] = True
2019-05-15 04:51:23 +00:00
fbuy_mock = MagicMock(return_value=None)
mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock)
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/forcebuy",
2019-05-15 04:51:23 +00:00
data='{"pair": "ETH/BTC"}')
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json() == {"status": "Error buying pair ETH/BTC."}
2019-05-15 04:51:23 +00:00
2020-12-26 16:33:27 +00:00
# Test creating trade
2019-05-15 04:51:23 +00:00
fbuy_mock = MagicMock(return_value=Trade(
pair='ETH/ETH',
amount=1,
amount_requested=1,
2021-04-20 10:54:22 +00:00
exchange='binance',
2019-05-15 04:51:23 +00:00
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,
2021-01-01 18:38:28 +00:00
id=22,
timeframe=5,
strategy=CURRENT_TEST_STRATEGY
2019-05-15 04:51:23 +00:00
))
mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock)
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/forcebuy",
2019-05-15 04:51:23 +00:00
data='{"pair": "ETH/BTC"}')
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json() == {
'amount': 1,
'amount_requested': 1,
2021-01-01 18:38:28 +00:00
'trade_id': 22,
2020-12-26 16:33:27 +00:00
'close_date': None,
'close_timestamp': None,
'close_rate': 0.265441,
'open_date': ANY,
'open_timestamp': ANY,
'open_rate': 0.245441,
'pair': 'ETH/ETH',
'stake_amount': 1,
'stop_loss_abs': None,
'stop_loss_pct': None,
'stop_loss_ratio': None,
'stoploss_order_id': None,
'stoploss_last_update': None,
'stoploss_last_update_timestamp': None,
'initial_stop_loss_abs': None,
'initial_stop_loss_pct': None,
'initial_stop_loss_ratio': None,
'close_profit': None,
'close_profit_pct': None,
'close_profit_abs': None,
'close_rate_requested': None,
'profit_ratio': None,
'profit_pct': None,
'profit_abs': None,
2021-04-02 12:35:19 +00:00
'profit_fiat': None,
2020-12-26 16:33:27 +00:00
'fee_close': 0.0025,
'fee_close_cost': None,
'fee_close_currency': None,
'fee_open': 0.0025,
'fee_open_cost': None,
'fee_open_currency': None,
'is_open': False,
'max_rate': None,
'min_rate': None,
'open_order_id': '123456',
'open_rate_requested': None,
'open_trade_value': 0.24605460,
'sell_reason': None,
'sell_order_status': None,
'strategy': CURRENT_TEST_STRATEGY,
2021-07-22 06:09:05 +00:00
'buy_tag': None,
2021-01-01 18:38:28 +00:00
'timeframe': 5,
2021-04-20 10:54:22 +00:00
'exchange': 'binance',
2021-08-06 22:19:36 +00:00
}
2019-05-15 04:51:23 +00:00
2019-05-15 05:00:17 +00:00
def test_api_forcesell(botclient, mocker, ticker, fee, markets):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2019-05-15 05:00:17 +00:00
mocker.patch.multiple(
'freqtrade.exchange.Exchange',
get_balances=MagicMock(return_value=ticker),
2019-12-18 15:34:30 +00:00
fetch_ticker=ticker,
2019-05-15 05:00:17 +00:00
get_fee=fee,
markets=PropertyMock(return_value=markets),
2021-06-05 13:22:52 +00:00
_is_dry_limit_order_filled=MagicMock(return_value=False),
2019-05-15 05:00:17 +00:00
)
patch_get_signal(ftbot)
2019-05-15 05:00:17 +00:00
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/forcesell",
2019-05-15 05:00:17 +00:00
data='{"tradeid": "1"}')
assert_response(rc, 502)
2020-12-26 16:33:27 +00:00
assert rc.json() == {"error": "Error querying /api/v1/forcesell: invalid argument"}
2019-05-15 04:51:23 +00:00
2021-07-23 11:34:18 +00:00
ftbot.enter_positions()
2019-05-15 05:00:17 +00:00
2019-05-25 12:13:59 +00:00
rc = client_post(client, f"{BASE_URI}/forcesell",
2019-05-15 05:00:17 +00:00
data='{"tradeid": "1"}')
assert_response(rc)
2020-12-26 16:33:27 +00:00
assert rc.json() == {'result': 'Created sell order for trade 1.'}
2020-06-15 06:47:43 +00:00
2020-07-02 05:10:56 +00:00
def test_api_pair_candles(botclient, ohlcv_history):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-06-15 06:47:43 +00:00
timeframe = '5m'
2020-12-15 19:49:46 +00:00
amount = 3
# No pair
rc = client_get(client,
f"{BASE_URI}/pair_candles?limit={amount}&timeframe={timeframe}")
2020-12-26 19:05:27 +00:00
assert_response(rc, 422)
# No timeframe
rc = client_get(client,
f"{BASE_URI}/pair_candles?pair=XRP%2FBTC")
2020-12-26 19:05:27 +00:00
assert_response(rc, 422)
rc = client_get(client,
f"{BASE_URI}/pair_candles?limit={amount}&pair=XRP%2FBTC&timeframe={timeframe}")
assert_response(rc)
2020-12-26 19:05:27 +00:00
assert 'columns' in rc.json()
assert 'data_start_ts' in rc.json()
assert 'data_start' in rc.json()
assert 'data_stop' in rc.json()
assert 'data_stop_ts' in rc.json()
assert len(rc.json()['data']) == 0
2020-06-15 06:47:43 +00:00
ohlcv_history['sma'] = ohlcv_history['close'].rolling(2).mean()
2020-07-02 06:39:07 +00:00
ohlcv_history['buy'] = 0
2020-10-02 04:41:28 +00:00
ohlcv_history.loc[1, 'buy'] = 1
2020-07-02 06:39:07 +00:00
ohlcv_history['sell'] = 0
2021-07-23 11:34:18 +00:00
ftbot.dataprovider._set_cached_df("XRP/BTC", timeframe, ohlcv_history)
2020-06-15 06:47:43 +00:00
rc = client_get(client,
2020-07-02 05:10:56 +00:00
f"{BASE_URI}/pair_candles?limit={amount}&pair=XRP%2FBTC&timeframe={timeframe}")
2020-06-15 06:47:43 +00:00
assert_response(rc)
2020-12-26 19:05:27 +00:00
assert 'strategy' in rc.json()
assert rc.json()['strategy'] == CURRENT_TEST_STRATEGY
2020-12-26 19:05:27 +00:00
assert 'columns' in rc.json()
assert 'data_start_ts' in rc.json()
assert 'data_start' in rc.json()
assert 'data_stop' in rc.json()
assert 'data_stop_ts' in rc.json()
assert rc.json()['data_start'] == '2017-11-26 08:50:00+00:00'
assert rc.json()['data_start_ts'] == 1511686200000
assert rc.json()['data_stop'] == '2017-11-26 09:00:00+00:00'
assert rc.json()['data_stop_ts'] == 1511686800000
assert isinstance(rc.json()['columns'], list)
assert rc.json()['columns'] == ['date', 'open', 'high',
2020-12-27 08:02:35 +00:00
'low', 'close', 'volume', 'sma', 'buy', 'sell',
'__date_ts', '_buy_signal_open', '_sell_signal_open']
2020-12-26 19:05:27 +00:00
assert 'pair' in rc.json()
assert rc.json()['pair'] == 'XRP/BTC'
2020-06-15 06:47:43 +00:00
2020-12-26 19:05:27 +00:00
assert 'data' in rc.json()
assert len(rc.json()['data']) == amount
2020-06-15 06:47:43 +00:00
2020-12-26 19:05:27 +00:00
assert (rc.json()['data'] ==
[['2017-11-26 08:50:00', 8.794e-05, 8.948e-05, 8.794e-05, 8.88e-05, 0.0877869,
None, 0, 0, 1511686200000, None, None],
['2017-11-26 08:55:00', 8.88e-05, 8.942e-05, 8.88e-05,
2020-12-15 19:49:46 +00:00
8.893e-05, 0.05874751, 8.886500000000001e-05, 1, 0, 1511686500000, 8.88e-05, None],
['2017-11-26 09:00:00', 8.891e-05, 8.893e-05, 8.875e-05, 8.877e-05,
0.7039405, 8.885e-05, 0, 0, 1511686800000, None, None]
2020-12-15 19:49:46 +00:00
2020-06-15 06:47:43 +00:00
])
2020-06-23 04:49:53 +00:00
2020-09-11 18:45:59 +00:00
def test_api_pair_history(botclient, ohlcv_history):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-09-11 18:45:59 +00:00
timeframe = '5m'
# No pair
rc = client_get(client,
f"{BASE_URI}/pair_history?timeframe={timeframe}"
f"&timerange=20180111-20180112&strategy={CURRENT_TEST_STRATEGY}")
2020-12-26 19:05:27 +00:00
assert_response(rc, 422)
2020-09-11 18:45:59 +00:00
# No Timeframe
rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC"
f"&timerange=20180111-20180112&strategy={CURRENT_TEST_STRATEGY}")
2020-12-26 19:05:27 +00:00
assert_response(rc, 422)
2020-09-11 18:45:59 +00:00
# No timerange
rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}"
f"&strategy={CURRENT_TEST_STRATEGY}")
2020-12-26 19:05:27 +00:00
assert_response(rc, 422)
2020-09-11 18:45:59 +00:00
# No strategy
rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}"
"&timerange=20180111-20180112")
2020-12-26 19:05:27 +00:00
assert_response(rc, 422)
2020-09-11 18:45:59 +00:00
# Working
rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}"
f"&timerange=20180111-20180112&strategy={CURRENT_TEST_STRATEGY}")
2020-09-11 18:45:59 +00:00
assert_response(rc, 200)
2020-12-26 19:05:27 +00:00
assert rc.json()['length'] == 289
assert len(rc.json()['data']) == rc.json()['length']
assert 'columns' in rc.json()
assert 'data' in rc.json()
assert rc.json()['pair'] == 'UNITTEST/BTC'
assert rc.json()['strategy'] == CURRENT_TEST_STRATEGY
2020-12-26 19:05:27 +00:00
assert rc.json()['data_start'] == '2018-01-11 00:00:00+00:00'
assert rc.json()['data_start_ts'] == 1515628800000
assert rc.json()['data_stop'] == '2018-01-12 00:00:00+00:00'
assert rc.json()['data_stop_ts'] == 1515715200000
2020-09-11 18:45:59 +00:00
# No data found
rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}"
f"&timerange=20200111-20200112&strategy={CURRENT_TEST_STRATEGY}")
assert_response(rc, 502)
assert rc.json()['error'] == ("Error querying /api/v1/pair_history: "
"No data for UNITTEST/BTC, 5m in 20200111-20200112 found.")
2020-09-11 18:45:59 +00:00
2020-06-23 04:49:53 +00:00
def test_api_plot_config(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-06-23 04:49:53 +00:00
rc = client_get(client, f"{BASE_URI}/plot_config")
assert_response(rc)
2020-12-26 19:05:27 +00:00
assert rc.json() == {}
2020-06-23 04:49:53 +00:00
2021-07-23 11:34:18 +00:00
ftbot.strategy.plot_config = {
2021-07-20 16:56:03 +00:00
'main_plot': {'sma': {}},
'subplots': {'RSI': {'rsi': {'color': 'red'}}}
}
2020-06-23 04:49:53 +00:00
rc = client_get(client, f"{BASE_URI}/plot_config")
assert_response(rc)
2021-07-23 11:34:18 +00:00
assert rc.json() == ftbot.strategy.plot_config
2020-12-26 19:05:27 +00:00
assert isinstance(rc.json()['main_plot'], dict)
assert isinstance(rc.json()['subplots'], dict)
2021-07-23 11:34:18 +00:00
ftbot.strategy.plot_config = {'main_plot': {'sma': {}}}
rc = client_get(client, f"{BASE_URI}/plot_config")
assert_response(rc)
assert isinstance(rc.json()['main_plot'], dict)
assert isinstance(rc.json()['subplots'], dict)
2020-07-31 05:31:20 +00:00
def test_api_strategies(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-07-31 05:31:20 +00:00
rc = client_get(client, f"{BASE_URI}/strategies")
assert_response(rc)
assert rc.json() == {'strategies': [
'HyperoptableStrategy',
2021-09-19 23:44:12 +00:00
'InformativeDecoratorTest',
2021-08-26 17:38:41 +00:00
'StrategyTestV2',
2021-09-21 17:14:14 +00:00
'StrategyTestV3',
'TestStrategyLegacyV1',
2021-08-06 22:19:36 +00:00
]}
2020-08-01 15:49:59 +00:00
2020-09-17 05:53:22 +00:00
def test_api_strategy(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-09-17 05:53:22 +00:00
rc = client_get(client, f"{BASE_URI}/strategy/{CURRENT_TEST_STRATEGY}")
2020-09-17 05:53:22 +00:00
assert_response(rc)
assert rc.json()['strategy'] == CURRENT_TEST_STRATEGY
2020-09-17 05:53:22 +00:00
data = (Path(__file__).parents[1] / "strategy/strats/strategy_test_v3.py").read_text()
2020-12-26 19:05:27 +00:00
assert rc.json()['code'] == data
2020-09-17 05:53:22 +00:00
rc = client_get(client, f"{BASE_URI}/strategy/NoStrat")
assert_response(rc, 404)
2020-08-01 15:49:59 +00:00
def test_list_available_pairs(botclient):
2021-07-23 11:34:18 +00:00
ftbot, client = botclient
2020-08-01 15:49:59 +00:00
rc = client_get(client, f"{BASE_URI}/available_pairs")
assert_response(rc)
assert rc.json()['length'] == 13
2020-12-26 19:05:27 +00:00
assert isinstance(rc.json()['pairs'], list)
2020-08-01 15:49:59 +00:00
rc = client_get(client, f"{BASE_URI}/available_pairs?timeframe=5m")
assert_response(rc)
2020-12-26 19:05:27 +00:00
assert rc.json()['length'] == 12
2020-08-01 15:49:59 +00:00
rc = client_get(client, f"{BASE_URI}/available_pairs?stake_currency=ETH")
assert_response(rc)
2020-12-26 19:05:27 +00:00
assert rc.json()['length'] == 1
assert rc.json()['pairs'] == ['XRP/ETH']
assert len(rc.json()['pair_interval']) == 2
2020-08-01 15:49:59 +00:00
rc = client_get(client, f"{BASE_URI}/available_pairs?stake_currency=ETH&timeframe=5m")
assert_response(rc)
2020-12-26 19:05:27 +00:00
assert rc.json()['length'] == 1
assert rc.json()['pairs'] == ['XRP/ETH']
assert len(rc.json()['pair_interval']) == 1
2021-04-01 17:59:49 +00:00
2021-10-06 17:36:51 +00:00
def test_sysinfo(botclient):
ftbot, client = botclient
rc = client_get(client, f"{BASE_URI}/sysinfo")
assert_response(rc)
result = rc.json()
assert 'cpu_pct' in result
assert 'ram_pct' in result
def test_api_backtesting(botclient, mocker, fee, caplog):
2021-04-01 17:59:49 +00:00
ftbot, client = botclient
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
# Backtesting not started yet
rc = client_get(client, f"{BASE_URI}/backtest")
assert_response(rc)
result = rc.json()
assert result['status'] == 'not_started'
assert not result['running']
assert result['status_msg'] == 'Backtest not yet executed'
assert result['progress'] == 0
# Reset backtesting
rc = client_delete(client, f"{BASE_URI}/backtest")
assert_response(rc)
result = rc.json()
assert result['status'] == 'reset'
assert not result['running']
assert result['status_msg'] == 'Backtest reset'
# start backtesting
data = {
"strategy": CURRENT_TEST_STRATEGY,
2021-04-01 17:59:49 +00:00
"timeframe": "5m",
"timerange": "20180110-20180111",
"max_open_trades": 3,
"stake_amount": 100,
"dry_run_wallet": 1000,
"enable_protections": False
}
rc = client_post(client, f"{BASE_URI}/backtest", data=json.dumps(data))
assert_response(rc)
result = rc.json()
assert result['status'] == 'running'
assert result['progress'] == 0
assert result['running']
assert result['status_msg'] == 'Backtest started'
rc = client_get(client, f"{BASE_URI}/backtest")
assert_response(rc)
result = rc.json()
assert result['status'] == 'ended'
assert not result['running']
assert result['status_msg'] == 'Backtest ended'
assert result['progress'] == 1
assert result['backtest_result']
rc = client_get(client, f"{BASE_URI}/backtest/abort")
assert_response(rc)
result = rc.json()
assert result['status'] == 'not_running'
assert not result['running']
assert result['status_msg'] == 'Backtest ended'
2021-07-06 19:04:52 +00:00
# Simulate running backtest
ApiServer._bgtask_running = True
rc = client_get(client, f"{BASE_URI}/backtest/abort")
assert_response(rc)
result = rc.json()
assert result['status'] == 'stopping'
assert not result['running']
assert result['status_msg'] == 'Backtest ended'
# Get running backtest...
rc = client_get(client, f"{BASE_URI}/backtest")
assert_response(rc)
result = rc.json()
assert result['status'] == 'running'
assert result['running']
assert result['step'] == "backtest"
assert result['status_msg'] == "Backtest running"
# Try delete with task still running
rc = client_delete(client, f"{BASE_URI}/backtest")
assert_response(rc)
result = rc.json()
assert result['status'] == 'running'
# Post to backtest that's still running
rc = client_post(client, f"{BASE_URI}/backtest", data=json.dumps(data))
assert_response(rc, 502)
result = rc.json()
assert 'Bot Background task already running' in result['error']
ApiServer._bgtask_running = False
mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest_one_strategy',
side_effect=DependencyException())
rc = client_post(client, f"{BASE_URI}/backtest", data=json.dumps(data))
assert log_has("Backtesting caused an error: ", caplog)
2021-04-01 17:59:49 +00:00
# Delete backtesting to avoid leakage since the backtest-object may stick around.
rc = client_delete(client, f"{BASE_URI}/backtest")
assert_response(rc)
result = rc.json()
assert result['status'] == 'reset'
assert not result['running']
assert result['status_msg'] == 'Backtest reset'