| 1 | """ |
| 2 | Unit test file for rpc/api_server.py |
| 3 | """ |
| 4 | |
| 5 | from datetime import datetime, timedelta, timezone |
| 6 | from pathlib import Path |
| 7 | from unittest.mock import ANY, MagicMock, PropertyMock |
| 8 | |
| 9 | import pytest |
| 10 | import uvicorn |
| 11 | from fastapi import FastAPI |
| 12 | from fastapi.exceptions import HTTPException |
| 13 | from fastapi.testclient import TestClient |
| 14 | from numpy import isnan |
| 15 | from requests.auth import _basic_auth_str |
| 16 | |
| 17 | from freqtrade.__init__ import __version__ |
| 18 | from freqtrade.exceptions import ExchangeError |
| 19 | from freqtrade.loggers import setup_logging, setup_logging_pre |
| 20 | from freqtrade.persistence import PairLocks, Trade |
| 21 | from freqtrade.rpc import RPC |
| 22 | from freqtrade.rpc.api_server import ApiServer |
| 23 | from freqtrade.rpc.api_server.api_auth import create_token, get_user_from_token |
| 24 | from freqtrade.rpc.api_server.uvicorn_threaded import UvicornServer |
| 25 | from freqtrade.state import RunMode, State |
| 26 | from tests.conftest import (create_mock_trades, get_mock_coro, get_patched_freqtradebot, log_has, |
| 27 | log_has_re, patch_get_signal) |
| 28 | |
| 29 | |
| 30 | BASE_URI = "/api/v1" |
| 31 | _TEST_USER = "FreqTrader" |
| 32 | _TEST_PASS = "SuperSecurePassword1!" |
| 33 | |
| 34 | |
| 35 | @pytest.fixture |
| 36 | def botclient(default_conf, mocker): |
| 37 | setup_logging_pre() |
| 38 | setup_logging(default_conf) |
| 39 | default_conf['runmode'] = RunMode.DRY_RUN |
| 40 | default_conf.update({"api_server": {"enabled": True, |
| 41 | "listen_ip_address": "127.0.0.1", |
| 42 | "listen_port": 8080, |
| 43 | "CORS_origins": ['http://example.com'], |
| 44 | "username": _TEST_USER, |
| 45 | "password": _TEST_PASS, |
| 46 | }}) |
| 47 | |
| 48 | ftbot = get_patched_freqtradebot(mocker, default_conf) |
| 49 | rpc = RPC(ftbot) |
| 50 | mocker.patch('freqtrade.rpc.api_server.ApiServer.start_api', MagicMock()) |
| 51 | apiserver = ApiServer(rpc, default_conf) |
| 52 | yield ftbot, TestClient(apiserver.app) |
| 53 | # Cleanup ... ? |
| 54 | |
| 55 | |
| 56 | def client_post(client, url, data={}): |
| 57 | return client.post(url, |
| 58 | data=data, |
| 59 | headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS), |
| 60 | 'Origin': 'http://example.com', |
| 61 | 'content-type': 'application/json' |
| 62 | }) |
| 63 | |
| 64 | |
| 65 | def client_get(client, url): |
| 66 | # Add fake Origin to ensure CORS kicks in |
| 67 | return client.get(url, headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS), |
| 68 | 'Origin': 'http://example.com'}) |
| 69 | |
| 70 | |
| 71 | def client_delete(client, url): |
| 72 | # Add fake Origin to ensure CORS kicks in |
| 73 | return client.delete(url, headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS), |
| 74 | 'Origin': 'http://example.com'}) |
| 75 | |
| 76 | |
| 77 | def assert_response(response, expected_code=200, needs_cors=True): |
| 78 | assert response.status_code == expected_code |
| 79 | assert response.headers.get('content-type') == "application/json" |
| 80 | if needs_cors: |
| 81 | assert ('access-control-allow-credentials', 'true') in response.headers.items() |
| 82 | assert ('access-control-allow-origin', 'http://example.com') in response.headers.items() |
| 83 | |
| 84 | |
| 85 | def test_api_not_found(botclient): |
| 86 | ftbot, client = botclient |
| 87 | |
| 88 | rc = client_get(client, f"{BASE_URI}/invalid_url") |
| 89 | assert_response(rc, 404) |
| 90 | assert rc.json() == {"detail": "Not Found"} |
| 91 | |
| 92 | |
| 93 | def test_api_ui_fallback(botclient): |
| 94 | ftbot, client = botclient |
| 95 | |
| 96 | rc = client_get(client, "/favicon.ico") |
| 97 | assert rc.status_code == 200 |
| 98 | |
| 99 | rc = client_get(client, "/fallback_file.html") |
| 100 | assert rc.status_code == 200 |
| 101 | assert '`freqtrade install-ui`' in rc.text |
| 102 | |
| 103 | # Forwarded to fallback_html or index.html (depending if it's installed or not) |
| 104 | rc = client_get(client, "/something") |
| 105 | assert rc.status_code == 200 |
| 106 | |
| 107 | |
| 108 | def test_api_auth(): |
| 109 | with pytest.raises(ValueError): |
| 110 | create_token({'identity': {'u': 'Freqtrade'}}, 'secret1234', token_type="NotATokenType") |
| 111 | |
| 112 | token = create_token({'identity': {'u': 'Freqtrade'}}, 'secret1234') |
| 113 | assert isinstance(token, str) |
| 114 | |
| 115 | u = get_user_from_token(token, 'secret1234') |
| 116 | assert u == 'Freqtrade' |
| 117 | with pytest.raises(HTTPException): |
| 118 | get_user_from_token(token, 'secret1234', token_type='refresh') |
| 119 | # Create invalid token |
| 120 | token = create_token({'identity': {'u1': 'Freqrade'}}, 'secret1234') |
| 121 | with pytest.raises(HTTPException): |
| 122 | get_user_from_token(token, 'secret1234') |
| 123 | |
| 124 | with pytest.raises(HTTPException): |
| 125 | get_user_from_token(b'not_a_token', 'secret1234') |
| 126 | |
| 127 | |
| 128 | def test_api_unauthorized(botclient): |
| 129 | ftbot, client = botclient |
| 130 | rc = client.get(f"{BASE_URI}/ping") |
| 131 | assert_response(rc, needs_cors=False) |
| 132 | assert rc.json() == {'status': 'pong'} |
| 133 | |
| 134 | # Don't send user/pass information |
| 135 | rc = client.get(f"{BASE_URI}/version") |
| 136 | assert_response(rc, 401, needs_cors=False) |
| 137 | assert rc.json() == {'detail': 'Unauthorized'} |
| 138 | |
| 139 | # Change only username |
| 140 | ftbot.config['api_server']['username'] = 'Ftrader' |
| 141 | rc = client_get(client, f"{BASE_URI}/version") |
| 142 | assert_response(rc, 401) |
| 143 | assert rc.json() == {'detail': 'Unauthorized'} |
| 144 | |
| 145 | # Change only password |
| 146 | ftbot.config['api_server']['username'] = _TEST_USER |
| 147 | ftbot.config['api_server']['password'] = 'WrongPassword' |
| 148 | rc = client_get(client, f"{BASE_URI}/version") |
| 149 | assert_response(rc, 401) |
| 150 | assert rc.json() == {'detail': 'Unauthorized'} |
| 151 | |
| 152 | ftbot.config['api_server']['username'] = 'Ftrader' |
| 153 | ftbot.config['api_server']['password'] = 'WrongPassword' |
| 154 | |
| 155 | rc = client_get(client, f"{BASE_URI}/version") |
| 156 | assert_response(rc, 401) |
| 157 | assert rc.json() == {'detail': 'Unauthorized'} |
| 158 | |
| 159 | |
| 160 | def test_api_token_login(botclient): |
| 161 | ftbot, client = botclient |
| 162 | rc = client.post(f"{BASE_URI}/token/login", |
| 163 | data=None, |
| 164 | headers={'Authorization': _basic_auth_str('WRONG_USER', 'WRONG_PASS'), |
| 165 | 'Origin': 'http://example.com'}) |
| 166 | assert_response(rc, 401) |
| 167 | rc = client_post(client, f"{BASE_URI}/token/login") |
| 168 | assert_response(rc) |
| 169 | assert 'access_token' in rc.json() |
| 170 | assert 'refresh_token' in rc.json() |
| 171 | |
| 172 | # test Authentication is working with JWT tokens too |
| 173 | rc = client.get(f"{BASE_URI}/count", |
| 174 | headers={'Authorization': f'Bearer {rc.json()["access_token"]}', |
| 175 | 'Origin': 'http://example.com'}) |
| 176 | assert_response(rc) |
| 177 | |
| 178 | |
| 179 | def test_api_token_refresh(botclient): |
| 180 | ftbot, client = botclient |
| 181 | rc = client_post(client, f"{BASE_URI}/token/login") |
| 182 | assert_response(rc) |
| 183 | rc = client.post(f"{BASE_URI}/token/refresh", |
| 184 | data=None, |
| 185 | headers={'Authorization': f'Bearer {rc.json()["refresh_token"]}', |
| 186 | 'Origin': 'http://example.com'}) |
| 187 | assert_response(rc) |
| 188 | assert 'access_token' in rc.json() |
| 189 | assert 'refresh_token' not in rc.json() |
| 190 | |
| 191 | |
| 192 | def test_api_stop_workflow(botclient): |
| 193 | ftbot, client = botclient |
| 194 | assert ftbot.state == State.RUNNING |
| 195 | rc = client_post(client, f"{BASE_URI}/stop") |
| 196 | assert_response(rc) |
| 197 | assert rc.json() == {'status': 'stopping trader ...'} |
| 198 | assert ftbot.state == State.STOPPED |
| 199 | |
| 200 | # Stop bot again |
| 201 | rc = client_post(client, f"{BASE_URI}/stop") |
| 202 | assert_response(rc) |
| 203 | assert rc.json() == {'status': 'already stopped'} |
| 204 | |
| 205 | # Start bot |
| 206 | rc = client_post(client, f"{BASE_URI}/start") |
| 207 | assert_response(rc) |
| 208 | assert rc.json() == {'status': 'starting trader ...'} |
| 209 | assert ftbot.state == State.RUNNING |
| 210 | |
| 211 | # Call start again |
| 212 | rc = client_post(client, f"{BASE_URI}/start") |
| 213 | assert_response(rc) |
| 214 | assert rc.json() == {'status': 'already running'} |
| 215 | |
| 216 | |
| 217 | def test_api__init__(default_conf, mocker): |
| 218 | """ |
| 219 | Test __init__() method |
| 220 | """ |
| 221 | default_conf.update({"api_server": {"enabled": True, |
| 222 | "listen_ip_address": "127.0.0.1", |
| 223 | "listen_port": 8080, |
| 224 | "username": "TestUser", |
| 225 | "password": "testPass", |
| 226 | }}) |
| 227 | mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) |
| 228 | mocker.patch('freqtrade.rpc.api_server.webserver.ApiServer.start_api', MagicMock()) |
| 229 | apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf) |
| 230 | assert apiserver._config == default_conf |
| 231 | |
| 232 | |
| 233 | def test_api_UvicornServer(mocker): |
| 234 | thread_mock = mocker.patch('freqtrade.rpc.api_server.uvicorn_threaded.threading.Thread') |
| 235 | s = UvicornServer(uvicorn.Config(MagicMock(), port=8080, host='127.0.0.1')) |
| 236 | assert thread_mock.call_count == 0 |
| 237 | |
| 238 | s.install_signal_handlers() |
| 239 | # Original implementation starts a thread - make sure that's not the case |
| 240 | assert thread_mock.call_count == 0 |
| 241 | |
| 242 | # Fake started to avoid sleeping forever |
| 243 | s.started = True |
| 244 | s.run_in_thread() |
| 245 | assert thread_mock.call_count == 1 |
| 246 | |
| 247 | s.cleanup() |
| 248 | assert s.should_exit is True |
| 249 | |
| 250 | |
| 251 | def test_api_UvicornServer_run(mocker): |
| 252 | serve_mock = mocker.patch('freqtrade.rpc.api_server.uvicorn_threaded.UvicornServer.serve', |
| 253 | get_mock_coro(None)) |
| 254 | s = UvicornServer(uvicorn.Config(MagicMock(), port=8080, host='127.0.0.1')) |
| 255 | assert serve_mock.call_count == 0 |
| 256 | |
| 257 | s.install_signal_handlers() |
| 258 | # Original implementation starts a thread - make sure that's not the case |
| 259 | assert serve_mock.call_count == 0 |
| 260 | |
| 261 | # Fake started to avoid sleeping forever |
| 262 | s.started = True |
| 263 | s.run() |
| 264 | assert serve_mock.call_count == 1 |
| 265 | |
| 266 | |
| 267 | def test_api_UvicornServer_run_no_uvloop(mocker, import_fails): |
| 268 | serve_mock = mocker.patch('freqtrade.rpc.api_server.uvicorn_threaded.UvicornServer.serve', |
| 269 | get_mock_coro(None)) |
| 270 | s = UvicornServer(uvicorn.Config(MagicMock(), port=8080, host='127.0.0.1')) |
| 271 | assert serve_mock.call_count == 0 |
| 272 | |
| 273 | s.install_signal_handlers() |
| 274 | # Original implementation starts a thread - make sure that's not the case |
| 275 | assert serve_mock.call_count == 0 |
| 276 | |
| 277 | # Fake started to avoid sleeping forever |
| 278 | s.started = True |
| 279 | s.run() |
| 280 | assert serve_mock.call_count == 1 |
| 281 | |
| 282 | |
| 283 | def test_api_run(default_conf, mocker, caplog): |
| 284 | default_conf.update({"api_server": {"enabled": True, |
| 285 | "listen_ip_address": "127.0.0.1", |
| 286 | "listen_port": 8080, |
| 287 | "username": "TestUser", |
| 288 | "password": "testPass", |
| 289 | }}) |
| 290 | mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) |
| 291 | |
| 292 | server_mock = MagicMock() |
| 293 | mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer', server_mock) |
| 294 | |
| 295 | apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf) |
| 296 | |
| 297 | assert server_mock.call_count == 1 |
| 298 | assert apiserver._config == default_conf |
| 299 | apiserver.start_api() |
| 300 | assert server_mock.call_count == 2 |
| 301 | assert server_mock.call_args_list[0][0][0].host == "127.0.0.1" |
| 302 | assert server_mock.call_args_list[0][0][0].port == 8080 |
| 303 | assert isinstance(server_mock.call_args_list[0][0][0].app, FastAPI) |
| 304 | |
| 305 | assert log_has("Starting HTTP Server at 127.0.0.1:8080", caplog) |
| 306 | assert log_has("Starting Local Rest Server.", caplog) |
| 307 | |
| 308 | # Test binding to public |
| 309 | caplog.clear() |
| 310 | server_mock.reset_mock() |
| 311 | apiserver._config.update({"api_server": {"enabled": True, |
| 312 | "listen_ip_address": "0.0.0.0", |
| 313 | "listen_port": 8089, |
| 314 | "password": "", |
| 315 | }}) |
| 316 | apiserver.start_api() |
| 317 | |
| 318 | assert server_mock.call_count == 1 |
| 319 | assert server_mock.call_args_list[0][0][0].host == "0.0.0.0" |
| 320 | assert server_mock.call_args_list[0][0][0].port == 8089 |
| 321 | assert isinstance(server_mock.call_args_list[0][0][0].app, FastAPI) |
| 322 | assert log_has("Starting HTTP Server at 0.0.0.0:8089", caplog) |
| 323 | assert log_has("Starting Local Rest Server.", caplog) |
| 324 | assert log_has("SECURITY WARNING - Local Rest Server listening to external connections", |
| 325 | caplog) |
| 326 | assert log_has("SECURITY WARNING - This is insecure please set to your loopback," |
| 327 | "e.g 127.0.0.1 in config.json", caplog) |
| 328 | assert log_has("SECURITY WARNING - No password for local REST Server defined. " |
| 329 | "Please make sure that this is intentional!", caplog) |
| 330 | assert log_has_re("SECURITY WARNING - `jwt_secret_key` seems to be default.*", caplog) |
| 331 | |
| 332 | # Test crashing API server |
| 333 | caplog.clear() |
| 334 | mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer', |
| 335 | MagicMock(side_effect=Exception)) |
| 336 | apiserver.start_api() |
| 337 | assert log_has("Api server failed to start.", caplog) |
| 338 | |
| 339 | |
| 340 | def test_api_cleanup(default_conf, mocker, caplog): |
| 341 | default_conf.update({"api_server": {"enabled": True, |
| 342 | "listen_ip_address": "127.0.0.1", |
| 343 | "listen_port": 8080, |
| 344 | "username": "TestUser", |
| 345 | "password": "testPass", |
| 346 | }}) |
| 347 | mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) |
| 348 | |
| 349 | server_mock = MagicMock() |
| 350 | server_mock.cleanup = MagicMock() |
| 351 | mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer', server_mock) |
| 352 | |
| 353 | apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf) |
| 354 | |
| 355 | apiserver.cleanup() |
| 356 | assert apiserver._server.cleanup.call_count == 1 |
| 357 | assert log_has("Stopping API Server", caplog) |
| 358 | |
| 359 | |
| 360 | def test_api_reloadconf(botclient): |
| 361 | ftbot, client = botclient |
| 362 | |
| 363 | rc = client_post(client, f"{BASE_URI}/reload_config") |
| 364 | assert_response(rc) |
| 365 | assert rc.json() == {'status': 'Reloading config ...'} |
| 366 | assert ftbot.state == State.RELOAD_CONFIG |
| 367 | |
| 368 | |
| 369 | def test_api_stopbuy(botclient): |
| 370 | ftbot, client = botclient |
| 371 | assert ftbot.config['max_open_trades'] != 0 |
| 372 | |
| 373 | rc = client_post(client, f"{BASE_URI}/stopbuy") |
| 374 | assert_response(rc) |
| 375 | assert rc.json() == {'status': 'No more buy will occur from now. Run /reload_config to reset.'} |
| 376 | assert ftbot.config['max_open_trades'] == 0 |
| 377 | |
| 378 | |
| 379 | def test_api_balance(botclient, mocker, rpc_balance): |
| 380 | ftbot, client = botclient |
| 381 | |
| 382 | ftbot.config['dry_run'] = False |
| 383 | mocker.patch('freqtrade.exchange.Exchange.get_balances', return_value=rpc_balance) |
| 384 | mocker.patch('freqtrade.exchange.Exchange.get_valid_pair_combination', |
| 385 | side_effect=lambda a, b: f"{a}/{b}") |
| 386 | ftbot.wallets.update() |
| 387 | |
| 388 | rc = client_get(client, f"{BASE_URI}/balance") |
| 389 | assert_response(rc) |
| 390 | assert "currencies" in rc.json() |
| 391 | assert len(rc.json()["currencies"]) == 5 |
| 392 | assert rc.json()['currencies'][0] == { |
| 393 | 'currency': 'BTC', |
| 394 | 'free': 12.0, |
| 395 | 'balance': 12.0, |
| 396 | 'used': 0.0, |
| 397 | 'est_stake': 12.0, |
| 398 | 'stake': 'BTC', |
| 399 | } |
| 400 | |
| 401 | |
| 402 | def test_api_count(botclient, mocker, ticker, fee, markets): |
| 403 | ftbot, client = botclient |
| 404 | patch_get_signal(ftbot, (True, False)) |
| 405 | mocker.patch.multiple( |
| 406 | 'freqtrade.exchange.Exchange', |
| 407 | get_balances=MagicMock(return_value=ticker), |
| 408 | fetch_ticker=ticker, |
| 409 | get_fee=fee, |
| 410 | markets=PropertyMock(return_value=markets) |
| 411 | ) |
| 412 | rc = client_get(client, f"{BASE_URI}/count") |
| 413 | assert_response(rc) |
| 414 | |
| 415 | assert rc.json()["current"] == 0 |
| 416 | assert rc.json()["max"] == 1 |
| 417 | |
| 418 | # Create some test data |
| 419 | create_mock_trades(fee) |
| 420 | rc = client_get(client, f"{BASE_URI}/count") |
| 421 | assert_response(rc) |
| 422 | assert rc.json()["current"] == 4 |
| 423 | assert rc.json()["max"] == 1 |
| 424 | |
| 425 | ftbot.config['max_open_trades'] = float('inf') |
| 426 | rc = client_get(client, f"{BASE_URI}/count") |
| 427 | assert rc.json()["max"] == -1 |
| 428 | |
| 429 | |
| 430 | def test_api_locks(botclient): |
| 431 | ftbot, client = botclient |
| 432 | |
| 433 | rc = client_get(client, f"{BASE_URI}/locks") |
| 434 | assert_response(rc) |
| 435 | |
| 436 | assert 'locks' in rc.json() |
| 437 | |
| 438 | assert rc.json()['lock_count'] == 0 |
| 439 | assert rc.json()['lock_count'] == len(rc.json()['locks']) |
| 440 | |
| 441 | PairLocks.lock_pair('ETH/BTC', datetime.now(timezone.utc) + timedelta(minutes=4), 'randreason') |
| 442 | PairLocks.lock_pair('XRP/BTC', datetime.now(timezone.utc) + timedelta(minutes=20), 'deadbeef') |
| 443 | |
| 444 | rc = client_get(client, f"{BASE_URI}/locks") |
| 445 | assert_response(rc) |
| 446 | |
| 447 | assert rc.json()['lock_count'] == 2 |
| 448 | assert rc.json()['lock_count'] == len(rc.json()['locks']) |
| 449 | assert 'ETH/BTC' in (rc.json()['locks'][0]['pair'], rc.json()['locks'][1]['pair']) |
| 450 | assert 'randreason' in (rc.json()['locks'][0]['reason'], rc.json()['locks'][1]['reason']) |
| 451 | assert 'deadbeef' in (rc.json()['locks'][0]['reason'], rc.json()['locks'][1]['reason']) |
| 452 | |
| 453 | # Test deletions |
| 454 | rc = client_delete(client, f"{BASE_URI}/locks/1") |
| 455 | assert_response(rc) |
| 456 | assert rc.json()['lock_count'] == 1 |
| 457 | |
| 458 | rc = client_post(client, f"{BASE_URI}/locks/delete", |
| 459 | data='{"pair": "XRP/BTC"}') |
| 460 | assert_response(rc) |
| 461 | assert rc.json()['lock_count'] == 0 |
| 462 | |
| 463 | |
| 464 | def test_api_show_config(botclient, mocker): |
| 465 | ftbot, client = botclient |
| 466 | patch_get_signal(ftbot, (True, False)) |
| 467 | |
| 468 | rc = client_get(client, f"{BASE_URI}/show_config") |
| 469 | assert_response(rc) |
| 470 | assert 'dry_run' in rc.json() |
| 471 | assert rc.json()['exchange'] == 'binance' |
| 472 | assert rc.json()['timeframe'] == '5m' |
| 473 | assert rc.json()['timeframe_ms'] == 300000 |
| 474 | assert rc.json()['timeframe_min'] == 5 |
| 475 | assert rc.json()['state'] == 'running' |
| 476 | assert rc.json()['bot_name'] == 'freqtrade' |
| 477 | assert not rc.json()['trailing_stop'] |
| 478 | assert 'bid_strategy' in rc.json() |
| 479 | assert 'ask_strategy' in rc.json() |
| 480 | |
| 481 | |
| 482 | def test_api_daily(botclient, mocker, ticker, fee, markets): |
| 483 | ftbot, client = botclient |
| 484 | patch_get_signal(ftbot, (True, False)) |
| 485 | mocker.patch.multiple( |
| 486 | 'freqtrade.exchange.Exchange', |
| 487 | get_balances=MagicMock(return_value=ticker), |
| 488 | fetch_ticker=ticker, |
| 489 | get_fee=fee, |
| 490 | markets=PropertyMock(return_value=markets) |
| 491 | ) |
| 492 | rc = client_get(client, f"{BASE_URI}/daily") |
| 493 | assert_response(rc) |
| 494 | assert len(rc.json()['data']) == 7 |
| 495 | assert rc.json()['stake_currency'] == 'BTC' |
| 496 | assert rc.json()['fiat_display_currency'] == 'USD' |
| 497 | assert rc.json()['data'][0]['date'] == str(datetime.utcnow().date()) |
| 498 | |
| 499 | |
| 500 | def test_api_trades(botclient, mocker, fee, markets): |
| 501 | ftbot, client = botclient |
| 502 | patch_get_signal(ftbot, (True, False)) |
| 503 | mocker.patch.multiple( |
| 504 | 'freqtrade.exchange.Exchange', |
| 505 | markets=PropertyMock(return_value=markets) |
| 506 | ) |
| 507 | rc = client_get(client, f"{BASE_URI}/trades") |
| 508 | assert_response(rc) |
| 509 | assert len(rc.json()) == 2 |
| 510 | assert rc.json()['trades_count'] == 0 |
| 511 | |
| 512 | create_mock_trades(fee) |
| 513 | Trade.query.session.flush() |
| 514 | |
| 515 | rc = client_get(client, f"{BASE_URI}/trades") |
| 516 | assert_response(rc) |
| 517 | assert len(rc.json()['trades']) == 2 |
| 518 | assert rc.json()['trades_count'] == 2 |
| 519 | rc = client_get(client, f"{BASE_URI}/trades?limit=1") |
| 520 | assert_response(rc) |
| 521 | assert len(rc.json()['trades']) == 1 |
| 522 | assert rc.json()['trades_count'] == 1 |
| 523 | |
| 524 | |
| 525 | def test_api_trade_single(botclient, mocker, fee, ticker, markets): |
| 526 | ftbot, client = botclient |
| 527 | patch_get_signal(ftbot, (True, False)) |
| 528 | mocker.patch.multiple( |
| 529 | 'freqtrade.exchange.Exchange', |
| 530 | markets=PropertyMock(return_value=markets), |
| 531 | fetch_ticker=ticker, |
| 532 | ) |
| 533 | rc = client_get(client, f"{BASE_URI}/trade/3") |
| 534 | assert_response(rc, 404) |
| 535 | assert rc.json()['detail'] == 'Trade not found.' |
| 536 | |
| 537 | create_mock_trades(fee) |
| 538 | Trade.query.session.flush() |
| 539 | |
| 540 | rc = client_get(client, f"{BASE_URI}/trade/3") |
| 541 | assert_response(rc) |
| 542 | assert rc.json()['trade_id'] == 3 |
| 543 | |
| 544 | |
| 545 | def test_api_delete_trade(botclient, mocker, fee, markets): |
| 546 | ftbot, client = botclient |
| 547 | patch_get_signal(ftbot, (True, False)) |
| 548 | stoploss_mock = MagicMock() |
| 549 | cancel_mock = MagicMock() |
| 550 | mocker.patch.multiple( |
| 551 | 'freqtrade.exchange.Exchange', |
| 552 | markets=PropertyMock(return_value=markets), |
| 553 | cancel_order=cancel_mock, |
| 554 | cancel_stoploss_order=stoploss_mock, |
| 555 | ) |
| 556 | rc = client_delete(client, f"{BASE_URI}/trades/1") |
| 557 | # Error - trade won't exist yet. |
| 558 | assert_response(rc, 502) |
| 559 | |
| 560 | create_mock_trades(fee) |
| 561 | Trade.query.session.flush() |
| 562 | ftbot.strategy.order_types['stoploss_on_exchange'] = True |
| 563 | trades = Trade.query.all() |
| 564 | trades[1].stoploss_order_id = '1234' |
| 565 | assert len(trades) > 2 |
| 566 | |
| 567 | rc = client_delete(client, f"{BASE_URI}/trades/1") |
| 568 | assert_response(rc) |
| 569 | assert rc.json()['result_msg'] == 'Deleted trade 1. Closed 1 open orders.' |
| 570 | assert len(trades) - 1 == len(Trade.query.all()) |
| 571 | assert cancel_mock.call_count == 1 |
| 572 | |
| 573 | cancel_mock.reset_mock() |
| 574 | rc = client_delete(client, f"{BASE_URI}/trades/1") |
| 575 | # Trade is gone now. |
| 576 | assert_response(rc, 502) |
| 577 | assert cancel_mock.call_count == 0 |
| 578 | |
| 579 | assert len(trades) - 1 == len(Trade.query.all()) |
| 580 | rc = client_delete(client, f"{BASE_URI}/trades/2") |
| 581 | assert_response(rc) |
| 582 | assert rc.json()['result_msg'] == 'Deleted trade 2. Closed 2 open orders.' |
| 583 | assert len(trades) - 2 == len(Trade.query.all()) |
| 584 | assert stoploss_mock.call_count == 1 |
| 585 | |
| 586 | |
| 587 | def test_api_logs(botclient): |
| 588 | ftbot, client = botclient |
| 589 | rc = client_get(client, f"{BASE_URI}/logs") |
| 590 | assert_response(rc) |
| 591 | assert len(rc.json()) == 2 |
| 592 | assert 'logs' in rc.json() |
| 593 | # Using a fixed comparison here would make this test fail! |
| 594 | assert rc.json()['log_count'] > 1 |
| 595 | assert len(rc.json()['logs']) == rc.json()['log_count'] |
| 596 | |
| 597 | assert isinstance(rc.json()['logs'][0], list) |
| 598 | # date |
| 599 | assert isinstance(rc.json()['logs'][0][0], str) |
| 600 | # created_timestamp |
| 601 | assert isinstance(rc.json()['logs'][0][1], float) |
| 602 | assert isinstance(rc.json()['logs'][0][2], str) |
| 603 | assert isinstance(rc.json()['logs'][0][3], str) |
| 604 | assert isinstance(rc.json()['logs'][0][4], str) |
| 605 | |
| 606 | rc1 = client_get(client, f"{BASE_URI}/logs?limit=5") |
| 607 | assert_response(rc1) |
| 608 | assert len(rc1.json()) == 2 |
| 609 | assert 'logs' in rc1.json() |
| 610 | # Using a fixed comparison here would make this test fail! |
| 611 | if rc1.json()['log_count'] < 5: |
| 612 | # Help debugging random test failure |
| 613 | print(f"rc={rc.json()}") |
| 614 | print(f"rc1={rc1.json()}") |
| 615 | assert rc1.json()['log_count'] == 5 |
| 616 | assert len(rc1.json()['logs']) == rc1.json()['log_count'] |
| 617 | |
| 618 | |
| 619 | def test_api_edge_disabled(botclient, mocker, ticker, fee, markets): |
| 620 | ftbot, client = botclient |
| 621 | patch_get_signal(ftbot, (True, False)) |
| 622 | mocker.patch.multiple( |
| 623 | 'freqtrade.exchange.Exchange', |
| 624 | get_balances=MagicMock(return_value=ticker), |
| 625 | fetch_ticker=ticker, |
| 626 | get_fee=fee, |
| 627 | markets=PropertyMock(return_value=markets) |
| 628 | ) |
| 629 | rc = client_get(client, f"{BASE_URI}/edge") |
| 630 | assert_response(rc, 502) |
| 631 | assert rc.json() == {"error": "Error querying /api/v1/edge: Edge is not enabled."} |
| 632 | |
| 633 | |
| 634 | @pytest.mark.usefixtures("init_persistence") |
| 635 | def test_api_profit(botclient, mocker, ticker, fee, markets): |
| 636 | ftbot, client = botclient |
| 637 | patch_get_signal(ftbot, (True, False)) |
| 638 | mocker.patch.multiple( |
| 639 | 'freqtrade.exchange.Exchange', |
| 640 | get_balances=MagicMock(return_value=ticker), |
| 641 | fetch_ticker=ticker, |
| 642 | get_fee=fee, |
| 643 | markets=PropertyMock(return_value=markets) |
| 644 | ) |
| 645 | |
| 646 | rc = client_get(client, f"{BASE_URI}/profit") |
| 647 | assert_response(rc, 200) |
| 648 | assert rc.json()['trade_count'] == 0 |
| 649 | |
| 650 | create_mock_trades(fee) |
| 651 | # Simulate fulfilled LIMIT_BUY order for trade |
| 652 | |
| 653 | rc = client_get(client, f"{BASE_URI}/profit") |
| 654 | assert_response(rc) |
| 655 | assert rc.json() == {'avg_duration': ANY, |
| 656 | 'best_pair': 'XRP/BTC', |
| 657 | 'best_rate': 1.0, |
| 658 | 'first_trade_date': ANY, |
| 659 | 'first_trade_timestamp': ANY, |
| 660 | 'latest_trade_date': '5 minutes ago', |
| 661 | 'latest_trade_timestamp': ANY, |
| 662 | 'profit_all_coin': -44.0631579, |
| 663 | 'profit_all_fiat': -543959.6842755, |
| 664 | 'profit_all_percent_mean': -66.41, |
| 665 | 'profit_all_ratio_mean': -0.6641100666666667, |
| 666 | 'profit_all_percent_sum': -398.47, |
| 667 | 'profit_all_ratio_sum': -3.9846604, |
| 668 | 'profit_closed_coin': 0.00073913, |
| 669 | 'profit_closed_fiat': 9.124559849999999, |
| 670 | 'profit_closed_ratio_mean': 0.0075, |
| 671 | 'profit_closed_percent_mean': 0.75, |
| 672 | 'profit_closed_ratio_sum': 0.015, |
| 673 | 'profit_closed_percent_sum': 1.5, |
| 674 | 'trade_count': 6, |
| 675 | 'closed_trade_count': 2, |
| 676 | 'winning_trades': 2, |
| 677 | 'losing_trades': 0, |
| 678 | } |
| 679 | |
| 680 | |
| 681 | @pytest.mark.usefixtures("init_persistence") |
| 682 | def test_api_stats(botclient, mocker, ticker, fee, markets,): |
| 683 | ftbot, client = botclient |
| 684 | patch_get_signal(ftbot, (True, False)) |
| 685 | mocker.patch.multiple( |
| 686 | 'freqtrade.exchange.Exchange', |
| 687 | get_balances=MagicMock(return_value=ticker), |
| 688 | fetch_ticker=ticker, |
| 689 | get_fee=fee, |
| 690 | markets=PropertyMock(return_value=markets) |
| 691 | ) |
| 692 | |
| 693 | rc = client_get(client, f"{BASE_URI}/stats") |
| 694 | assert_response(rc, 200) |
| 695 | assert 'durations' in rc.json() |
| 696 | assert 'sell_reasons' in rc.json() |
| 697 | |
| 698 | create_mock_trades(fee) |
| 699 | |
| 700 | rc = client_get(client, f"{BASE_URI}/stats") |
| 701 | assert_response(rc, 200) |
| 702 | assert 'durations' in rc.json() |
| 703 | assert 'sell_reasons' in rc.json() |
| 704 | |
| 705 | assert 'wins' in rc.json()['durations'] |
| 706 | assert 'losses' in rc.json()['durations'] |
| 707 | assert 'draws' in rc.json()['durations'] |
| 708 | |
| 709 | |
| 710 | def test_api_performance(botclient, mocker, ticker, fee): |
| 711 | ftbot, client = botclient |
| 712 | patch_get_signal(ftbot, (True, False)) |
| 713 | |
| 714 | trade = Trade( |
| 715 | pair='LTC/ETH', |
| 716 | amount=1, |
| 717 | exchange='binance', |
| 718 | stake_amount=1, |
| 719 | open_rate=0.245441, |
| 720 | open_order_id="123456", |
| 721 | is_open=False, |
| 722 | fee_close=fee.return_value, |
| 723 | fee_open=fee.return_value, |
| 724 | close_rate=0.265441, |
| 725 | |
| 726 | ) |
| 727 | trade.close_profit = trade.calc_profit_ratio() |
| 728 | Trade.query.session.add(trade) |
| 729 | |
| 730 | trade = Trade( |
| 731 | pair='XRP/ETH', |
| 732 | amount=5, |
| 733 | stake_amount=1, |
| 734 | exchange='binance', |
| 735 | open_rate=0.412, |
| 736 | open_order_id="123456", |
| 737 | is_open=False, |
| 738 | fee_close=fee.return_value, |
| 739 | fee_open=fee.return_value, |
| 740 | close_rate=0.391 |
| 741 | ) |
| 742 | trade.close_profit = trade.calc_profit_ratio() |
| 743 | Trade.query.session.add(trade) |
| 744 | Trade.query.session.flush() |
| 745 | |
| 746 | rc = client_get(client, f"{BASE_URI}/performance") |
| 747 | assert_response(rc) |
| 748 | assert len(rc.json()) == 2 |
| 749 | assert rc.json() == [{'count': 1, 'pair': 'LTC/ETH', 'profit': 7.61}, |
| 750 | {'count': 1, 'pair': 'XRP/ETH', 'profit': -5.57}] |
| 751 | |
| 752 | |
| 753 | def test_api_status(botclient, mocker, ticker, fee, markets): |
| 754 | ftbot, client = botclient |
| 755 | patch_get_signal(ftbot, (True, False)) |
| 756 | mocker.patch.multiple( |
| 757 | 'freqtrade.exchange.Exchange', |
| 758 | get_balances=MagicMock(return_value=ticker), |
| 759 | fetch_ticker=ticker, |
| 760 | get_fee=fee, |
| 761 | markets=PropertyMock(return_value=markets), |
| 762 | fetch_order=MagicMock(return_value={}), |
| 763 | ) |
| 764 | |
| 765 | rc = client_get(client, f"{BASE_URI}/status") |
| 766 | assert_response(rc, 200) |
| 767 | assert rc.json() == [] |
| 768 | create_mock_trades(fee) |
| 769 | |
| 770 | rc = client_get(client, f"{BASE_URI}/status") |
| 771 | assert_response(rc) |
| 772 | assert len(rc.json()) == 4 |
| 773 | assert rc.json()[0] == { |
| 774 | 'amount': 123.0, |
| 775 | 'amount_requested': 123.0, |
| 776 | 'close_date': None, |
| 777 | 'close_timestamp': None, |
| 778 | 'close_profit': None, |
| 779 | 'close_profit_pct': None, |
| 780 | 'close_profit_abs': None, |
| 781 | 'close_rate': None, |
| 782 | 'current_profit': ANY, |
| 783 | 'current_profit_pct': ANY, |
| 784 | 'current_profit_abs': ANY, |
| 785 | 'profit_ratio': ANY, |
| 786 | 'profit_pct': ANY, |
| 787 | 'profit_abs': ANY, |
| 788 | 'profit_fiat': ANY, |
| 789 | 'current_rate': 1.099e-05, |
| 790 | 'open_date': ANY, |
| 791 | 'open_timestamp': ANY, |
| 792 | 'open_order': None, |
| 793 | 'open_rate': 0.123, |
| 794 | 'pair': 'ETH/BTC', |
| 795 | 'stake_amount': 0.001, |
| 796 | 'stop_loss_abs': ANY, |
| 797 | 'stop_loss_pct': ANY, |
| 798 | 'stop_loss_ratio': ANY, |
| 799 | 'stoploss_order_id': None, |
| 800 | 'stoploss_last_update': ANY, |
| 801 | 'stoploss_last_update_timestamp': ANY, |
| 802 | 'initial_stop_loss_abs': 0.0, |
| 803 | 'initial_stop_loss_pct': ANY, |
| 804 | 'initial_stop_loss_ratio': ANY, |
| 805 | 'stoploss_current_dist': ANY, |
| 806 | 'stoploss_current_dist_ratio': ANY, |
| 807 | 'stoploss_current_dist_pct': ANY, |
| 808 | 'stoploss_entry_dist': ANY, |
| 809 | 'stoploss_entry_dist_ratio': ANY, |
| 810 | 'trade_id': 1, |
| 811 | 'close_rate_requested': ANY, |
| 812 | 'fee_close': 0.0025, |
| 813 | 'fee_close_cost': None, |
| 814 | 'fee_close_currency': None, |
| 815 | 'fee_open': 0.0025, |
| 816 | 'fee_open_cost': None, |
| 817 | 'fee_open_currency': None, |
| 818 | 'is_open': True, |
| 819 | 'max_rate': ANY, |
| 820 | 'min_rate': ANY, |
| 821 | 'open_order_id': 'dry_run_buy_12345', |
| 822 | 'open_rate_requested': ANY, |
| 823 | 'open_trade_value': 15.1668225, |
| 824 | 'sell_reason': None, |
| 825 | 'sell_order_status': None, |
| 826 | 'strategy': 'DefaultStrategy', |
| 827 | 'timeframe': 5, |
| 828 | 'exchange': 'binance', |
| 829 | } |
| 830 | |
| 831 | mocker.patch('freqtrade.freqtradebot.FreqtradeBot.get_sell_rate', |
| 832 | MagicMock(side_effect=ExchangeError("Pair 'ETH/BTC' not available"))) |
| 833 | |
| 834 | rc = client_get(client, f"{BASE_URI}/status") |
| 835 | assert_response(rc) |
| 836 | resp_values = rc.json() |
| 837 | assert len(resp_values) == 4 |
| 838 | assert isnan(resp_values[0]['profit_abs']) |
| 839 | |
| 840 | |
| 841 | def test_api_version(botclient): |
| 842 | ftbot, client = botclient |
| 843 | |
| 844 | rc = client_get(client, f"{BASE_URI}/version") |
| 845 | assert_response(rc) |
| 846 | assert rc.json() == {"version": __version__} |
| 847 | |
| 848 | |
| 849 | def test_api_blacklist(botclient, mocker): |
| 850 | ftbot, client = botclient |
| 851 | |
| 852 | rc = client_get(client, f"{BASE_URI}/blacklist") |
| 853 | assert_response(rc) |
| 854 | # DOGE and HOT are not in the markets mock! |
| 855 | assert rc.json() == {"blacklist": ["DOGE/BTC", "HOT/BTC"], |
| 856 | "blacklist_expanded": [], |
| 857 | "length": 2, |
| 858 | "method": ["StaticPairList"], |
| 859 | "errors": {}, |
| 860 | } |
| 861 | |
| 862 | # Add ETH/BTC to blacklist |
| 863 | rc = client_post(client, f"{BASE_URI}/blacklist", |
| 864 | data='{"blacklist": ["ETH/BTC"]}') |
| 865 | assert_response(rc) |
| 866 | assert rc.json() == {"blacklist": ["DOGE/BTC", "HOT/BTC", "ETH/BTC"], |
| 867 | "blacklist_expanded": ["ETH/BTC"], |
| 868 | "length": 3, |
| 869 | "method": ["StaticPairList"], |
| 870 | "errors": {}, |
| 871 | } |
| 872 | |
| 873 | rc = client_post(client, f"{BASE_URI}/blacklist", |
| 874 | data='{"blacklist": ["XRP/.*"]}') |
| 875 | assert_response(rc) |
| 876 | assert rc.json() == {"blacklist": ["DOGE/BTC", "HOT/BTC", "ETH/BTC", "XRP/.*"], |
| 877 | "blacklist_expanded": ["ETH/BTC", "XRP/BTC"], |
| 878 | "length": 4, |
| 879 | "method": ["StaticPairList"], |
| 880 | "errors": {}, |
| 881 | } |
| 882 | |
| 883 | |
| 884 | def test_api_whitelist(botclient): |
| 885 | ftbot, client = botclient |
| 886 | |
| 887 | rc = client_get(client, f"{BASE_URI}/whitelist") |
| 888 | assert_response(rc) |
| 889 | assert rc.json() == { |
| 890 | "whitelist": ['ETH/BTC', 'LTC/BTC', 'XRP/BTC', 'NEO/BTC'], |
| 891 | "length": 4, |
| 892 | "method": ["StaticPairList"] |
| 893 | } |
| 894 | |
| 895 | |
| 896 | def test_api_forcebuy(botclient, mocker, fee): |
| 897 | ftbot, client = botclient |
| 898 | |
| 899 | rc = client_post(client, f"{BASE_URI}/forcebuy", |
| 900 | data='{"pair": "ETH/BTC"}') |
| 901 | assert_response(rc, 502) |
| 902 | assert rc.json() == {"error": "Error querying /api/v1/forcebuy: Forcebuy not enabled."} |
| 903 | |
| 904 | # enable forcebuy |
| 905 | ftbot.config['forcebuy_enable'] = True |
| 906 | |
| 907 | fbuy_mock = MagicMock(return_value=None) |
| 908 | mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) |
| 909 | rc = client_post(client, f"{BASE_URI}/forcebuy", |
| 910 | data='{"pair": "ETH/BTC"}') |
| 911 | assert_response(rc) |
| 912 | assert rc.json() == {"status": "Error buying pair ETH/BTC."} |
| 913 | |
| 914 | # Test creating trade |
| 915 | fbuy_mock = MagicMock(return_value=Trade( |
| 916 | pair='ETH/ETH', |
| 917 | amount=1, |
| 918 | amount_requested=1, |
| 919 | exchange='binance', |
| 920 | stake_amount=1, |
| 921 | open_rate=0.245441, |
| 922 | open_order_id="123456", |
| 923 | open_date=datetime.utcnow(), |
| 924 | is_open=False, |
| 925 | fee_close=fee.return_value, |
| 926 | fee_open=fee.return_value, |
| 927 | close_rate=0.265441, |
| 928 | id=22, |
| 929 | timeframe=5, |
| 930 | strategy="DefaultStrategy" |
| 931 | )) |
| 932 | mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) |
| 933 | |
| 934 | rc = client_post(client, f"{BASE_URI}/forcebuy", |
| 935 | data='{"pair": "ETH/BTC"}') |
| 936 | assert_response(rc) |
| 937 | assert rc.json() == { |
| 938 | 'amount': 1, |
| 939 | 'amount_requested': 1, |
| 940 | 'trade_id': 22, |
| 941 | 'close_date': None, |
| 942 | 'close_timestamp': None, |
| 943 | 'close_rate': 0.265441, |
| 944 | 'open_date': ANY, |
| 945 | 'open_timestamp': ANY, |
| 946 | 'open_rate': 0.245441, |
| 947 | 'pair': 'ETH/ETH', |
| 948 | 'stake_amount': 1, |
| 949 | 'stop_loss_abs': None, |
| 950 | 'stop_loss_pct': None, |
| 951 | 'stop_loss_ratio': None, |
| 952 | 'stoploss_order_id': None, |
| 953 | 'stoploss_last_update': None, |
| 954 | 'stoploss_last_update_timestamp': None, |
| 955 | 'initial_stop_loss_abs': None, |
| 956 | 'initial_stop_loss_pct': None, |
| 957 | 'initial_stop_loss_ratio': None, |
| 958 | 'close_profit': None, |
| 959 | 'close_profit_pct': None, |
| 960 | 'close_profit_abs': None, |
| 961 | 'close_rate_requested': None, |
| 962 | 'profit_ratio': None, |
| 963 | 'profit_pct': None, |
| 964 | 'profit_abs': None, |
| 965 | 'profit_fiat': None, |
| 966 | 'fee_close': 0.0025, |
| 967 | 'fee_close_cost': None, |
| 968 | 'fee_close_currency': None, |
| 969 | 'fee_open': 0.0025, |
| 970 | 'fee_open_cost': None, |
| 971 | 'fee_open_currency': None, |
| 972 | 'is_open': False, |
| 973 | 'max_rate': None, |
| 974 | 'min_rate': None, |
| 975 | 'open_order_id': '123456', |
| 976 | 'open_rate_requested': None, |
| 977 | 'open_trade_value': 0.24605460, |
| 978 | 'sell_reason': None, |
| 979 | 'sell_order_status': None, |
| 980 | 'strategy': 'DefaultStrategy', |
| 981 | 'timeframe': 5, |
| 982 | 'exchange': 'binance', |
| 983 | } |
| 984 | |
| 985 | |
| 986 | def test_api_forcesell(botclient, mocker, ticker, fee, markets): |
| 987 | ftbot, client = botclient |
| 988 | mocker.patch.multiple( |
| 989 | 'freqtrade.exchange.Exchange', |
| 990 | get_balances=MagicMock(return_value=ticker), |
| 991 | fetch_ticker=ticker, |
| 992 | get_fee=fee, |
| 993 | markets=PropertyMock(return_value=markets) |
| 994 | ) |
| 995 | patch_get_signal(ftbot, (True, False)) |
| 996 | |
| 997 | rc = client_post(client, f"{BASE_URI}/forcesell", |
| 998 | data='{"tradeid": "1"}') |
| 999 | assert_response(rc, 502) |
| 1000 | assert rc.json() == {"error": "Error querying /api/v1/forcesell: invalid argument"} |
| 1001 | |
| 1002 | ftbot.enter_positions() |
| 1003 | |
| 1004 | rc = client_post(client, f"{BASE_URI}/forcesell", |
| 1005 | data='{"tradeid": "1"}') |
| 1006 | assert_response(rc) |
| 1007 | assert rc.json() == {'result': 'Created sell order for trade 1.'} |
| 1008 | |
| 1009 | |
| 1010 | def test_api_pair_candles(botclient, ohlcv_history): |
| 1011 | ftbot, client = botclient |
| 1012 | timeframe = '5m' |
| 1013 | amount = 3 |
| 1014 | |
| 1015 | # No pair |
| 1016 | rc = client_get(client, |
| 1017 | f"{BASE_URI}/pair_candles?limit={amount}&timeframe={timeframe}") |
| 1018 | assert_response(rc, 422) |
| 1019 | |
| 1020 | # No timeframe |
| 1021 | rc = client_get(client, |
| 1022 | f"{BASE_URI}/pair_candles?pair=XRP%2FBTC") |
| 1023 | assert_response(rc, 422) |
| 1024 | |
| 1025 | rc = client_get(client, |
| 1026 | f"{BASE_URI}/pair_candles?limit={amount}&pair=XRP%2FBTC&timeframe={timeframe}") |
| 1027 | assert_response(rc) |
| 1028 | assert 'columns' in rc.json() |
| 1029 | assert 'data_start_ts' in rc.json() |
| 1030 | assert 'data_start' in rc.json() |
| 1031 | assert 'data_stop' in rc.json() |
| 1032 | assert 'data_stop_ts' in rc.json() |
| 1033 | assert len(rc.json()['data']) == 0 |
| 1034 | ohlcv_history['sma'] = ohlcv_history['close'].rolling(2).mean() |
| 1035 | ohlcv_history['buy'] = 0 |
| 1036 | ohlcv_history.loc[1, 'buy'] = 1 |
| 1037 | ohlcv_history['sell'] = 0 |
| 1038 | |
| 1039 | ftbot.dataprovider._set_cached_df("XRP/BTC", timeframe, ohlcv_history) |
| 1040 | |
| 1041 | rc = client_get(client, |
| 1042 | f"{BASE_URI}/pair_candles?limit={amount}&pair=XRP%2FBTC&timeframe={timeframe}") |
| 1043 | assert_response(rc) |
| 1044 | assert 'strategy' in rc.json() |
| 1045 | assert rc.json()['strategy'] == 'DefaultStrategy' |
| 1046 | assert 'columns' in rc.json() |
| 1047 | assert 'data_start_ts' in rc.json() |
| 1048 | assert 'data_start' in rc.json() |
| 1049 | assert 'data_stop' in rc.json() |
| 1050 | assert 'data_stop_ts' in rc.json() |
| 1051 | assert rc.json()['data_start'] == '2017-11-26 08:50:00+00:00' |
| 1052 | assert rc.json()['data_start_ts'] == 1511686200000 |
| 1053 | assert rc.json()['data_stop'] == '2017-11-26 09:00:00+00:00' |
| 1054 | assert rc.json()['data_stop_ts'] == 1511686800000 |
| 1055 | assert isinstance(rc.json()['columns'], list) |
| 1056 | assert rc.json()['columns'] == ['date', 'open', 'high', |
| 1057 | 'low', 'close', 'volume', 'sma', 'buy', 'sell', |
| 1058 | '__date_ts', '_buy_signal_open', '_sell_signal_open'] |
| 1059 | assert 'pair' in rc.json() |
| 1060 | assert rc.json()['pair'] == 'XRP/BTC' |
| 1061 | |
| 1062 | assert 'data' in rc.json() |
| 1063 | assert len(rc.json()['data']) == amount |
| 1064 | |
| 1065 | assert (rc.json()['data'] == |
| 1066 | [['2017-11-26 08:50:00', 8.794e-05, 8.948e-05, 8.794e-05, 8.88e-05, 0.0877869, |
| 1067 | None, 0, 0, 1511686200000, None, None], |
| 1068 | ['2017-11-26 08:55:00', 8.88e-05, 8.942e-05, 8.88e-05, |
| 1069 | 8.893e-05, 0.05874751, 8.886500000000001e-05, 1, 0, 1511686500000, 8.88e-05, None], |
| 1070 | ['2017-11-26 09:00:00', 8.891e-05, 8.893e-05, 8.875e-05, 8.877e-05, |
| 1071 | 0.7039405, 8.885e-05, 0, 0, 1511686800000, None, None] |
| 1072 | |
| 1073 | ]) |
| 1074 | |
| 1075 | |
| 1076 | def test_api_pair_history(botclient, ohlcv_history): |
| 1077 | ftbot, client = botclient |
| 1078 | timeframe = '5m' |
| 1079 | |
| 1080 | # No pair |
| 1081 | rc = client_get(client, |
| 1082 | f"{BASE_URI}/pair_history?timeframe={timeframe}" |
| 1083 | "&timerange=20180111-20180112&strategy=DefaultStrategy") |
| 1084 | assert_response(rc, 422) |
| 1085 | |
| 1086 | # No Timeframe |
| 1087 | rc = client_get(client, |
| 1088 | f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC" |
| 1089 | "&timerange=20180111-20180112&strategy=DefaultStrategy") |
| 1090 | assert_response(rc, 422) |
| 1091 | |
| 1092 | # No timerange |
| 1093 | rc = client_get(client, |
| 1094 | f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}" |
| 1095 | "&strategy=DefaultStrategy") |
| 1096 | assert_response(rc, 422) |
| 1097 | |
| 1098 | # No strategy |
| 1099 | rc = client_get(client, |
| 1100 | f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}" |
| 1101 | "&timerange=20180111-20180112") |
| 1102 | assert_response(rc, 422) |
| 1103 | |
| 1104 | # Working |
| 1105 | rc = client_get(client, |
| 1106 | f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}" |
| 1107 | "&timerange=20180111-20180112&strategy=DefaultStrategy") |
| 1108 | assert_response(rc, 200) |
| 1109 | assert rc.json()['length'] == 289 |
| 1110 | assert len(rc.json()['data']) == rc.json()['length'] |
| 1111 | assert 'columns' in rc.json() |
| 1112 | assert 'data' in rc.json() |
| 1113 | assert rc.json()['pair'] == 'UNITTEST/BTC' |
| 1114 | assert rc.json()['strategy'] == 'DefaultStrategy' |
| 1115 | assert rc.json()['data_start'] == '2018-01-11 00:00:00+00:00' |
| 1116 | assert rc.json()['data_start_ts'] == 1515628800000 |
| 1117 | assert rc.json()['data_stop'] == '2018-01-12 00:00:00+00:00' |
| 1118 | assert rc.json()['data_stop_ts'] == 1515715200000 |
| 1119 | |
| 1120 | # No data found |
| 1121 | rc = client_get(client, |
| 1122 | f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}" |
| 1123 | "&timerange=20200111-20200112&strategy=DefaultStrategy") |
| 1124 | assert_response(rc, 502) |
| 1125 | assert rc.json()['error'] == ("Error querying /api/v1/pair_history: " |
| 1126 | "No data for UNITTEST/BTC, 5m in 20200111-20200112 found.") |
| 1127 | |
| 1128 | |
| 1129 | def test_api_plot_config(botclient): |
| 1130 | ftbot, client = botclient |
| 1131 | |
| 1132 | rc = client_get(client, f"{BASE_URI}/plot_config") |
| 1133 | assert_response(rc) |
| 1134 | assert rc.json() == {} |
| 1135 | |
| 1136 | ftbot.strategy.plot_config = {'main_plot': {'sma': {}}, |
| 1137 | 'subplots': {'RSI': {'rsi': {'color': 'red'}}}} |
| 1138 | rc = client_get(client, f"{BASE_URI}/plot_config") |
| 1139 | assert_response(rc) |
| 1140 | assert rc.json() == ftbot.strategy.plot_config |
| 1141 | assert isinstance(rc.json()['main_plot'], dict) |
| 1142 | |
| 1143 | |
| 1144 | def test_api_strategies(botclient): |
| 1145 | ftbot, client = botclient |
| 1146 | |
| 1147 | rc = client_get(client, f"{BASE_URI}/strategies") |
| 1148 | |
| 1149 | assert_response(rc) |
| 1150 | assert rc.json() == {'strategies': [ |
| 1151 | 'DefaultStrategy', |
| 1152 | 'HyperoptableStrategy', |
| 1153 | 'TestStrategyLegacy' |
| 1154 | ]} |
| 1155 | |
| 1156 | |
| 1157 | def test_api_strategy(botclient): |
| 1158 | ftbot, client = botclient |
| 1159 | |
| 1160 | rc = client_get(client, f"{BASE_URI}/strategy/DefaultStrategy") |
| 1161 | |
| 1162 | assert_response(rc) |
| 1163 | assert rc.json()['strategy'] == 'DefaultStrategy' |
| 1164 | |
| 1165 | data = (Path(__file__).parents[1] / "strategy/strats/default_strategy.py").read_text() |
| 1166 | assert rc.json()['code'] == data |
| 1167 | |
| 1168 | rc = client_get(client, f"{BASE_URI}/strategy/NoStrat") |
| 1169 | assert_response(rc, 404) |
| 1170 | |
| 1171 | |
| 1172 | def test_list_available_pairs(botclient): |
| 1173 | ftbot, client = botclient |
| 1174 | |
| 1175 | rc = client_get(client, f"{BASE_URI}/available_pairs") |
| 1176 | |
| 1177 | assert_response(rc) |
| 1178 | assert rc.json()['length'] == 13 |
| 1179 | assert isinstance(rc.json()['pairs'], list) |
| 1180 | |
| 1181 | rc = client_get(client, f"{BASE_URI}/available_pairs?timeframe=5m") |
| 1182 | assert_response(rc) |
| 1183 | assert rc.json()['length'] == 12 |
| 1184 | |
| 1185 | rc = client_get(client, f"{BASE_URI}/available_pairs?stake_currency=ETH") |
| 1186 | assert_response(rc) |
| 1187 | assert rc.json()['length'] == 1 |
| 1188 | assert rc.json()['pairs'] == ['XRP/ETH'] |
| 1189 | assert len(rc.json()['pair_interval']) == 2 |
| 1190 | |
| 1191 | rc = client_get(client, f"{BASE_URI}/available_pairs?stake_currency=ETH&timeframe=5m") |
| 1192 | assert_response(rc) |
| 1193 | assert rc.json()['length'] == 1 |
| 1194 | assert rc.json()['pairs'] == ['XRP/ETH'] |
| 1195 | assert len(rc.json()['pair_interval']) == 1 |