| 1 | import copy |
| 2 | import logging |
| 3 | from datetime import datetime, timedelta, timezone |
| 4 | from math import isclose |
| 5 | from random import randint |
| 6 | from unittest.mock import MagicMock, Mock, PropertyMock, patch |
| 7 | |
| 8 | import arrow |
| 9 | import ccxt |
| 10 | import pytest |
| 11 | from pandas import DataFrame |
| 12 | |
| 13 | from freqtrade.exceptions import (DDosProtection, DependencyException, InvalidOrderException, |
| 14 | OperationalException, TemporaryError) |
| 15 | from freqtrade.exchange import Binance, Bittrex, Exchange, Kraken |
| 16 | from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT, API_RETRY_COUNT, |
| 17 | calculate_backoff) |
| 18 | from freqtrade.exchange.exchange import (market_is_active, timeframe_to_minutes, timeframe_to_msecs, |
| 19 | timeframe_to_next_date, timeframe_to_prev_date, |
| 20 | timeframe_to_seconds) |
| 21 | from freqtrade.resolvers.exchange_resolver import ExchangeResolver |
| 22 | from tests.conftest import get_mock_coro, get_patched_exchange, log_has, log_has_re |
| 23 | |
| 24 | |
| 25 | # Make sure to always keep one exchange here which is NOT subclassed!! |
| 26 | EXCHANGES = ['bittrex', 'binance', 'kraken', 'ftx'] |
| 27 | |
| 28 | |
| 29 | def ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 30 | fun, mock_ccxt_fun, retries=API_RETRY_COUNT + 1, **kwargs): |
| 31 | |
| 32 | with patch('freqtrade.exchange.common.time.sleep'): |
| 33 | with pytest.raises(DDosProtection): |
| 34 | api_mock.__dict__[mock_ccxt_fun] = MagicMock(side_effect=ccxt.DDoSProtection("DDos")) |
| 35 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 36 | getattr(exchange, fun)(**kwargs) |
| 37 | assert api_mock.__dict__[mock_ccxt_fun].call_count == retries |
| 38 | |
| 39 | with pytest.raises(TemporaryError): |
| 40 | api_mock.__dict__[mock_ccxt_fun] = MagicMock(side_effect=ccxt.NetworkError("DeaDBeef")) |
| 41 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 42 | getattr(exchange, fun)(**kwargs) |
| 43 | assert api_mock.__dict__[mock_ccxt_fun].call_count == retries |
| 44 | |
| 45 | with pytest.raises(OperationalException): |
| 46 | api_mock.__dict__[mock_ccxt_fun] = MagicMock(side_effect=ccxt.BaseError("DeadBeef")) |
| 47 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 48 | getattr(exchange, fun)(**kwargs) |
| 49 | assert api_mock.__dict__[mock_ccxt_fun].call_count == 1 |
| 50 | |
| 51 | |
| 52 | async def async_ccxt_exception(mocker, default_conf, api_mock, fun, mock_ccxt_fun, |
| 53 | retries=API_RETRY_COUNT + 1, **kwargs): |
| 54 | |
| 55 | with patch('freqtrade.exchange.common.asyncio.sleep', get_mock_coro(None)): |
| 56 | with pytest.raises(DDosProtection): |
| 57 | api_mock.__dict__[mock_ccxt_fun] = MagicMock(side_effect=ccxt.DDoSProtection("Dooh")) |
| 58 | exchange = get_patched_exchange(mocker, default_conf, api_mock) |
| 59 | await getattr(exchange, fun)(**kwargs) |
| 60 | assert api_mock.__dict__[mock_ccxt_fun].call_count == retries |
| 61 | |
| 62 | with pytest.raises(TemporaryError): |
| 63 | api_mock.__dict__[mock_ccxt_fun] = MagicMock(side_effect=ccxt.NetworkError("DeadBeef")) |
| 64 | exchange = get_patched_exchange(mocker, default_conf, api_mock) |
| 65 | await getattr(exchange, fun)(**kwargs) |
| 66 | assert api_mock.__dict__[mock_ccxt_fun].call_count == retries |
| 67 | |
| 68 | with pytest.raises(OperationalException): |
| 69 | api_mock.__dict__[mock_ccxt_fun] = MagicMock(side_effect=ccxt.BaseError("DeadBeef")) |
| 70 | exchange = get_patched_exchange(mocker, default_conf, api_mock) |
| 71 | await getattr(exchange, fun)(**kwargs) |
| 72 | assert api_mock.__dict__[mock_ccxt_fun].call_count == 1 |
| 73 | |
| 74 | |
| 75 | def test_init(default_conf, mocker, caplog): |
| 76 | caplog.set_level(logging.INFO) |
| 77 | get_patched_exchange(mocker, default_conf) |
| 78 | assert log_has('Instance is running with dry_run enabled', caplog) |
| 79 | |
| 80 | |
| 81 | def test_init_ccxt_kwargs(default_conf, mocker, caplog): |
| 82 | mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={})) |
| 83 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 84 | caplog.set_level(logging.INFO) |
| 85 | conf = copy.deepcopy(default_conf) |
| 86 | conf['exchange']['ccxt_async_config'] = {'aiohttp_trust_env': True, 'asyncio_loop': True} |
| 87 | ex = Exchange(conf) |
| 88 | assert log_has( |
| 89 | "Applying additional ccxt config: {'aiohttp_trust_env': True, 'asyncio_loop': True}", |
| 90 | caplog) |
| 91 | assert ex._api_async.aiohttp_trust_env |
| 92 | assert not ex._api.aiohttp_trust_env |
| 93 | |
| 94 | # Reset logging and config |
| 95 | caplog.clear() |
| 96 | conf = copy.deepcopy(default_conf) |
| 97 | conf['exchange']['ccxt_config'] = {'TestKWARG': 11} |
| 98 | conf['exchange']['ccxt_sync_config'] = {'TestKWARG44': 11} |
| 99 | conf['exchange']['ccxt_async_config'] = {'asyncio_loop': True} |
| 100 | asynclogmsg = "Applying additional ccxt config: {'TestKWARG': 11, 'asyncio_loop': True}" |
| 101 | ex = Exchange(conf) |
| 102 | assert not ex._api_async.aiohttp_trust_env |
| 103 | assert hasattr(ex._api, 'TestKWARG') |
| 104 | assert ex._api.TestKWARG == 11 |
| 105 | # ccxt_config is assigned to both sync and async |
| 106 | assert not hasattr(ex._api_async, 'TestKWARG44') |
| 107 | |
| 108 | assert hasattr(ex._api_async, 'TestKWARG') |
| 109 | assert log_has("Applying additional ccxt config: {'TestKWARG': 11, 'TestKWARG44': 11}", caplog) |
| 110 | assert log_has(asynclogmsg, caplog) |
| 111 | |
| 112 | |
| 113 | def test_destroy(default_conf, mocker, caplog): |
| 114 | caplog.set_level(logging.DEBUG) |
| 115 | get_patched_exchange(mocker, default_conf) |
| 116 | assert log_has('Exchange object destroyed, closing async loop', caplog) |
| 117 | |
| 118 | |
| 119 | def test_init_exception(default_conf, mocker): |
| 120 | default_conf['exchange']['name'] = 'wrong_exchange_name' |
| 121 | |
| 122 | with pytest.raises(OperationalException, |
| 123 | match=f"Exchange {default_conf['exchange']['name']} is not supported"): |
| 124 | Exchange(default_conf) |
| 125 | |
| 126 | default_conf['exchange']['name'] = 'binance' |
| 127 | with pytest.raises(OperationalException, |
| 128 | match=f"Exchange {default_conf['exchange']['name']} is not supported"): |
| 129 | mocker.patch("ccxt.binance", MagicMock(side_effect=AttributeError)) |
| 130 | Exchange(default_conf) |
| 131 | |
| 132 | with pytest.raises(OperationalException, |
| 133 | match=r"Initialization of ccxt failed. Reason: DeadBeef"): |
| 134 | mocker.patch("ccxt.binance", MagicMock(side_effect=ccxt.BaseError("DeadBeef"))) |
| 135 | Exchange(default_conf) |
| 136 | |
| 137 | |
| 138 | def test_exchange_resolver(default_conf, mocker, caplog): |
| 139 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=MagicMock())) |
| 140 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 141 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 142 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 143 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 144 | |
| 145 | exchange = ExchangeResolver.load_exchange('huobi', default_conf) |
| 146 | assert isinstance(exchange, Exchange) |
| 147 | assert log_has_re(r"No .* specific subclass found. Using the generic class instead.", caplog) |
| 148 | caplog.clear() |
| 149 | |
| 150 | exchange = ExchangeResolver.load_exchange('Bittrex', default_conf) |
| 151 | assert isinstance(exchange, Exchange) |
| 152 | assert isinstance(exchange, Bittrex) |
| 153 | assert not log_has_re(r"No .* specific subclass found. Using the generic class instead.", |
| 154 | caplog) |
| 155 | caplog.clear() |
| 156 | |
| 157 | exchange = ExchangeResolver.load_exchange('kraken', default_conf) |
| 158 | assert isinstance(exchange, Exchange) |
| 159 | assert isinstance(exchange, Kraken) |
| 160 | assert not isinstance(exchange, Binance) |
| 161 | assert not log_has_re(r"No .* specific subclass found. Using the generic class instead.", |
| 162 | caplog) |
| 163 | |
| 164 | exchange = ExchangeResolver.load_exchange('binance', default_conf) |
| 165 | assert isinstance(exchange, Exchange) |
| 166 | assert isinstance(exchange, Binance) |
| 167 | assert not isinstance(exchange, Kraken) |
| 168 | |
| 169 | assert not log_has_re(r"No .* specific subclass found. Using the generic class instead.", |
| 170 | caplog) |
| 171 | |
| 172 | # Test mapping |
| 173 | exchange = ExchangeResolver.load_exchange('binanceus', default_conf) |
| 174 | assert isinstance(exchange, Exchange) |
| 175 | assert isinstance(exchange, Binance) |
| 176 | assert not isinstance(exchange, Kraken) |
| 177 | |
| 178 | |
| 179 | def test_validate_order_time_in_force(default_conf, mocker, caplog): |
| 180 | caplog.set_level(logging.INFO) |
| 181 | # explicitly test bittrex, exchanges implementing other policies need seperate tests |
| 182 | ex = get_patched_exchange(mocker, default_conf, id="bittrex") |
| 183 | tif = { |
| 184 | "buy": "gtc", |
| 185 | "sell": "gtc", |
| 186 | } |
| 187 | |
| 188 | ex.validate_order_time_in_force(tif) |
| 189 | tif2 = { |
| 190 | "buy": "fok", |
| 191 | "sell": "ioc", |
| 192 | } |
| 193 | with pytest.raises(OperationalException, match=r"Time in force.*not supported for .*"): |
| 194 | ex.validate_order_time_in_force(tif2) |
| 195 | |
| 196 | # Patch to see if this will pass if the values are in the ft dict |
| 197 | ex._ft_has.update({"order_time_in_force": ["gtc", "fok", "ioc"]}) |
| 198 | ex.validate_order_time_in_force(tif2) |
| 199 | |
| 200 | |
| 201 | @pytest.mark.parametrize("amount,precision_mode,precision,expected", [ |
| 202 | (2.34559, 2, 4, 2.3455), |
| 203 | (2.34559, 2, 5, 2.34559), |
| 204 | (2.34559, 2, 3, 2.345), |
| 205 | (2.9999, 2, 3, 2.999), |
| 206 | (2.9909, 2, 3, 2.990), |
| 207 | # Tests for Tick-size |
| 208 | (2.34559, 4, 0.0001, 2.3455), |
| 209 | (2.34559, 4, 0.00001, 2.34559), |
| 210 | (2.34559, 4, 0.001, 2.345), |
| 211 | (2.9999, 4, 0.001, 2.999), |
| 212 | (2.9909, 4, 0.001, 2.990), |
| 213 | (2.9909, 4, 0.005, 2.990), |
| 214 | (2.9999, 4, 0.005, 2.995), |
| 215 | ]) |
| 216 | def test_amount_to_precision(default_conf, mocker, amount, precision_mode, precision, expected): |
| 217 | ''' |
| 218 | Test rounds down |
| 219 | ''' |
| 220 | |
| 221 | markets = PropertyMock(return_value={'ETH/BTC': {'precision': {'amount': precision}}}) |
| 222 | |
| 223 | exchange = get_patched_exchange(mocker, default_conf, id="binance") |
| 224 | # digits counting mode |
| 225 | # DECIMAL_PLACES = 2 |
| 226 | # SIGNIFICANT_DIGITS = 3 |
| 227 | # TICK_SIZE = 4 |
| 228 | mocker.patch('freqtrade.exchange.Exchange.precisionMode', |
| 229 | PropertyMock(return_value=precision_mode)) |
| 230 | mocker.patch('freqtrade.exchange.Exchange.markets', markets) |
| 231 | |
| 232 | pair = 'ETH/BTC' |
| 233 | assert exchange.amount_to_precision(pair, amount) == expected |
| 234 | |
| 235 | |
| 236 | @pytest.mark.parametrize("price,precision_mode,precision,expected", [ |
| 237 | (2.34559, 2, 4, 2.3456), |
| 238 | (2.34559, 2, 5, 2.34559), |
| 239 | (2.34559, 2, 3, 2.346), |
| 240 | (2.9999, 2, 3, 3.000), |
| 241 | (2.9909, 2, 3, 2.991), |
| 242 | # Tests for Tick_size |
| 243 | (2.34559, 4, 0.0001, 2.3456), |
| 244 | (2.34559, 4, 0.00001, 2.34559), |
| 245 | (2.34559, 4, 0.001, 2.346), |
| 246 | (2.9999, 4, 0.001, 3.000), |
| 247 | (2.9909, 4, 0.001, 2.991), |
| 248 | (2.9909, 4, 0.005, 2.995), |
| 249 | (2.9973, 4, 0.005, 3.0), |
| 250 | (2.9977, 4, 0.005, 3.0), |
| 251 | (234.43, 4, 0.5, 234.5), |
| 252 | (234.53, 4, 0.5, 235.0), |
| 253 | (0.891534, 4, 0.0001, 0.8916), |
| 254 | |
| 255 | ]) |
| 256 | def test_price_to_precision(default_conf, mocker, price, precision_mode, precision, expected): |
| 257 | ''' |
| 258 | Test price to precision |
| 259 | ''' |
| 260 | markets = PropertyMock(return_value={'ETH/BTC': {'precision': {'price': precision}}}) |
| 261 | |
| 262 | exchange = get_patched_exchange(mocker, default_conf, id="binance") |
| 263 | mocker.patch('freqtrade.exchange.Exchange.markets', markets) |
| 264 | # digits counting mode |
| 265 | # DECIMAL_PLACES = 2 |
| 266 | # SIGNIFICANT_DIGITS = 3 |
| 267 | # TICK_SIZE = 4 |
| 268 | mocker.patch('freqtrade.exchange.Exchange.precisionMode', |
| 269 | PropertyMock(return_value=precision_mode)) |
| 270 | |
| 271 | pair = 'ETH/BTC' |
| 272 | assert pytest.approx(exchange.price_to_precision(pair, price)) == expected |
| 273 | |
| 274 | |
| 275 | @pytest.mark.parametrize("price,precision_mode,precision,expected", [ |
| 276 | (2.34559, 2, 4, 0.0001), |
| 277 | (2.34559, 2, 5, 0.00001), |
| 278 | (2.34559, 2, 3, 0.001), |
| 279 | (2.9999, 2, 3, 0.001), |
| 280 | (200.0511, 2, 3, 0.001), |
| 281 | # Tests for Tick_size |
| 282 | (2.34559, 4, 0.0001, 0.0001), |
| 283 | (2.34559, 4, 0.00001, 0.00001), |
| 284 | (2.34559, 4, 0.0025, 0.0025), |
| 285 | (2.9909, 4, 0.0025, 0.0025), |
| 286 | (234.43, 4, 0.5, 0.5), |
| 287 | (234.43, 4, 0.0025, 0.0025), |
| 288 | (234.43, 4, 0.00013, 0.00013), |
| 289 | |
| 290 | ]) |
| 291 | def test_price_get_one_pip(default_conf, mocker, price, precision_mode, precision, expected): |
| 292 | markets = PropertyMock(return_value={'ETH/BTC': {'precision': {'price': precision}}}) |
| 293 | exchange = get_patched_exchange(mocker, default_conf, id="binance") |
| 294 | mocker.patch('freqtrade.exchange.Exchange.markets', markets) |
| 295 | mocker.patch('freqtrade.exchange.Exchange.precisionMode', |
| 296 | PropertyMock(return_value=precision_mode)) |
| 297 | pair = 'ETH/BTC' |
| 298 | assert pytest.approx(exchange.price_get_one_pip(pair, price)) == expected |
| 299 | |
| 300 | |
| 301 | def test_get_min_pair_stake_amount(mocker, default_conf) -> None: |
| 302 | |
| 303 | exchange = get_patched_exchange(mocker, default_conf, id="binance") |
| 304 | stoploss = -0.05 |
| 305 | markets = {'ETH/BTC': {'symbol': 'ETH/BTC'}} |
| 306 | |
| 307 | # no pair found |
| 308 | mocker.patch( |
| 309 | 'freqtrade.exchange.Exchange.markets', |
| 310 | PropertyMock(return_value=markets) |
| 311 | ) |
| 312 | with pytest.raises(ValueError, match=r'.*get market information.*'): |
| 313 | exchange.get_min_pair_stake_amount('BNB/BTC', 1, stoploss) |
| 314 | |
| 315 | # no 'limits' section |
| 316 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) |
| 317 | assert result is None |
| 318 | |
| 319 | # empty 'limits' section |
| 320 | markets["ETH/BTC"]["limits"] = {} |
| 321 | mocker.patch( |
| 322 | 'freqtrade.exchange.Exchange.markets', |
| 323 | PropertyMock(return_value=markets) |
| 324 | ) |
| 325 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) |
| 326 | assert result is None |
| 327 | |
| 328 | # no cost Min |
| 329 | markets["ETH/BTC"]["limits"] = { |
| 330 | 'cost': {"min": None}, |
| 331 | 'amount': {} |
| 332 | } |
| 333 | mocker.patch( |
| 334 | 'freqtrade.exchange.Exchange.markets', |
| 335 | PropertyMock(return_value=markets) |
| 336 | ) |
| 337 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) |
| 338 | assert result is None |
| 339 | |
| 340 | # no amount Min |
| 341 | markets["ETH/BTC"]["limits"] = { |
| 342 | 'cost': {}, |
| 343 | 'amount': {"min": None} |
| 344 | } |
| 345 | mocker.patch( |
| 346 | 'freqtrade.exchange.Exchange.markets', |
| 347 | PropertyMock(return_value=markets) |
| 348 | ) |
| 349 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) |
| 350 | assert result is None |
| 351 | |
| 352 | # empty 'cost'/'amount' section |
| 353 | markets["ETH/BTC"]["limits"] = { |
| 354 | 'cost': {}, |
| 355 | 'amount': {} |
| 356 | } |
| 357 | mocker.patch( |
| 358 | 'freqtrade.exchange.Exchange.markets', |
| 359 | PropertyMock(return_value=markets) |
| 360 | ) |
| 361 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) |
| 362 | assert result is None |
| 363 | |
| 364 | # min cost is set |
| 365 | markets["ETH/BTC"]["limits"] = { |
| 366 | 'cost': {'min': 2}, |
| 367 | 'amount': {} |
| 368 | } |
| 369 | mocker.patch( |
| 370 | 'freqtrade.exchange.Exchange.markets', |
| 371 | PropertyMock(return_value=markets) |
| 372 | ) |
| 373 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) |
| 374 | assert isclose(result, 2 * (1+0.05) / (1-abs(stoploss))) |
| 375 | |
| 376 | # min amount is set |
| 377 | markets["ETH/BTC"]["limits"] = { |
| 378 | 'cost': {}, |
| 379 | 'amount': {'min': 2} |
| 380 | } |
| 381 | mocker.patch( |
| 382 | 'freqtrade.exchange.Exchange.markets', |
| 383 | PropertyMock(return_value=markets) |
| 384 | ) |
| 385 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) |
| 386 | assert isclose(result, 2 * 2 * (1+0.05) / (1-abs(stoploss))) |
| 387 | |
| 388 | # min amount and cost are set (cost is minimal) |
| 389 | markets["ETH/BTC"]["limits"] = { |
| 390 | 'cost': {'min': 2}, |
| 391 | 'amount': {'min': 2} |
| 392 | } |
| 393 | mocker.patch( |
| 394 | 'freqtrade.exchange.Exchange.markets', |
| 395 | PropertyMock(return_value=markets) |
| 396 | ) |
| 397 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) |
| 398 | assert isclose(result, max(2, 2 * 2) * (1+0.05) / (1-abs(stoploss))) |
| 399 | |
| 400 | # min amount and cost are set (amount is minial) |
| 401 | markets["ETH/BTC"]["limits"] = { |
| 402 | 'cost': {'min': 8}, |
| 403 | 'amount': {'min': 2} |
| 404 | } |
| 405 | mocker.patch( |
| 406 | 'freqtrade.exchange.Exchange.markets', |
| 407 | PropertyMock(return_value=markets) |
| 408 | ) |
| 409 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) |
| 410 | assert isclose(result, max(8, 2 * 2) * (1+0.05) / (1-abs(stoploss))) |
| 411 | |
| 412 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4) |
| 413 | assert isclose(result, max(8, 2 * 2) * 1.5) |
| 414 | |
| 415 | # Really big stoploss |
| 416 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1) |
| 417 | assert isclose(result, max(8, 2 * 2) * 1.5) |
| 418 | |
| 419 | |
| 420 | def test_get_min_pair_stake_amount_real_data(mocker, default_conf) -> None: |
| 421 | exchange = get_patched_exchange(mocker, default_conf, id="binance") |
| 422 | stoploss = -0.05 |
| 423 | markets = {'ETH/BTC': {'symbol': 'ETH/BTC'}} |
| 424 | |
| 425 | # Real Binance data |
| 426 | markets["ETH/BTC"]["limits"] = { |
| 427 | 'cost': {'min': 0.0001}, |
| 428 | 'amount': {'min': 0.001} |
| 429 | } |
| 430 | mocker.patch( |
| 431 | 'freqtrade.exchange.Exchange.markets', |
| 432 | PropertyMock(return_value=markets) |
| 433 | ) |
| 434 | result = exchange.get_min_pair_stake_amount('ETH/BTC', 0.020405, stoploss) |
| 435 | assert round(result, 8) == round( |
| 436 | max(0.0001, 0.001 * 0.020405) * (1+0.05) / (1-abs(stoploss)), |
| 437 | 8 |
| 438 | ) |
| 439 | |
| 440 | |
| 441 | def test_set_sandbox(default_conf, mocker): |
| 442 | """ |
| 443 | Test working scenario |
| 444 | """ |
| 445 | api_mock = MagicMock() |
| 446 | api_mock.load_markets = MagicMock(return_value={ |
| 447 | 'ETH/BTC': '', 'LTC/BTC': '', 'XRP/BTC': '', 'NEO/BTC': '' |
| 448 | }) |
| 449 | url_mock = PropertyMock(return_value={'test': "api-public.sandbox.gdax.com", |
| 450 | 'api': 'https://api.gdax.com'}) |
| 451 | type(api_mock).urls = url_mock |
| 452 | exchange = get_patched_exchange(mocker, default_conf, api_mock) |
| 453 | liveurl = exchange._api.urls['api'] |
| 454 | default_conf['exchange']['sandbox'] = True |
| 455 | exchange.set_sandbox(exchange._api, default_conf['exchange'], 'Logname') |
| 456 | assert exchange._api.urls['api'] != liveurl |
| 457 | |
| 458 | |
| 459 | def test_set_sandbox_exception(default_conf, mocker): |
| 460 | """ |
| 461 | Test Fail scenario |
| 462 | """ |
| 463 | api_mock = MagicMock() |
| 464 | api_mock.load_markets = MagicMock(return_value={ |
| 465 | 'ETH/BTC': '', 'LTC/BTC': '', 'XRP/BTC': '', 'NEO/BTC': '' |
| 466 | }) |
| 467 | url_mock = PropertyMock(return_value={'api': 'https://api.gdax.com'}) |
| 468 | type(api_mock).urls = url_mock |
| 469 | |
| 470 | with pytest.raises(OperationalException, match=r'does not provide a sandbox api'): |
| 471 | exchange = get_patched_exchange(mocker, default_conf, api_mock) |
| 472 | default_conf['exchange']['sandbox'] = True |
| 473 | exchange.set_sandbox(exchange._api, default_conf['exchange'], 'Logname') |
| 474 | |
| 475 | |
| 476 | def test__load_async_markets(default_conf, mocker, caplog): |
| 477 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt') |
| 478 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 479 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 480 | mocker.patch('freqtrade.exchange.Exchange._load_markets') |
| 481 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 482 | exchange = Exchange(default_conf) |
| 483 | exchange._api_async.load_markets = get_mock_coro(None) |
| 484 | exchange._load_async_markets() |
| 485 | assert exchange._api_async.load_markets.call_count == 1 |
| 486 | caplog.set_level(logging.DEBUG) |
| 487 | |
| 488 | exchange._api_async.load_markets = Mock(side_effect=ccxt.BaseError("deadbeef")) |
| 489 | exchange._load_async_markets() |
| 490 | |
| 491 | assert log_has('Could not load async markets. Reason: deadbeef', caplog) |
| 492 | |
| 493 | |
| 494 | def test__load_markets(default_conf, mocker, caplog): |
| 495 | caplog.set_level(logging.INFO) |
| 496 | api_mock = MagicMock() |
| 497 | api_mock.load_markets = MagicMock(side_effect=ccxt.BaseError("SomeError")) |
| 498 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 499 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 500 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 501 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 502 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 503 | Exchange(default_conf) |
| 504 | assert log_has('Unable to initialize markets.', caplog) |
| 505 | |
| 506 | expected_return = {'ETH/BTC': 'available'} |
| 507 | api_mock = MagicMock() |
| 508 | api_mock.load_markets = MagicMock(return_value=expected_return) |
| 509 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 510 | default_conf['exchange']['pair_whitelist'] = ['ETH/BTC'] |
| 511 | ex = Exchange(default_conf) |
| 512 | |
| 513 | assert ex.markets == expected_return |
| 514 | |
| 515 | |
| 516 | def test_reload_markets(default_conf, mocker, caplog): |
| 517 | caplog.set_level(logging.DEBUG) |
| 518 | initial_markets = {'ETH/BTC': {}} |
| 519 | updated_markets = {'ETH/BTC': {}, "LTC/BTC": {}} |
| 520 | |
| 521 | api_mock = MagicMock() |
| 522 | api_mock.load_markets = MagicMock(return_value=initial_markets) |
| 523 | default_conf['exchange']['markets_refresh_interval'] = 10 |
| 524 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id="binance", |
| 525 | mock_markets=False) |
| 526 | exchange._load_async_markets = MagicMock() |
| 527 | exchange._last_markets_refresh = arrow.utcnow().int_timestamp |
| 528 | |
| 529 | assert exchange.markets == initial_markets |
| 530 | |
| 531 | # less than 10 minutes have passed, no reload |
| 532 | exchange.reload_markets() |
| 533 | assert exchange.markets == initial_markets |
| 534 | assert exchange._load_async_markets.call_count == 0 |
| 535 | |
| 536 | api_mock.load_markets = MagicMock(return_value=updated_markets) |
| 537 | # more than 10 minutes have passed, reload is executed |
| 538 | exchange._last_markets_refresh = arrow.utcnow().int_timestamp - 15 * 60 |
| 539 | exchange.reload_markets() |
| 540 | assert exchange.markets == updated_markets |
| 541 | assert exchange._load_async_markets.call_count == 1 |
| 542 | assert log_has('Performing scheduled market reload..', caplog) |
| 543 | |
| 544 | |
| 545 | def test_reload_markets_exception(default_conf, mocker, caplog): |
| 546 | caplog.set_level(logging.DEBUG) |
| 547 | |
| 548 | api_mock = MagicMock() |
| 549 | api_mock.load_markets = MagicMock(side_effect=ccxt.NetworkError("LoadError")) |
| 550 | default_conf['exchange']['markets_refresh_interval'] = 10 |
| 551 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id="binance") |
| 552 | |
| 553 | # less than 10 minutes have passed, no reload |
| 554 | exchange.reload_markets() |
| 555 | assert exchange._last_markets_refresh == 0 |
| 556 | assert log_has_re(r"Could not reload markets.*", caplog) |
| 557 | |
| 558 | |
| 559 | @pytest.mark.parametrize("stake_currency", ['ETH', 'BTC', 'USDT']) |
| 560 | def test_validate_stake_currency(default_conf, stake_currency, mocker, caplog): |
| 561 | default_conf['stake_currency'] = stake_currency |
| 562 | api_mock = MagicMock() |
| 563 | type(api_mock).load_markets = MagicMock(return_value={ |
| 564 | 'ETH/BTC': {'quote': 'BTC'}, 'LTC/BTC': {'quote': 'BTC'}, |
| 565 | 'XRP/ETH': {'quote': 'ETH'}, 'NEO/USDT': {'quote': 'USDT'}, |
| 566 | }) |
| 567 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 568 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 569 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 570 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 571 | Exchange(default_conf) |
| 572 | |
| 573 | |
| 574 | def test_validate_stake_currency_error(default_conf, mocker, caplog): |
| 575 | default_conf['stake_currency'] = 'XRP' |
| 576 | api_mock = MagicMock() |
| 577 | type(api_mock).load_markets = MagicMock(return_value={ |
| 578 | 'ETH/BTC': {'quote': 'BTC'}, 'LTC/BTC': {'quote': 'BTC'}, |
| 579 | 'XRP/ETH': {'quote': 'ETH'}, 'NEO/USDT': {'quote': 'USDT'}, |
| 580 | }) |
| 581 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 582 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 583 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 584 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 585 | with pytest.raises(OperationalException, |
| 586 | match=r'XRP is not available as stake on .*' |
| 587 | 'Available currencies are: BTC, ETH, USDT'): |
| 588 | Exchange(default_conf) |
| 589 | |
| 590 | |
| 591 | def test_get_quote_currencies(default_conf, mocker): |
| 592 | ex = get_patched_exchange(mocker, default_conf) |
| 593 | |
| 594 | assert set(ex.get_quote_currencies()) == set(['USD', 'ETH', 'BTC', 'USDT']) |
| 595 | |
| 596 | |
| 597 | @pytest.mark.parametrize('pair,expected', [ |
| 598 | ('XRP/BTC', 'BTC'), |
| 599 | ('LTC/USD', 'USD'), |
| 600 | ('ETH/USDT', 'USDT'), |
| 601 | ('XLTCUSDT', 'USDT'), |
| 602 | ('XRP/NOCURRENCY', ''), |
| 603 | ]) |
| 604 | def test_get_pair_quote_currency(default_conf, mocker, pair, expected): |
| 605 | ex = get_patched_exchange(mocker, default_conf) |
| 606 | assert ex.get_pair_quote_currency(pair) == expected |
| 607 | |
| 608 | |
| 609 | @pytest.mark.parametrize('pair,expected', [ |
| 610 | ('XRP/BTC', 'XRP'), |
| 611 | ('LTC/USD', 'LTC'), |
| 612 | ('ETH/USDT', 'ETH'), |
| 613 | ('XLTCUSDT', 'LTC'), |
| 614 | ('XRP/NOCURRENCY', ''), |
| 615 | ]) |
| 616 | def test_get_pair_base_currency(default_conf, mocker, pair, expected): |
| 617 | ex = get_patched_exchange(mocker, default_conf) |
| 618 | assert ex.get_pair_base_currency(pair) == expected |
| 619 | |
| 620 | |
| 621 | def test_validate_pairs(default_conf, mocker): # test exchange.validate_pairs directly |
| 622 | api_mock = MagicMock() |
| 623 | type(api_mock).load_markets = MagicMock(return_value={ |
| 624 | 'ETH/BTC': {'quote': 'BTC'}, |
| 625 | 'LTC/BTC': {'quote': 'BTC'}, |
| 626 | 'XRP/BTC': {'quote': 'BTC'}, |
| 627 | 'NEO/BTC': {'quote': 'BTC'}, |
| 628 | }) |
| 629 | id_mock = PropertyMock(return_value='test_exchange') |
| 630 | type(api_mock).id = id_mock |
| 631 | |
| 632 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 633 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 634 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 635 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 636 | Exchange(default_conf) |
| 637 | |
| 638 | |
| 639 | def test_validate_pairs_not_available(default_conf, mocker): |
| 640 | api_mock = MagicMock() |
| 641 | type(api_mock).markets = PropertyMock(return_value={ |
| 642 | 'XRP/BTC': {'inactive': True, 'base': 'XRP', 'quote': 'BTC'} |
| 643 | }) |
| 644 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 645 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 646 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 647 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 648 | |
| 649 | with pytest.raises(OperationalException, match=r'not available'): |
| 650 | Exchange(default_conf) |
| 651 | |
| 652 | |
| 653 | def test_validate_pairs_exception(default_conf, mocker, caplog): |
| 654 | caplog.set_level(logging.INFO) |
| 655 | api_mock = MagicMock() |
| 656 | mocker.patch('freqtrade.exchange.Exchange.name', PropertyMock(return_value='Binance')) |
| 657 | |
| 658 | type(api_mock).markets = PropertyMock(return_value={}) |
| 659 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', api_mock) |
| 660 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 661 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 662 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 663 | |
| 664 | with pytest.raises(OperationalException, match=r'Pair ETH/BTC is not available on Binance'): |
| 665 | Exchange(default_conf) |
| 666 | |
| 667 | mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value={})) |
| 668 | Exchange(default_conf) |
| 669 | assert log_has('Unable to validate pairs (assuming they are correct).', caplog) |
| 670 | |
| 671 | |
| 672 | def test_validate_pairs_restricted(default_conf, mocker, caplog): |
| 673 | api_mock = MagicMock() |
| 674 | type(api_mock).load_markets = MagicMock(return_value={ |
| 675 | 'ETH/BTC': {'quote': 'BTC'}, 'LTC/BTC': {'quote': 'BTC'}, |
| 676 | 'XRP/BTC': {'quote': 'BTC', 'info': {'IsRestricted': True}}, |
| 677 | 'NEO/BTC': {'quote': 'BTC', 'info': 'TestString'}, # info can also be a string ... |
| 678 | }) |
| 679 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 680 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 681 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 682 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 683 | |
| 684 | Exchange(default_conf) |
| 685 | assert log_has("Pair XRP/BTC is restricted for some users on this exchange." |
| 686 | "Please check if you are impacted by this restriction " |
| 687 | "on the exchange and eventually remove XRP/BTC from your whitelist.", caplog) |
| 688 | |
| 689 | |
| 690 | def test_validate_pairs_stakecompatibility(default_conf, mocker, caplog): |
| 691 | api_mock = MagicMock() |
| 692 | type(api_mock).load_markets = MagicMock(return_value={ |
| 693 | 'ETH/BTC': {'quote': 'BTC'}, 'LTC/BTC': {'quote': 'BTC'}, |
| 694 | 'XRP/BTC': {'quote': 'BTC'}, 'NEO/BTC': {'quote': 'BTC'}, |
| 695 | 'HELLO-WORLD': {'quote': 'BTC'}, |
| 696 | }) |
| 697 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 698 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 699 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 700 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 701 | |
| 702 | Exchange(default_conf) |
| 703 | |
| 704 | |
| 705 | def test_validate_pairs_stakecompatibility_downloaddata(default_conf, mocker, caplog): |
| 706 | api_mock = MagicMock() |
| 707 | default_conf['stake_currency'] = '' |
| 708 | type(api_mock).load_markets = MagicMock(return_value={ |
| 709 | 'ETH/BTC': {'quote': 'BTC'}, 'LTC/BTC': {'quote': 'BTC'}, |
| 710 | 'XRP/BTC': {'quote': 'BTC'}, 'NEO/BTC': {'quote': 'BTC'}, |
| 711 | 'HELLO-WORLD': {'quote': 'BTC'}, |
| 712 | }) |
| 713 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 714 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 715 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 716 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 717 | |
| 718 | Exchange(default_conf) |
| 719 | assert type(api_mock).load_markets.call_count == 1 |
| 720 | |
| 721 | |
| 722 | def test_validate_pairs_stakecompatibility_fail(default_conf, mocker, caplog): |
| 723 | default_conf['exchange']['pair_whitelist'].append('HELLO-WORLD') |
| 724 | api_mock = MagicMock() |
| 725 | type(api_mock).load_markets = MagicMock(return_value={ |
| 726 | 'ETH/BTC': {'quote': 'BTC'}, 'LTC/BTC': {'quote': 'BTC'}, |
| 727 | 'XRP/BTC': {'quote': 'BTC'}, 'NEO/BTC': {'quote': 'BTC'}, |
| 728 | 'HELLO-WORLD': {'quote': 'USDT'}, |
| 729 | }) |
| 730 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 731 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 732 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 733 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 734 | |
| 735 | with pytest.raises(OperationalException, match=r"Stake-currency 'BTC' not compatible with.*"): |
| 736 | Exchange(default_conf) |
| 737 | |
| 738 | |
| 739 | @pytest.mark.parametrize("timeframe", [ |
| 740 | ('5m'), ("1m"), ("15m"), ("1h") |
| 741 | ]) |
| 742 | def test_validate_timeframes(default_conf, mocker, timeframe): |
| 743 | default_conf["timeframe"] = timeframe |
| 744 | api_mock = MagicMock() |
| 745 | id_mock = PropertyMock(return_value='test_exchange') |
| 746 | type(api_mock).id = id_mock |
| 747 | timeframes = PropertyMock(return_value={'1m': '1m', |
| 748 | '5m': '5m', |
| 749 | '15m': '15m', |
| 750 | '1h': '1h'}) |
| 751 | type(api_mock).timeframes = timeframes |
| 752 | |
| 753 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 754 | mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={})) |
| 755 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 756 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 757 | Exchange(default_conf) |
| 758 | |
| 759 | |
| 760 | def test_validate_timeframes_failed(default_conf, mocker): |
| 761 | default_conf["timeframe"] = "3m" |
| 762 | api_mock = MagicMock() |
| 763 | id_mock = PropertyMock(return_value='test_exchange') |
| 764 | type(api_mock).id = id_mock |
| 765 | timeframes = PropertyMock(return_value={'15s': '15s', |
| 766 | '1m': '1m', |
| 767 | '5m': '5m', |
| 768 | '15m': '15m', |
| 769 | '1h': '1h'}) |
| 770 | type(api_mock).timeframes = timeframes |
| 771 | |
| 772 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 773 | mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={})) |
| 774 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs', MagicMock()) |
| 775 | with pytest.raises(OperationalException, |
| 776 | match=r"Invalid timeframe '3m'. This exchange supports.*"): |
| 777 | Exchange(default_conf) |
| 778 | default_conf["timeframe"] = "15s" |
| 779 | |
| 780 | with pytest.raises(OperationalException, |
| 781 | match=r"Timeframes < 1m are currently not supported by Freqtrade."): |
| 782 | Exchange(default_conf) |
| 783 | |
| 784 | |
| 785 | def test_validate_timeframes_emulated_ohlcv_1(default_conf, mocker): |
| 786 | default_conf["timeframe"] = "3m" |
| 787 | api_mock = MagicMock() |
| 788 | id_mock = PropertyMock(return_value='test_exchange') |
| 789 | type(api_mock).id = id_mock |
| 790 | |
| 791 | # delete timeframes so magicmock does not autocreate it |
| 792 | del api_mock.timeframes |
| 793 | |
| 794 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 795 | mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={})) |
| 796 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 797 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 798 | with pytest.raises(OperationalException, |
| 799 | match=r'The ccxt library does not provide the list of timeframes ' |
| 800 | r'for the exchange ".*" and this exchange ' |
| 801 | r'is therefore not supported. *'): |
| 802 | Exchange(default_conf) |
| 803 | |
| 804 | |
| 805 | def test_validate_timeframes_emulated_ohlcvi_2(default_conf, mocker): |
| 806 | default_conf["timeframe"] = "3m" |
| 807 | api_mock = MagicMock() |
| 808 | id_mock = PropertyMock(return_value='test_exchange') |
| 809 | type(api_mock).id = id_mock |
| 810 | |
| 811 | # delete timeframes so magicmock does not autocreate it |
| 812 | del api_mock.timeframes |
| 813 | |
| 814 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 815 | mocker.patch('freqtrade.exchange.Exchange._load_markets', |
| 816 | MagicMock(return_value={'timeframes': None})) |
| 817 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs', MagicMock()) |
| 818 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 819 | with pytest.raises(OperationalException, |
| 820 | match=r'The ccxt library does not provide the list of timeframes ' |
| 821 | r'for the exchange ".*" and this exchange ' |
| 822 | r'is therefore not supported. *'): |
| 823 | Exchange(default_conf) |
| 824 | |
| 825 | |
| 826 | def test_validate_timeframes_not_in_config(default_conf, mocker): |
| 827 | del default_conf["timeframe"] |
| 828 | api_mock = MagicMock() |
| 829 | id_mock = PropertyMock(return_value='test_exchange') |
| 830 | type(api_mock).id = id_mock |
| 831 | timeframes = PropertyMock(return_value={'1m': '1m', |
| 832 | '5m': '5m', |
| 833 | '15m': '15m', |
| 834 | '1h': '1h'}) |
| 835 | type(api_mock).timeframes = timeframes |
| 836 | |
| 837 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 838 | mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={})) |
| 839 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 840 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 841 | Exchange(default_conf) |
| 842 | |
| 843 | |
| 844 | def test_validate_order_types(default_conf, mocker): |
| 845 | api_mock = MagicMock() |
| 846 | |
| 847 | type(api_mock).has = PropertyMock(return_value={'createMarketOrder': True}) |
| 848 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 849 | mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={})) |
| 850 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 851 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 852 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 853 | mocker.patch('freqtrade.exchange.Exchange.name', 'Bittrex') |
| 854 | |
| 855 | default_conf['order_types'] = { |
| 856 | 'buy': 'limit', |
| 857 | 'sell': 'limit', |
| 858 | 'stoploss': 'market', |
| 859 | 'stoploss_on_exchange': False |
| 860 | } |
| 861 | Exchange(default_conf) |
| 862 | |
| 863 | type(api_mock).has = PropertyMock(return_value={'createMarketOrder': False}) |
| 864 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 865 | |
| 866 | default_conf['order_types'] = { |
| 867 | 'buy': 'limit', |
| 868 | 'sell': 'limit', |
| 869 | 'stoploss': 'market', |
| 870 | 'stoploss_on_exchange': False |
| 871 | } |
| 872 | with pytest.raises(OperationalException, |
| 873 | match=r'Exchange .* does not support market orders.'): |
| 874 | Exchange(default_conf) |
| 875 | |
| 876 | default_conf['order_types'] = { |
| 877 | 'buy': 'limit', |
| 878 | 'sell': 'limit', |
| 879 | 'stoploss': 'limit', |
| 880 | 'stoploss_on_exchange': True |
| 881 | } |
| 882 | with pytest.raises(OperationalException, |
| 883 | match=r'On exchange stoploss is not supported for .*'): |
| 884 | Exchange(default_conf) |
| 885 | |
| 886 | |
| 887 | def test_validate_order_types_not_in_config(default_conf, mocker): |
| 888 | api_mock = MagicMock() |
| 889 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', MagicMock(return_value=api_mock)) |
| 890 | mocker.patch('freqtrade.exchange.Exchange._load_markets', MagicMock(return_value={})) |
| 891 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 892 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 893 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 894 | |
| 895 | conf = copy.deepcopy(default_conf) |
| 896 | Exchange(conf) |
| 897 | |
| 898 | |
| 899 | def test_validate_required_startup_candles(default_conf, mocker, caplog): |
| 900 | api_mock = MagicMock() |
| 901 | mocker.patch('freqtrade.exchange.Exchange.name', PropertyMock(return_value='Binance')) |
| 902 | |
| 903 | mocker.patch('freqtrade.exchange.Exchange._init_ccxt', api_mock) |
| 904 | mocker.patch('freqtrade.exchange.Exchange.validate_timeframes') |
| 905 | mocker.patch('freqtrade.exchange.Exchange._load_async_markets') |
| 906 | mocker.patch('freqtrade.exchange.Exchange.validate_pairs') |
| 907 | mocker.patch('freqtrade.exchange.Exchange.validate_stakecurrency') |
| 908 | |
| 909 | default_conf['startup_candle_count'] = 20 |
| 910 | ex = Exchange(default_conf) |
| 911 | assert ex |
| 912 | default_conf['startup_candle_count'] = 600 |
| 913 | |
| 914 | with pytest.raises(OperationalException, match=r'This strategy requires 600.*'): |
| 915 | Exchange(default_conf) |
| 916 | |
| 917 | |
| 918 | def test_exchange_has(default_conf, mocker): |
| 919 | exchange = get_patched_exchange(mocker, default_conf) |
| 920 | assert not exchange.exchange_has('ASDFASDF') |
| 921 | api_mock = MagicMock() |
| 922 | |
| 923 | type(api_mock).has = PropertyMock(return_value={'deadbeef': True}) |
| 924 | exchange = get_patched_exchange(mocker, default_conf, api_mock) |
| 925 | assert exchange.exchange_has("deadbeef") |
| 926 | |
| 927 | type(api_mock).has = PropertyMock(return_value={'deadbeef': False}) |
| 928 | exchange = get_patched_exchange(mocker, default_conf, api_mock) |
| 929 | assert not exchange.exchange_has("deadbeef") |
| 930 | |
| 931 | |
| 932 | @pytest.mark.parametrize("side", [ |
| 933 | ("buy"), |
| 934 | ("sell") |
| 935 | ]) |
| 936 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 937 | def test_create_dry_run_order(default_conf, mocker, side, exchange_name): |
| 938 | default_conf['dry_run'] = True |
| 939 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 940 | |
| 941 | order = exchange.create_dry_run_order( |
| 942 | pair='ETH/BTC', ordertype='limit', side=side, amount=1, rate=200) |
| 943 | assert 'id' in order |
| 944 | assert f'dry_run_{side}_' in order["id"] |
| 945 | assert order["side"] == side |
| 946 | assert order["type"] == "limit" |
| 947 | assert order["symbol"] == "ETH/BTC" |
| 948 | |
| 949 | |
| 950 | @pytest.mark.parametrize("side", [ |
| 951 | ("buy"), |
| 952 | ("sell") |
| 953 | ]) |
| 954 | @pytest.mark.parametrize("ordertype,rate,marketprice", [ |
| 955 | ("market", None, None), |
| 956 | ("market", 200, True), |
| 957 | ("limit", 200, None), |
| 958 | ("stop_loss_limit", 200, None) |
| 959 | ]) |
| 960 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 961 | def test_create_order(default_conf, mocker, side, ordertype, rate, marketprice, exchange_name): |
| 962 | api_mock = MagicMock() |
| 963 | order_id = 'test_prod_{}_{}'.format(side, randint(0, 10 ** 6)) |
| 964 | api_mock.options = {} if not marketprice else {"createMarketBuyOrderRequiresPrice": True} |
| 965 | api_mock.create_order = MagicMock(return_value={ |
| 966 | 'id': order_id, |
| 967 | 'info': { |
| 968 | 'foo': 'bar' |
| 969 | } |
| 970 | }) |
| 971 | default_conf['dry_run'] = False |
| 972 | mocker.patch('freqtrade.exchange.Exchange.amount_to_precision', lambda s, x, y: y) |
| 973 | mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y) |
| 974 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 975 | |
| 976 | order = exchange.create_order( |
| 977 | pair='ETH/BTC', ordertype=ordertype, side=side, amount=1, rate=200) |
| 978 | |
| 979 | assert 'id' in order |
| 980 | assert 'info' in order |
| 981 | assert order['id'] == order_id |
| 982 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 983 | assert api_mock.create_order.call_args[0][1] == ordertype |
| 984 | assert api_mock.create_order.call_args[0][2] == side |
| 985 | assert api_mock.create_order.call_args[0][3] == 1 |
| 986 | assert api_mock.create_order.call_args[0][4] is rate |
| 987 | |
| 988 | |
| 989 | def test_buy_dry_run(default_conf, mocker): |
| 990 | default_conf['dry_run'] = True |
| 991 | exchange = get_patched_exchange(mocker, default_conf) |
| 992 | |
| 993 | order = exchange.buy(pair='ETH/BTC', ordertype='limit', |
| 994 | amount=1, rate=200, time_in_force='gtc') |
| 995 | assert 'id' in order |
| 996 | assert 'dry_run_buy_' in order['id'] |
| 997 | |
| 998 | |
| 999 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1000 | def test_buy_prod(default_conf, mocker, exchange_name): |
| 1001 | api_mock = MagicMock() |
| 1002 | order_id = 'test_prod_buy_{}'.format(randint(0, 10 ** 6)) |
| 1003 | order_type = 'market' |
| 1004 | time_in_force = 'gtc' |
| 1005 | api_mock.options = {} |
| 1006 | api_mock.create_order = MagicMock(return_value={ |
| 1007 | 'id': order_id, |
| 1008 | 'info': { |
| 1009 | 'foo': 'bar' |
| 1010 | } |
| 1011 | }) |
| 1012 | default_conf['dry_run'] = False |
| 1013 | mocker.patch('freqtrade.exchange.Exchange.amount_to_precision', lambda s, x, y: y) |
| 1014 | mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y) |
| 1015 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1016 | |
| 1017 | order = exchange.buy(pair='ETH/BTC', ordertype=order_type, |
| 1018 | amount=1, rate=200, time_in_force=time_in_force) |
| 1019 | |
| 1020 | assert 'id' in order |
| 1021 | assert 'info' in order |
| 1022 | assert order['id'] == order_id |
| 1023 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 1024 | assert api_mock.create_order.call_args[0][1] == order_type |
| 1025 | assert api_mock.create_order.call_args[0][2] == 'buy' |
| 1026 | assert api_mock.create_order.call_args[0][3] == 1 |
| 1027 | assert api_mock.create_order.call_args[0][4] is None |
| 1028 | |
| 1029 | api_mock.create_order.reset_mock() |
| 1030 | order_type = 'limit' |
| 1031 | order = exchange.buy( |
| 1032 | pair='ETH/BTC', |
| 1033 | ordertype=order_type, |
| 1034 | amount=1, |
| 1035 | rate=200, |
| 1036 | time_in_force=time_in_force) |
| 1037 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 1038 | assert api_mock.create_order.call_args[0][1] == order_type |
| 1039 | assert api_mock.create_order.call_args[0][2] == 'buy' |
| 1040 | assert api_mock.create_order.call_args[0][3] == 1 |
| 1041 | assert api_mock.create_order.call_args[0][4] == 200 |
| 1042 | |
| 1043 | # test exception handling |
| 1044 | with pytest.raises(DependencyException): |
| 1045 | api_mock.create_order = MagicMock(side_effect=ccxt.InsufficientFunds("Not enough funds")) |
| 1046 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1047 | exchange.buy(pair='ETH/BTC', ordertype=order_type, |
| 1048 | amount=1, rate=200, time_in_force=time_in_force) |
| 1049 | |
| 1050 | with pytest.raises(DependencyException): |
| 1051 | api_mock.create_order = MagicMock(side_effect=ccxt.InvalidOrder("Order not found")) |
| 1052 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1053 | exchange.buy(pair='ETH/BTC', ordertype='limit', |
| 1054 | amount=1, rate=200, time_in_force=time_in_force) |
| 1055 | |
| 1056 | with pytest.raises(DependencyException): |
| 1057 | api_mock.create_order = MagicMock(side_effect=ccxt.InvalidOrder("Order not found")) |
| 1058 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1059 | exchange.buy(pair='ETH/BTC', ordertype='market', |
| 1060 | amount=1, rate=200, time_in_force=time_in_force) |
| 1061 | |
| 1062 | with pytest.raises(TemporaryError): |
| 1063 | api_mock.create_order = MagicMock(side_effect=ccxt.NetworkError("Network disconnect")) |
| 1064 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1065 | exchange.buy(pair='ETH/BTC', ordertype=order_type, |
| 1066 | amount=1, rate=200, time_in_force=time_in_force) |
| 1067 | |
| 1068 | with pytest.raises(OperationalException): |
| 1069 | api_mock.create_order = MagicMock(side_effect=ccxt.BaseError("Unknown error")) |
| 1070 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1071 | exchange.buy(pair='ETH/BTC', ordertype=order_type, |
| 1072 | amount=1, rate=200, time_in_force=time_in_force) |
| 1073 | |
| 1074 | |
| 1075 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1076 | def test_buy_considers_time_in_force(default_conf, mocker, exchange_name): |
| 1077 | api_mock = MagicMock() |
| 1078 | order_id = 'test_prod_buy_{}'.format(randint(0, 10 ** 6)) |
| 1079 | api_mock.options = {} |
| 1080 | api_mock.create_order = MagicMock(return_value={ |
| 1081 | 'id': order_id, |
| 1082 | 'info': { |
| 1083 | 'foo': 'bar' |
| 1084 | } |
| 1085 | }) |
| 1086 | default_conf['dry_run'] = False |
| 1087 | mocker.patch('freqtrade.exchange.Exchange.amount_to_precision', lambda s, x, y: y) |
| 1088 | mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y) |
| 1089 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1090 | |
| 1091 | order_type = 'limit' |
| 1092 | time_in_force = 'ioc' |
| 1093 | |
| 1094 | order = exchange.buy(pair='ETH/BTC', ordertype=order_type, |
| 1095 | amount=1, rate=200, time_in_force=time_in_force) |
| 1096 | |
| 1097 | assert 'id' in order |
| 1098 | assert 'info' in order |
| 1099 | assert order['id'] == order_id |
| 1100 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 1101 | assert api_mock.create_order.call_args[0][1] == order_type |
| 1102 | assert api_mock.create_order.call_args[0][2] == 'buy' |
| 1103 | assert api_mock.create_order.call_args[0][3] == 1 |
| 1104 | assert api_mock.create_order.call_args[0][4] == 200 |
| 1105 | assert "timeInForce" in api_mock.create_order.call_args[0][5] |
| 1106 | assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force |
| 1107 | |
| 1108 | order_type = 'market' |
| 1109 | time_in_force = 'ioc' |
| 1110 | |
| 1111 | order = exchange.buy(pair='ETH/BTC', ordertype=order_type, |
| 1112 | amount=1, rate=200, time_in_force=time_in_force) |
| 1113 | |
| 1114 | assert 'id' in order |
| 1115 | assert 'info' in order |
| 1116 | assert order['id'] == order_id |
| 1117 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 1118 | assert api_mock.create_order.call_args[0][1] == order_type |
| 1119 | assert api_mock.create_order.call_args[0][2] == 'buy' |
| 1120 | assert api_mock.create_order.call_args[0][3] == 1 |
| 1121 | assert api_mock.create_order.call_args[0][4] is None |
| 1122 | # Market orders should not send timeInForce!! |
| 1123 | assert "timeInForce" not in api_mock.create_order.call_args[0][5] |
| 1124 | |
| 1125 | |
| 1126 | def test_sell_dry_run(default_conf, mocker): |
| 1127 | default_conf['dry_run'] = True |
| 1128 | exchange = get_patched_exchange(mocker, default_conf) |
| 1129 | |
| 1130 | order = exchange.sell(pair='ETH/BTC', ordertype='limit', amount=1, rate=200) |
| 1131 | assert 'id' in order |
| 1132 | assert 'dry_run_sell_' in order['id'] |
| 1133 | |
| 1134 | |
| 1135 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1136 | def test_sell_prod(default_conf, mocker, exchange_name): |
| 1137 | api_mock = MagicMock() |
| 1138 | order_id = 'test_prod_sell_{}'.format(randint(0, 10 ** 6)) |
| 1139 | order_type = 'market' |
| 1140 | api_mock.options = {} |
| 1141 | api_mock.create_order = MagicMock(return_value={ |
| 1142 | 'id': order_id, |
| 1143 | 'info': { |
| 1144 | 'foo': 'bar' |
| 1145 | } |
| 1146 | }) |
| 1147 | default_conf['dry_run'] = False |
| 1148 | |
| 1149 | mocker.patch('freqtrade.exchange.Exchange.amount_to_precision', lambda s, x, y: y) |
| 1150 | mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y) |
| 1151 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1152 | |
| 1153 | order = exchange.sell(pair='ETH/BTC', ordertype=order_type, amount=1, rate=200) |
| 1154 | |
| 1155 | assert 'id' in order |
| 1156 | assert 'info' in order |
| 1157 | assert order['id'] == order_id |
| 1158 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 1159 | assert api_mock.create_order.call_args[0][1] == order_type |
| 1160 | assert api_mock.create_order.call_args[0][2] == 'sell' |
| 1161 | assert api_mock.create_order.call_args[0][3] == 1 |
| 1162 | assert api_mock.create_order.call_args[0][4] is None |
| 1163 | |
| 1164 | api_mock.create_order.reset_mock() |
| 1165 | order_type = 'limit' |
| 1166 | order = exchange.sell(pair='ETH/BTC', ordertype=order_type, amount=1, rate=200) |
| 1167 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 1168 | assert api_mock.create_order.call_args[0][1] == order_type |
| 1169 | assert api_mock.create_order.call_args[0][2] == 'sell' |
| 1170 | assert api_mock.create_order.call_args[0][3] == 1 |
| 1171 | assert api_mock.create_order.call_args[0][4] == 200 |
| 1172 | |
| 1173 | # test exception handling |
| 1174 | with pytest.raises(DependencyException): |
| 1175 | api_mock.create_order = MagicMock(side_effect=ccxt.InsufficientFunds("0 balance")) |
| 1176 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1177 | exchange.sell(pair='ETH/BTC', ordertype=order_type, amount=1, rate=200) |
| 1178 | |
| 1179 | with pytest.raises(DependencyException): |
| 1180 | api_mock.create_order = MagicMock(side_effect=ccxt.InvalidOrder("Order not found")) |
| 1181 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1182 | exchange.sell(pair='ETH/BTC', ordertype='limit', amount=1, rate=200) |
| 1183 | |
| 1184 | # Market orders don't require price, so the behaviour is slightly different |
| 1185 | with pytest.raises(DependencyException): |
| 1186 | api_mock.create_order = MagicMock(side_effect=ccxt.InvalidOrder("Order not found")) |
| 1187 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1188 | exchange.sell(pair='ETH/BTC', ordertype='market', amount=1, rate=200) |
| 1189 | |
| 1190 | with pytest.raises(TemporaryError): |
| 1191 | api_mock.create_order = MagicMock(side_effect=ccxt.NetworkError("No Connection")) |
| 1192 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1193 | exchange.sell(pair='ETH/BTC', ordertype=order_type, amount=1, rate=200) |
| 1194 | |
| 1195 | with pytest.raises(OperationalException): |
| 1196 | api_mock.create_order = MagicMock(side_effect=ccxt.BaseError("DeadBeef")) |
| 1197 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1198 | exchange.sell(pair='ETH/BTC', ordertype=order_type, amount=1, rate=200) |
| 1199 | |
| 1200 | |
| 1201 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1202 | def test_sell_considers_time_in_force(default_conf, mocker, exchange_name): |
| 1203 | api_mock = MagicMock() |
| 1204 | order_id = 'test_prod_sell_{}'.format(randint(0, 10 ** 6)) |
| 1205 | api_mock.create_order = MagicMock(return_value={ |
| 1206 | 'id': order_id, |
| 1207 | 'info': { |
| 1208 | 'foo': 'bar' |
| 1209 | } |
| 1210 | }) |
| 1211 | api_mock.options = {} |
| 1212 | default_conf['dry_run'] = False |
| 1213 | mocker.patch('freqtrade.exchange.Exchange.amount_to_precision', lambda s, x, y: y) |
| 1214 | mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y) |
| 1215 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1216 | |
| 1217 | order_type = 'limit' |
| 1218 | time_in_force = 'ioc' |
| 1219 | |
| 1220 | order = exchange.sell(pair='ETH/BTC', ordertype=order_type, |
| 1221 | amount=1, rate=200, time_in_force=time_in_force) |
| 1222 | |
| 1223 | assert 'id' in order |
| 1224 | assert 'info' in order |
| 1225 | assert order['id'] == order_id |
| 1226 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 1227 | assert api_mock.create_order.call_args[0][1] == order_type |
| 1228 | assert api_mock.create_order.call_args[0][2] == 'sell' |
| 1229 | assert api_mock.create_order.call_args[0][3] == 1 |
| 1230 | assert api_mock.create_order.call_args[0][4] == 200 |
| 1231 | assert "timeInForce" in api_mock.create_order.call_args[0][5] |
| 1232 | assert api_mock.create_order.call_args[0][5]["timeInForce"] == time_in_force |
| 1233 | |
| 1234 | order_type = 'market' |
| 1235 | time_in_force = 'ioc' |
| 1236 | order = exchange.sell(pair='ETH/BTC', ordertype=order_type, |
| 1237 | amount=1, rate=200, time_in_force=time_in_force) |
| 1238 | |
| 1239 | assert 'id' in order |
| 1240 | assert 'info' in order |
| 1241 | assert order['id'] == order_id |
| 1242 | assert api_mock.create_order.call_args[0][0] == 'ETH/BTC' |
| 1243 | assert api_mock.create_order.call_args[0][1] == order_type |
| 1244 | assert api_mock.create_order.call_args[0][2] == 'sell' |
| 1245 | assert api_mock.create_order.call_args[0][3] == 1 |
| 1246 | assert api_mock.create_order.call_args[0][4] is None |
| 1247 | # Market orders should not send timeInForce!! |
| 1248 | assert "timeInForce" not in api_mock.create_order.call_args[0][5] |
| 1249 | |
| 1250 | |
| 1251 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1252 | def test_get_balance_prod(default_conf, mocker, exchange_name): |
| 1253 | api_mock = MagicMock() |
| 1254 | api_mock.fetch_balance = MagicMock(return_value={'BTC': {'free': 123.4, 'total': 123.4}}) |
| 1255 | default_conf['dry_run'] = False |
| 1256 | |
| 1257 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1258 | |
| 1259 | assert exchange.get_balance(currency='BTC') == 123.4 |
| 1260 | |
| 1261 | with pytest.raises(OperationalException): |
| 1262 | api_mock.fetch_balance = MagicMock(side_effect=ccxt.BaseError("Unknown error")) |
| 1263 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1264 | |
| 1265 | exchange.get_balance(currency='BTC') |
| 1266 | |
| 1267 | with pytest.raises(TemporaryError, match=r'.*balance due to malformed exchange response:.*'): |
| 1268 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1269 | mocker.patch('freqtrade.exchange.Exchange.get_balances', MagicMock(return_value={})) |
| 1270 | mocker.patch('freqtrade.exchange.Kraken.get_balances', MagicMock(return_value={})) |
| 1271 | exchange.get_balance(currency='BTC') |
| 1272 | |
| 1273 | |
| 1274 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1275 | def test_get_balances_prod(default_conf, mocker, exchange_name): |
| 1276 | balance_item = { |
| 1277 | 'free': 10.0, |
| 1278 | 'total': 10.0, |
| 1279 | 'used': 0.0 |
| 1280 | } |
| 1281 | |
| 1282 | api_mock = MagicMock() |
| 1283 | api_mock.fetch_balance = MagicMock(return_value={ |
| 1284 | '1ST': balance_item, |
| 1285 | '2ST': balance_item, |
| 1286 | '3ST': balance_item |
| 1287 | }) |
| 1288 | default_conf['dry_run'] = False |
| 1289 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1290 | assert len(exchange.get_balances()) == 3 |
| 1291 | assert exchange.get_balances()['1ST']['free'] == 10.0 |
| 1292 | assert exchange.get_balances()['1ST']['total'] == 10.0 |
| 1293 | assert exchange.get_balances()['1ST']['used'] == 0.0 |
| 1294 | |
| 1295 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 1296 | "get_balances", "fetch_balance") |
| 1297 | |
| 1298 | |
| 1299 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1300 | def test_get_tickers(default_conf, mocker, exchange_name): |
| 1301 | api_mock = MagicMock() |
| 1302 | tick = {'ETH/BTC': { |
| 1303 | 'symbol': 'ETH/BTC', |
| 1304 | 'bid': 0.5, |
| 1305 | 'ask': 1, |
| 1306 | 'last': 42, |
| 1307 | }, 'BCH/BTC': { |
| 1308 | 'symbol': 'BCH/BTC', |
| 1309 | 'bid': 0.6, |
| 1310 | 'ask': 0.5, |
| 1311 | 'last': 41, |
| 1312 | } |
| 1313 | } |
| 1314 | api_mock.fetch_tickers = MagicMock(return_value=tick) |
| 1315 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1316 | # retrieve original ticker |
| 1317 | tickers = exchange.get_tickers() |
| 1318 | |
| 1319 | assert 'ETH/BTC' in tickers |
| 1320 | assert 'BCH/BTC' in tickers |
| 1321 | assert tickers['ETH/BTC']['bid'] == 0.5 |
| 1322 | assert tickers['ETH/BTC']['ask'] == 1 |
| 1323 | assert tickers['BCH/BTC']['bid'] == 0.6 |
| 1324 | assert tickers['BCH/BTC']['ask'] == 0.5 |
| 1325 | assert api_mock.fetch_tickers.call_count == 1 |
| 1326 | |
| 1327 | api_mock.fetch_tickers.reset_mock() |
| 1328 | |
| 1329 | # Cached ticker should not call api again |
| 1330 | tickers2 = exchange.get_tickers(cached=True) |
| 1331 | assert tickers2 == tickers |
| 1332 | assert api_mock.fetch_tickers.call_count == 0 |
| 1333 | tickers2 = exchange.get_tickers(cached=False) |
| 1334 | assert api_mock.fetch_tickers.call_count == 1 |
| 1335 | |
| 1336 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 1337 | "get_tickers", "fetch_tickers") |
| 1338 | |
| 1339 | with pytest.raises(OperationalException): |
| 1340 | api_mock.fetch_tickers = MagicMock(side_effect=ccxt.NotSupported("DeadBeef")) |
| 1341 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1342 | exchange.get_tickers() |
| 1343 | |
| 1344 | api_mock.fetch_tickers = MagicMock(return_value={}) |
| 1345 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1346 | exchange.get_tickers() |
| 1347 | |
| 1348 | |
| 1349 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1350 | def test_fetch_ticker(default_conf, mocker, exchange_name): |
| 1351 | api_mock = MagicMock() |
| 1352 | tick = { |
| 1353 | 'symbol': 'ETH/BTC', |
| 1354 | 'bid': 0.00001098, |
| 1355 | 'ask': 0.00001099, |
| 1356 | 'last': 0.0001, |
| 1357 | } |
| 1358 | api_mock.fetch_ticker = MagicMock(return_value=tick) |
| 1359 | api_mock.markets = {'ETH/BTC': {'active': True}} |
| 1360 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1361 | # retrieve original ticker |
| 1362 | ticker = exchange.fetch_ticker(pair='ETH/BTC') |
| 1363 | |
| 1364 | assert ticker['bid'] == 0.00001098 |
| 1365 | assert ticker['ask'] == 0.00001099 |
| 1366 | |
| 1367 | # change the ticker |
| 1368 | tick = { |
| 1369 | 'symbol': 'ETH/BTC', |
| 1370 | 'bid': 0.5, |
| 1371 | 'ask': 1, |
| 1372 | 'last': 42, |
| 1373 | } |
| 1374 | api_mock.fetch_ticker = MagicMock(return_value=tick) |
| 1375 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1376 | |
| 1377 | # if not caching the result we should get the same ticker |
| 1378 | # if not fetching a new result we should get the cached ticker |
| 1379 | ticker = exchange.fetch_ticker(pair='ETH/BTC') |
| 1380 | |
| 1381 | assert api_mock.fetch_ticker.call_count == 1 |
| 1382 | assert ticker['bid'] == 0.5 |
| 1383 | assert ticker['ask'] == 1 |
| 1384 | |
| 1385 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 1386 | "fetch_ticker", "fetch_ticker", |
| 1387 | pair='ETH/BTC') |
| 1388 | |
| 1389 | api_mock.fetch_ticker = MagicMock(return_value={}) |
| 1390 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1391 | exchange.fetch_ticker(pair='ETH/BTC') |
| 1392 | |
| 1393 | with pytest.raises(DependencyException, match=r'Pair XRP/ETH not available'): |
| 1394 | exchange.fetch_ticker(pair='XRP/ETH') |
| 1395 | |
| 1396 | |
| 1397 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1398 | def test_get_historic_ohlcv(default_conf, mocker, caplog, exchange_name): |
| 1399 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1400 | ohlcv = [ |
| 1401 | [ |
| 1402 | arrow.utcnow().int_timestamp * 1000, # unix timestamp ms |
| 1403 | 1, # open |
| 1404 | 2, # high |
| 1405 | 3, # low |
| 1406 | 4, # close |
| 1407 | 5, # volume (in quote currency) |
| 1408 | ] |
| 1409 | ] |
| 1410 | pair = 'ETH/BTC' |
| 1411 | |
| 1412 | async def mock_candle_hist(pair, timeframe, since_ms): |
| 1413 | return pair, timeframe, ohlcv |
| 1414 | |
| 1415 | exchange._async_get_candle_history = Mock(wraps=mock_candle_hist) |
| 1416 | # one_call calculation * 1.8 should do 2 calls |
| 1417 | |
| 1418 | since = 5 * 60 * exchange.ohlcv_candle_limit('5m') * 1.8 |
| 1419 | ret = exchange.get_historic_ohlcv(pair, "5m", int(( |
| 1420 | arrow.utcnow().int_timestamp - since) * 1000)) |
| 1421 | |
| 1422 | assert exchange._async_get_candle_history.call_count == 2 |
| 1423 | # Returns twice the above OHLCV data |
| 1424 | assert len(ret) == 2 |
| 1425 | |
| 1426 | caplog.clear() |
| 1427 | |
| 1428 | async def mock_get_candle_hist_error(pair, *args, **kwargs): |
| 1429 | raise TimeoutError() |
| 1430 | |
| 1431 | exchange._async_get_candle_history = MagicMock(side_effect=mock_get_candle_hist_error) |
| 1432 | ret = exchange.get_historic_ohlcv(pair, "5m", int( |
| 1433 | (arrow.utcnow().int_timestamp - since) * 1000)) |
| 1434 | assert log_has_re(r"Async code raised an exception: .*", caplog) |
| 1435 | |
| 1436 | |
| 1437 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1438 | def test_get_historic_ohlcv_as_df(default_conf, mocker, exchange_name): |
| 1439 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1440 | ohlcv = [ |
| 1441 | [ |
| 1442 | arrow.utcnow().int_timestamp * 1000, # unix timestamp ms |
| 1443 | 1, # open |
| 1444 | 2, # high |
| 1445 | 3, # low |
| 1446 | 4, # close |
| 1447 | 5, # volume (in quote currency) |
| 1448 | ], |
| 1449 | [ |
| 1450 | arrow.utcnow().shift(minutes=5).int_timestamp * 1000, # unix timestamp ms |
| 1451 | 1, # open |
| 1452 | 2, # high |
| 1453 | 3, # low |
| 1454 | 4, # close |
| 1455 | 5, # volume (in quote currency) |
| 1456 | ], |
| 1457 | [ |
| 1458 | arrow.utcnow().shift(minutes=10).int_timestamp * 1000, # unix timestamp ms |
| 1459 | 1, # open |
| 1460 | 2, # high |
| 1461 | 3, # low |
| 1462 | 4, # close |
| 1463 | 5, # volume (in quote currency) |
| 1464 | ] |
| 1465 | ] |
| 1466 | pair = 'ETH/BTC' |
| 1467 | |
| 1468 | async def mock_candle_hist(pair, timeframe, since_ms): |
| 1469 | return pair, timeframe, ohlcv |
| 1470 | |
| 1471 | exchange._async_get_candle_history = Mock(wraps=mock_candle_hist) |
| 1472 | # one_call calculation * 1.8 should do 2 calls |
| 1473 | |
| 1474 | since = 5 * 60 * exchange.ohlcv_candle_limit('5m') * 1.8 |
| 1475 | ret = exchange.get_historic_ohlcv_as_df(pair, "5m", int(( |
| 1476 | arrow.utcnow().int_timestamp - since) * 1000)) |
| 1477 | |
| 1478 | assert exchange._async_get_candle_history.call_count == 2 |
| 1479 | # Returns twice the above OHLCV data |
| 1480 | assert len(ret) == 2 |
| 1481 | assert isinstance(ret, DataFrame) |
| 1482 | assert 'date' in ret.columns |
| 1483 | assert 'open' in ret.columns |
| 1484 | assert 'close' in ret.columns |
| 1485 | assert 'high' in ret.columns |
| 1486 | |
| 1487 | |
| 1488 | def test_refresh_latest_ohlcv(mocker, default_conf, caplog) -> None: |
| 1489 | ohlcv = [ |
| 1490 | [ |
| 1491 | (arrow.utcnow().int_timestamp - 1) * 1000, # unix timestamp ms |
| 1492 | 1, # open |
| 1493 | 2, # high |
| 1494 | 3, # low |
| 1495 | 4, # close |
| 1496 | 5, # volume (in quote currency) |
| 1497 | ], |
| 1498 | [ |
| 1499 | arrow.utcnow().int_timestamp * 1000, # unix timestamp ms |
| 1500 | 3, # open |
| 1501 | 1, # high |
| 1502 | 4, # low |
| 1503 | 6, # close |
| 1504 | 5, # volume (in quote currency) |
| 1505 | ] |
| 1506 | ] |
| 1507 | |
| 1508 | caplog.set_level(logging.DEBUG) |
| 1509 | exchange = get_patched_exchange(mocker, default_conf) |
| 1510 | exchange._api_async.fetch_ohlcv = get_mock_coro(ohlcv) |
| 1511 | |
| 1512 | pairs = [('IOTA/ETH', '5m'), ('XRP/ETH', '5m')] |
| 1513 | # empty dicts |
| 1514 | assert not exchange._klines |
| 1515 | exchange.refresh_latest_ohlcv(pairs, cache=False) |
| 1516 | # No caching |
| 1517 | assert not exchange._klines |
| 1518 | assert exchange._api_async.fetch_ohlcv.call_count == 2 |
| 1519 | exchange._api_async.fetch_ohlcv.reset_mock() |
| 1520 | |
| 1521 | exchange.refresh_latest_ohlcv(pairs) |
| 1522 | |
| 1523 | assert log_has(f'Refreshing candle (OHLCV) data for {len(pairs)} pairs', caplog) |
| 1524 | assert exchange._klines |
| 1525 | assert exchange._api_async.fetch_ohlcv.call_count == 2 |
| 1526 | for pair in pairs: |
| 1527 | assert isinstance(exchange.klines(pair), DataFrame) |
| 1528 | assert len(exchange.klines(pair)) > 0 |
| 1529 | |
| 1530 | # klines function should return a different object on each call |
| 1531 | # if copy is "True" |
| 1532 | assert exchange.klines(pair) is not exchange.klines(pair) |
| 1533 | assert exchange.klines(pair) is not exchange.klines(pair, copy=True) |
| 1534 | assert exchange.klines(pair, copy=True) is not exchange.klines(pair, copy=True) |
| 1535 | assert exchange.klines(pair, copy=False) is exchange.klines(pair, copy=False) |
| 1536 | |
| 1537 | # test caching |
| 1538 | exchange.refresh_latest_ohlcv([('IOTA/ETH', '5m'), ('XRP/ETH', '5m')]) |
| 1539 | |
| 1540 | assert exchange._api_async.fetch_ohlcv.call_count == 2 |
| 1541 | assert log_has(f"Using cached candle (OHLCV) data for pair {pairs[0][0]}, " |
| 1542 | f"timeframe {pairs[0][1]} ...", |
| 1543 | caplog) |
| 1544 | |
| 1545 | |
| 1546 | @pytest.mark.asyncio |
| 1547 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1548 | async def test__async_get_candle_history(default_conf, mocker, caplog, exchange_name): |
| 1549 | ohlcv = [ |
| 1550 | [ |
| 1551 | arrow.utcnow().int_timestamp * 1000, # unix timestamp ms |
| 1552 | 1, # open |
| 1553 | 2, # high |
| 1554 | 3, # low |
| 1555 | 4, # close |
| 1556 | 5, # volume (in quote currency) |
| 1557 | ] |
| 1558 | ] |
| 1559 | |
| 1560 | caplog.set_level(logging.DEBUG) |
| 1561 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1562 | # Monkey-patch async function |
| 1563 | exchange._api_async.fetch_ohlcv = get_mock_coro(ohlcv) |
| 1564 | |
| 1565 | pair = 'ETH/BTC' |
| 1566 | res = await exchange._async_get_candle_history(pair, "5m") |
| 1567 | assert type(res) is tuple |
| 1568 | assert len(res) == 3 |
| 1569 | assert res[0] == pair |
| 1570 | assert res[1] == "5m" |
| 1571 | assert res[2] == ohlcv |
| 1572 | assert exchange._api_async.fetch_ohlcv.call_count == 1 |
| 1573 | assert not log_has(f"Using cached candle (OHLCV) data for {pair} ...", caplog) |
| 1574 | |
| 1575 | # exchange = Exchange(default_conf) |
| 1576 | await async_ccxt_exception(mocker, default_conf, MagicMock(), |
| 1577 | "_async_get_candle_history", "fetch_ohlcv", |
| 1578 | pair='ABCD/BTC', timeframe=default_conf['timeframe']) |
| 1579 | |
| 1580 | api_mock = MagicMock() |
| 1581 | with pytest.raises(OperationalException, |
| 1582 | match=r'Could not fetch historical candle \(OHLCV\) data.*'): |
| 1583 | api_mock.fetch_ohlcv = MagicMock(side_effect=ccxt.BaseError("Unknown error")) |
| 1584 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1585 | await exchange._async_get_candle_history(pair, "5m", |
| 1586 | (arrow.utcnow().int_timestamp - 2000) * 1000) |
| 1587 | |
| 1588 | with pytest.raises(OperationalException, match=r'Exchange.* does not support fetching ' |
| 1589 | r'historical candle \(OHLCV\) data\..*'): |
| 1590 | api_mock.fetch_ohlcv = MagicMock(side_effect=ccxt.NotSupported("Not supported")) |
| 1591 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1592 | await exchange._async_get_candle_history(pair, "5m", |
| 1593 | (arrow.utcnow().int_timestamp - 2000) * 1000) |
| 1594 | |
| 1595 | |
| 1596 | @pytest.mark.asyncio |
| 1597 | async def test__async_get_candle_history_empty(default_conf, mocker, caplog): |
| 1598 | """ Test empty exchange result """ |
| 1599 | ohlcv = [] |
| 1600 | |
| 1601 | caplog.set_level(logging.DEBUG) |
| 1602 | exchange = get_patched_exchange(mocker, default_conf) |
| 1603 | # Monkey-patch async function |
| 1604 | exchange._api_async.fetch_ohlcv = get_mock_coro([]) |
| 1605 | |
| 1606 | exchange = Exchange(default_conf) |
| 1607 | pair = 'ETH/BTC' |
| 1608 | res = await exchange._async_get_candle_history(pair, "5m") |
| 1609 | assert type(res) is tuple |
| 1610 | assert len(res) == 3 |
| 1611 | assert res[0] == pair |
| 1612 | assert res[1] == "5m" |
| 1613 | assert res[2] == ohlcv |
| 1614 | assert exchange._api_async.fetch_ohlcv.call_count == 1 |
| 1615 | |
| 1616 | |
| 1617 | def test_refresh_latest_ohlcv_inv_result(default_conf, mocker, caplog): |
| 1618 | |
| 1619 | async def mock_get_candle_hist(pair, *args, **kwargs): |
| 1620 | if pair == 'ETH/BTC': |
| 1621 | return [[]] |
| 1622 | else: |
| 1623 | raise TypeError() |
| 1624 | |
| 1625 | exchange = get_patched_exchange(mocker, default_conf) |
| 1626 | |
| 1627 | # Monkey-patch async function with empty result |
| 1628 | exchange._api_async.fetch_ohlcv = MagicMock(side_effect=mock_get_candle_hist) |
| 1629 | |
| 1630 | pairs = [("ETH/BTC", "5m"), ("XRP/BTC", "5m")] |
| 1631 | res = exchange.refresh_latest_ohlcv(pairs) |
| 1632 | assert exchange._klines |
| 1633 | assert exchange._api_async.fetch_ohlcv.call_count == 2 |
| 1634 | |
| 1635 | assert type(res) is dict |
| 1636 | assert len(res) == 1 |
| 1637 | # Test that each is in list at least once as order is not guaranteed |
| 1638 | assert log_has("Error loading ETH/BTC. Result was [[]].", caplog) |
| 1639 | assert log_has("Async code raised an exception: TypeError", caplog) |
| 1640 | |
| 1641 | |
| 1642 | def test_get_next_limit_in_list(): |
| 1643 | limit_range = [5, 10, 20, 50, 100, 500, 1000] |
| 1644 | assert Exchange.get_next_limit_in_list(1, limit_range) == 5 |
| 1645 | assert Exchange.get_next_limit_in_list(5, limit_range) == 5 |
| 1646 | assert Exchange.get_next_limit_in_list(6, limit_range) == 10 |
| 1647 | assert Exchange.get_next_limit_in_list(9, limit_range) == 10 |
| 1648 | assert Exchange.get_next_limit_in_list(10, limit_range) == 10 |
| 1649 | assert Exchange.get_next_limit_in_list(11, limit_range) == 20 |
| 1650 | assert Exchange.get_next_limit_in_list(19, limit_range) == 20 |
| 1651 | assert Exchange.get_next_limit_in_list(21, limit_range) == 50 |
| 1652 | assert Exchange.get_next_limit_in_list(51, limit_range) == 100 |
| 1653 | assert Exchange.get_next_limit_in_list(1000, limit_range) == 1000 |
| 1654 | # Going over the limit ... |
| 1655 | assert Exchange.get_next_limit_in_list(1001, limit_range) == 1000 |
| 1656 | assert Exchange.get_next_limit_in_list(2000, limit_range) == 1000 |
| 1657 | # Without required range |
| 1658 | assert Exchange.get_next_limit_in_list(2000, limit_range, False) is None |
| 1659 | assert Exchange.get_next_limit_in_list(15, limit_range, False) == 20 |
| 1660 | |
| 1661 | assert Exchange.get_next_limit_in_list(21, None) == 21 |
| 1662 | assert Exchange.get_next_limit_in_list(100, None) == 100 |
| 1663 | assert Exchange.get_next_limit_in_list(1000, None) == 1000 |
| 1664 | |
| 1665 | |
| 1666 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1667 | def test_fetch_l2_order_book(default_conf, mocker, order_book_l2, exchange_name): |
| 1668 | default_conf['exchange']['name'] = exchange_name |
| 1669 | api_mock = MagicMock() |
| 1670 | |
| 1671 | api_mock.fetch_l2_order_book = order_book_l2 |
| 1672 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1673 | order_book = exchange.fetch_l2_order_book(pair='ETH/BTC', limit=10) |
| 1674 | assert 'bids' in order_book |
| 1675 | assert 'asks' in order_book |
| 1676 | assert len(order_book['bids']) == 10 |
| 1677 | assert len(order_book['asks']) == 10 |
| 1678 | assert api_mock.fetch_l2_order_book.call_args_list[0][0][0] == 'ETH/BTC' |
| 1679 | |
| 1680 | for val in [1, 5, 10, 12, 20, 50, 100]: |
| 1681 | api_mock.fetch_l2_order_book.reset_mock() |
| 1682 | |
| 1683 | order_book = exchange.fetch_l2_order_book(pair='ETH/BTC', limit=val) |
| 1684 | assert api_mock.fetch_l2_order_book.call_args_list[0][0][0] == 'ETH/BTC' |
| 1685 | # Not all exchanges support all limits for orderbook |
| 1686 | if not exchange._ft_has['l2_limit_range'] or val in exchange._ft_has['l2_limit_range']: |
| 1687 | assert api_mock.fetch_l2_order_book.call_args_list[0][0][1] == val |
| 1688 | else: |
| 1689 | next_limit = exchange.get_next_limit_in_list(val, exchange._ft_has['l2_limit_range']) |
| 1690 | assert api_mock.fetch_l2_order_book.call_args_list[0][0][1] == next_limit |
| 1691 | |
| 1692 | |
| 1693 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1694 | def test_fetch_l2_order_book_exception(default_conf, mocker, exchange_name): |
| 1695 | api_mock = MagicMock() |
| 1696 | with pytest.raises(OperationalException): |
| 1697 | api_mock.fetch_l2_order_book = MagicMock(side_effect=ccxt.NotSupported("Not supported")) |
| 1698 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1699 | exchange.fetch_l2_order_book(pair='ETH/BTC', limit=50) |
| 1700 | with pytest.raises(TemporaryError): |
| 1701 | api_mock.fetch_l2_order_book = MagicMock(side_effect=ccxt.NetworkError("DeadBeef")) |
| 1702 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1703 | exchange.fetch_l2_order_book(pair='ETH/BTC', limit=50) |
| 1704 | with pytest.raises(OperationalException): |
| 1705 | api_mock.fetch_l2_order_book = MagicMock(side_effect=ccxt.BaseError("DeadBeef")) |
| 1706 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1707 | exchange.fetch_l2_order_book(pair='ETH/BTC', limit=50) |
| 1708 | |
| 1709 | |
| 1710 | def make_fetch_ohlcv_mock(data): |
| 1711 | def fetch_ohlcv_mock(pair, timeframe, since): |
| 1712 | if since: |
| 1713 | assert since > data[-1][0] |
| 1714 | return [] |
| 1715 | return data |
| 1716 | return fetch_ohlcv_mock |
| 1717 | |
| 1718 | |
| 1719 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1720 | @pytest.mark.asyncio |
| 1721 | async def test___async_get_candle_history_sort(default_conf, mocker, exchange_name): |
| 1722 | def sort_data(data, key): |
| 1723 | return sorted(data, key=key) |
| 1724 | |
| 1725 | # GDAX use-case (real data from GDAX) |
| 1726 | # This OHLCV data is ordered DESC (newest first, oldest last) |
| 1727 | ohlcv = [ |
| 1728 | [1527833100000, 0.07666, 0.07671, 0.07666, 0.07668, 16.65244264], |
| 1729 | [1527832800000, 0.07662, 0.07666, 0.07662, 0.07666, 1.30051526], |
| 1730 | [1527832500000, 0.07656, 0.07661, 0.07656, 0.07661, 12.034778840000001], |
| 1731 | [1527832200000, 0.07658, 0.07658, 0.07655, 0.07656, 0.59780186], |
| 1732 | [1527831900000, 0.07658, 0.07658, 0.07658, 0.07658, 1.76278136], |
| 1733 | [1527831600000, 0.07658, 0.07658, 0.07658, 0.07658, 2.22646521], |
| 1734 | [1527831300000, 0.07655, 0.07657, 0.07655, 0.07657, 1.1753], |
| 1735 | [1527831000000, 0.07654, 0.07654, 0.07651, 0.07651, 0.8073060299999999], |
| 1736 | [1527830700000, 0.07652, 0.07652, 0.07651, 0.07652, 10.04822687], |
| 1737 | [1527830400000, 0.07649, 0.07651, 0.07649, 0.07651, 2.5734867] |
| 1738 | ] |
| 1739 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1740 | exchange._api_async.fetch_ohlcv = get_mock_coro(ohlcv) |
| 1741 | sort_mock = mocker.patch('freqtrade.exchange.exchange.sorted', MagicMock(side_effect=sort_data)) |
| 1742 | # Test the OHLCV data sort |
| 1743 | res = await exchange._async_get_candle_history('ETH/BTC', default_conf['timeframe']) |
| 1744 | assert res[0] == 'ETH/BTC' |
| 1745 | res_ohlcv = res[2] |
| 1746 | |
| 1747 | assert sort_mock.call_count == 1 |
| 1748 | assert res_ohlcv[0][0] == 1527830400000 |
| 1749 | assert res_ohlcv[0][1] == 0.07649 |
| 1750 | assert res_ohlcv[0][2] == 0.07651 |
| 1751 | assert res_ohlcv[0][3] == 0.07649 |
| 1752 | assert res_ohlcv[0][4] == 0.07651 |
| 1753 | assert res_ohlcv[0][5] == 2.5734867 |
| 1754 | |
| 1755 | assert res_ohlcv[9][0] == 1527833100000 |
| 1756 | assert res_ohlcv[9][1] == 0.07666 |
| 1757 | assert res_ohlcv[9][2] == 0.07671 |
| 1758 | assert res_ohlcv[9][3] == 0.07666 |
| 1759 | assert res_ohlcv[9][4] == 0.07668 |
| 1760 | assert res_ohlcv[9][5] == 16.65244264 |
| 1761 | |
| 1762 | # Bittrex use-case (real data from Bittrex) |
| 1763 | # This OHLCV data is ordered ASC (oldest first, newest last) |
| 1764 | ohlcv = [ |
| 1765 | [1527827700000, 0.07659999, 0.0766, 0.07627, 0.07657998, 1.85216924], |
| 1766 | [1527828000000, 0.07657995, 0.07657995, 0.0763, 0.0763, 26.04051037], |
| 1767 | [1527828300000, 0.0763, 0.07659998, 0.0763, 0.0764, 10.36434124], |
| 1768 | [1527828600000, 0.0764, 0.0766, 0.0764, 0.0766, 5.71044773], |
| 1769 | [1527828900000, 0.0764, 0.07666998, 0.0764, 0.07666998, 47.48888565], |
| 1770 | [1527829200000, 0.0765, 0.07672999, 0.0765, 0.07672999, 3.37640326], |
| 1771 | [1527829500000, 0.0766, 0.07675, 0.0765, 0.07675, 8.36203831], |
| 1772 | [1527829800000, 0.07675, 0.07677999, 0.07620002, 0.076695, 119.22963884], |
| 1773 | [1527830100000, 0.076695, 0.07671, 0.07624171, 0.07671, 1.80689244], |
| 1774 | [1527830400000, 0.07671, 0.07674399, 0.07629216, 0.07655213, 2.31452783] |
| 1775 | ] |
| 1776 | exchange._api_async.fetch_ohlcv = get_mock_coro(ohlcv) |
| 1777 | # Reset sort mock |
| 1778 | sort_mock = mocker.patch('freqtrade.exchange.sorted', MagicMock(side_effect=sort_data)) |
| 1779 | # Test the OHLCV data sort |
| 1780 | res = await exchange._async_get_candle_history('ETH/BTC', default_conf['timeframe']) |
| 1781 | assert res[0] == 'ETH/BTC' |
| 1782 | assert res[1] == default_conf['timeframe'] |
| 1783 | res_ohlcv = res[2] |
| 1784 | # Sorted not called again - data is already in order |
| 1785 | assert sort_mock.call_count == 0 |
| 1786 | assert res_ohlcv[0][0] == 1527827700000 |
| 1787 | assert res_ohlcv[0][1] == 0.07659999 |
| 1788 | assert res_ohlcv[0][2] == 0.0766 |
| 1789 | assert res_ohlcv[0][3] == 0.07627 |
| 1790 | assert res_ohlcv[0][4] == 0.07657998 |
| 1791 | assert res_ohlcv[0][5] == 1.85216924 |
| 1792 | |
| 1793 | assert res_ohlcv[9][0] == 1527830400000 |
| 1794 | assert res_ohlcv[9][1] == 0.07671 |
| 1795 | assert res_ohlcv[9][2] == 0.07674399 |
| 1796 | assert res_ohlcv[9][3] == 0.07629216 |
| 1797 | assert res_ohlcv[9][4] == 0.07655213 |
| 1798 | assert res_ohlcv[9][5] == 2.31452783 |
| 1799 | |
| 1800 | |
| 1801 | @pytest.mark.asyncio |
| 1802 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1803 | async def test__async_fetch_trades(default_conf, mocker, caplog, exchange_name, |
| 1804 | fetch_trades_result): |
| 1805 | |
| 1806 | caplog.set_level(logging.DEBUG) |
| 1807 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1808 | # Monkey-patch async function |
| 1809 | exchange._api_async.fetch_trades = get_mock_coro(fetch_trades_result) |
| 1810 | |
| 1811 | pair = 'ETH/BTC' |
| 1812 | res = await exchange._async_fetch_trades(pair, since=None, params=None) |
| 1813 | assert type(res) is list |
| 1814 | assert isinstance(res[0], list) |
| 1815 | assert isinstance(res[1], list) |
| 1816 | |
| 1817 | assert exchange._api_async.fetch_trades.call_count == 1 |
| 1818 | assert exchange._api_async.fetch_trades.call_args[0][0] == pair |
| 1819 | assert exchange._api_async.fetch_trades.call_args[1]['limit'] == 1000 |
| 1820 | |
| 1821 | assert log_has_re(f"Fetching trades for pair {pair}, since .*", caplog) |
| 1822 | caplog.clear() |
| 1823 | exchange._api_async.fetch_trades.reset_mock() |
| 1824 | res = await exchange._async_fetch_trades(pair, since=None, params={'from': '123'}) |
| 1825 | assert exchange._api_async.fetch_trades.call_count == 1 |
| 1826 | assert exchange._api_async.fetch_trades.call_args[0][0] == pair |
| 1827 | assert exchange._api_async.fetch_trades.call_args[1]['limit'] == 1000 |
| 1828 | assert exchange._api_async.fetch_trades.call_args[1]['params'] == {'from': '123'} |
| 1829 | assert log_has_re(f"Fetching trades for pair {pair}, params: .*", caplog) |
| 1830 | |
| 1831 | exchange = Exchange(default_conf) |
| 1832 | await async_ccxt_exception(mocker, default_conf, MagicMock(), |
| 1833 | "_async_fetch_trades", "fetch_trades", |
| 1834 | pair='ABCD/BTC', since=None) |
| 1835 | |
| 1836 | api_mock = MagicMock() |
| 1837 | with pytest.raises(OperationalException, match=r'Could not fetch trade data*'): |
| 1838 | api_mock.fetch_trades = MagicMock(side_effect=ccxt.BaseError("Unknown error")) |
| 1839 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1840 | await exchange._async_fetch_trades(pair, since=(arrow.utcnow().int_timestamp - 2000) * 1000) |
| 1841 | |
| 1842 | with pytest.raises(OperationalException, match=r'Exchange.* does not support fetching ' |
| 1843 | r'historical trade data\..*'): |
| 1844 | api_mock.fetch_trades = MagicMock(side_effect=ccxt.NotSupported("Not supported")) |
| 1845 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 1846 | await exchange._async_fetch_trades(pair, since=(arrow.utcnow().int_timestamp - 2000) * 1000) |
| 1847 | |
| 1848 | |
| 1849 | @pytest.mark.asyncio |
| 1850 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1851 | async def test__async_get_trade_history_id(default_conf, mocker, exchange_name, |
| 1852 | fetch_trades_result): |
| 1853 | |
| 1854 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1855 | pagination_arg = exchange._trades_pagination_arg |
| 1856 | |
| 1857 | async def mock_get_trade_hist(pair, *args, **kwargs): |
| 1858 | if 'since' in kwargs: |
| 1859 | # Return first 3 |
| 1860 | return fetch_trades_result[:-2] |
| 1861 | elif kwargs.get('params', {}).get(pagination_arg) == fetch_trades_result[-3]['id']: |
| 1862 | # Return 2 |
| 1863 | return fetch_trades_result[-3:-1] |
| 1864 | else: |
| 1865 | # Return last 2 |
| 1866 | return fetch_trades_result[-2:] |
| 1867 | # Monkey-patch async function |
| 1868 | exchange._api_async.fetch_trades = MagicMock(side_effect=mock_get_trade_hist) |
| 1869 | |
| 1870 | pair = 'ETH/BTC' |
| 1871 | ret = await exchange._async_get_trade_history_id(pair, |
| 1872 | since=fetch_trades_result[0]['timestamp'], |
| 1873 | until=fetch_trades_result[-1]['timestamp'] - 1) |
| 1874 | assert type(ret) is tuple |
| 1875 | assert ret[0] == pair |
| 1876 | assert type(ret[1]) is list |
| 1877 | assert len(ret[1]) == len(fetch_trades_result) |
| 1878 | assert exchange._api_async.fetch_trades.call_count == 3 |
| 1879 | fetch_trades_cal = exchange._api_async.fetch_trades.call_args_list |
| 1880 | # first call (using since, not fromId) |
| 1881 | assert fetch_trades_cal[0][0][0] == pair |
| 1882 | assert fetch_trades_cal[0][1]['since'] == fetch_trades_result[0]['timestamp'] |
| 1883 | |
| 1884 | # 2nd call |
| 1885 | assert fetch_trades_cal[1][0][0] == pair |
| 1886 | assert 'params' in fetch_trades_cal[1][1] |
| 1887 | assert exchange._ft_has['trades_pagination_arg'] in fetch_trades_cal[1][1]['params'] |
| 1888 | |
| 1889 | |
| 1890 | @pytest.mark.asyncio |
| 1891 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1892 | async def test__async_get_trade_history_time(default_conf, mocker, caplog, exchange_name, |
| 1893 | fetch_trades_result): |
| 1894 | |
| 1895 | caplog.set_level(logging.DEBUG) |
| 1896 | |
| 1897 | async def mock_get_trade_hist(pair, *args, **kwargs): |
| 1898 | if kwargs['since'] == fetch_trades_result[0]['timestamp']: |
| 1899 | return fetch_trades_result[:-1] |
| 1900 | else: |
| 1901 | return fetch_trades_result[-1:] |
| 1902 | |
| 1903 | caplog.set_level(logging.DEBUG) |
| 1904 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1905 | # Monkey-patch async function |
| 1906 | exchange._api_async.fetch_trades = MagicMock(side_effect=mock_get_trade_hist) |
| 1907 | pair = 'ETH/BTC' |
| 1908 | ret = await exchange._async_get_trade_history_time(pair, |
| 1909 | since=fetch_trades_result[0]['timestamp'], |
| 1910 | until=fetch_trades_result[-1]['timestamp']-1) |
| 1911 | assert type(ret) is tuple |
| 1912 | assert ret[0] == pair |
| 1913 | assert type(ret[1]) is list |
| 1914 | assert len(ret[1]) == len(fetch_trades_result) |
| 1915 | assert exchange._api_async.fetch_trades.call_count == 2 |
| 1916 | fetch_trades_cal = exchange._api_async.fetch_trades.call_args_list |
| 1917 | # first call (using since, not fromId) |
| 1918 | assert fetch_trades_cal[0][0][0] == pair |
| 1919 | assert fetch_trades_cal[0][1]['since'] == fetch_trades_result[0]['timestamp'] |
| 1920 | |
| 1921 | # 2nd call |
| 1922 | assert fetch_trades_cal[1][0][0] == pair |
| 1923 | assert fetch_trades_cal[1][1]['since'] == fetch_trades_result[-2]['timestamp'] |
| 1924 | assert log_has_re(r"Stopping because until was reached.*", caplog) |
| 1925 | |
| 1926 | |
| 1927 | @pytest.mark.asyncio |
| 1928 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1929 | async def test__async_get_trade_history_time_empty(default_conf, mocker, caplog, exchange_name, |
| 1930 | trades_history): |
| 1931 | |
| 1932 | caplog.set_level(logging.DEBUG) |
| 1933 | |
| 1934 | async def mock_get_trade_hist(pair, *args, **kwargs): |
| 1935 | if kwargs['since'] == trades_history[0][0]: |
| 1936 | return trades_history[:-1] |
| 1937 | else: |
| 1938 | return [] |
| 1939 | |
| 1940 | caplog.set_level(logging.DEBUG) |
| 1941 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1942 | # Monkey-patch async function |
| 1943 | exchange._async_fetch_trades = MagicMock(side_effect=mock_get_trade_hist) |
| 1944 | pair = 'ETH/BTC' |
| 1945 | ret = await exchange._async_get_trade_history_time(pair, since=trades_history[0][0], |
| 1946 | until=trades_history[-1][0]-1) |
| 1947 | assert type(ret) is tuple |
| 1948 | assert ret[0] == pair |
| 1949 | assert type(ret[1]) is list |
| 1950 | assert len(ret[1]) == len(trades_history) - 1 |
| 1951 | assert exchange._async_fetch_trades.call_count == 2 |
| 1952 | fetch_trades_cal = exchange._async_fetch_trades.call_args_list |
| 1953 | # first call (using since, not fromId) |
| 1954 | assert fetch_trades_cal[0][0][0] == pair |
| 1955 | assert fetch_trades_cal[0][1]['since'] == trades_history[0][0] |
| 1956 | |
| 1957 | |
| 1958 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1959 | def test_get_historic_trades(default_conf, mocker, caplog, exchange_name, trades_history): |
| 1960 | mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=True) |
| 1961 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1962 | |
| 1963 | pair = 'ETH/BTC' |
| 1964 | |
| 1965 | exchange._async_get_trade_history_id = get_mock_coro((pair, trades_history)) |
| 1966 | exchange._async_get_trade_history_time = get_mock_coro((pair, trades_history)) |
| 1967 | ret = exchange.get_historic_trades(pair, since=trades_history[0][0], |
| 1968 | until=trades_history[-1][0]) |
| 1969 | |
| 1970 | # Depending on the exchange, one or the other method should be called |
| 1971 | assert sum([exchange._async_get_trade_history_id.call_count, |
| 1972 | exchange._async_get_trade_history_time.call_count]) == 1 |
| 1973 | |
| 1974 | assert len(ret) == 2 |
| 1975 | assert ret[0] == pair |
| 1976 | assert len(ret[1]) == len(trades_history) |
| 1977 | |
| 1978 | |
| 1979 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1980 | def test_get_historic_trades_notsupported(default_conf, mocker, caplog, exchange_name, |
| 1981 | trades_history): |
| 1982 | mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=False) |
| 1983 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1984 | |
| 1985 | pair = 'ETH/BTC' |
| 1986 | |
| 1987 | with pytest.raises(OperationalException, |
| 1988 | match="This exchange does not suport downloading Trades."): |
| 1989 | exchange.get_historic_trades(pair, since=trades_history[0][0], |
| 1990 | until=trades_history[-1][0]) |
| 1991 | |
| 1992 | |
| 1993 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 1994 | def test_cancel_order_dry_run(default_conf, mocker, exchange_name): |
| 1995 | default_conf['dry_run'] = True |
| 1996 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 1997 | assert exchange.cancel_order(order_id='123', pair='TKN/BTC') == {} |
| 1998 | assert exchange.cancel_stoploss_order(order_id='123', pair='TKN/BTC') == {} |
| 1999 | |
| 2000 | order = exchange.buy('ETH/BTC', 'limit', 5, 0.55, 'gtc') |
| 2001 | |
| 2002 | cancel_order = exchange.cancel_order(order_id=order['id'], pair='ETH/BTC') |
| 2003 | assert order['id'] == cancel_order['id'] |
| 2004 | assert order['amount'] == cancel_order['amount'] |
| 2005 | assert order['symbol'] == cancel_order['symbol'] |
| 2006 | assert cancel_order['status'] == 'canceled' |
| 2007 | |
| 2008 | |
| 2009 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2010 | @pytest.mark.parametrize("order,result", [ |
| 2011 | ({'status': 'closed', 'filled': 10}, False), |
| 2012 | ({'status': 'closed', 'filled': 0.0}, True), |
| 2013 | ({'status': 'canceled', 'filled': 0.0}, True), |
| 2014 | ({'status': 'canceled', 'filled': 10.0}, False), |
| 2015 | ({'status': 'unknown', 'filled': 10.0}, False), |
| 2016 | ({'result': 'testest123'}, False), |
| 2017 | ]) |
| 2018 | def test_check_order_canceled_empty(mocker, default_conf, exchange_name, order, result): |
| 2019 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 2020 | assert exchange.check_order_canceled_empty(order) == result |
| 2021 | |
| 2022 | |
| 2023 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2024 | @pytest.mark.parametrize("order,result", [ |
| 2025 | ({'status': 'closed', 'amount': 10, 'fee': {}}, True), |
| 2026 | ({'status': 'closed', 'amount': 0.0, 'fee': {}}, True), |
| 2027 | ({'status': 'canceled', 'amount': 0.0, 'fee': {}}, True), |
| 2028 | ({'status': 'canceled', 'amount': 10.0}, False), |
| 2029 | ({'amount': 10.0, 'fee': {}}, False), |
| 2030 | ({'result': 'testest123'}, False), |
| 2031 | ('hello_world', False), |
| 2032 | ]) |
| 2033 | def test_is_cancel_order_result_suitable(mocker, default_conf, exchange_name, order, result): |
| 2034 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 2035 | assert exchange.is_cancel_order_result_suitable(order) == result |
| 2036 | |
| 2037 | |
| 2038 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2039 | @pytest.mark.parametrize("corder,call_corder,call_forder", [ |
| 2040 | ({'status': 'closed', 'amount': 10, 'fee': {}}, 1, 0), |
| 2041 | ({'amount': 10, 'fee': {}}, 1, 1), |
| 2042 | ]) |
| 2043 | def test_cancel_order_with_result(default_conf, mocker, exchange_name, corder, |
| 2044 | call_corder, call_forder): |
| 2045 | default_conf['dry_run'] = False |
| 2046 | api_mock = MagicMock() |
| 2047 | api_mock.cancel_order = MagicMock(return_value=corder) |
| 2048 | api_mock.fetch_order = MagicMock(return_value={}) |
| 2049 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2050 | res = exchange.cancel_order_with_result('1234', 'ETH/BTC', 1234) |
| 2051 | assert isinstance(res, dict) |
| 2052 | assert api_mock.cancel_order.call_count == call_corder |
| 2053 | assert api_mock.fetch_order.call_count == call_forder |
| 2054 | |
| 2055 | |
| 2056 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2057 | def test_cancel_order_with_result_error(default_conf, mocker, exchange_name, caplog): |
| 2058 | default_conf['dry_run'] = False |
| 2059 | api_mock = MagicMock() |
| 2060 | api_mock.cancel_order = MagicMock(side_effect=ccxt.InvalidOrder("Did not find order")) |
| 2061 | api_mock.fetch_order = MagicMock(side_effect=ccxt.InvalidOrder("Did not find order")) |
| 2062 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2063 | |
| 2064 | res = exchange.cancel_order_with_result('1234', 'ETH/BTC', 1541) |
| 2065 | assert isinstance(res, dict) |
| 2066 | assert log_has("Could not cancel order 1234 for ETH/BTC.", caplog) |
| 2067 | assert log_has("Could not fetch cancelled order 1234.", caplog) |
| 2068 | assert res['amount'] == 1541 |
| 2069 | |
| 2070 | |
| 2071 | # Ensure that if not dry_run, we should call API |
| 2072 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2073 | def test_cancel_order(default_conf, mocker, exchange_name): |
| 2074 | default_conf['dry_run'] = False |
| 2075 | api_mock = MagicMock() |
| 2076 | api_mock.cancel_order = MagicMock(return_value={'id': '123'}) |
| 2077 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2078 | assert exchange.cancel_order(order_id='_', pair='TKN/BTC') == {'id': '123'} |
| 2079 | |
| 2080 | with pytest.raises(InvalidOrderException): |
| 2081 | api_mock.cancel_order = MagicMock(side_effect=ccxt.InvalidOrder("Did not find order")) |
| 2082 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2083 | exchange.cancel_order(order_id='_', pair='TKN/BTC') |
| 2084 | assert api_mock.cancel_order.call_count == 1 |
| 2085 | |
| 2086 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 2087 | "cancel_order", "cancel_order", |
| 2088 | order_id='_', pair='TKN/BTC') |
| 2089 | |
| 2090 | |
| 2091 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2092 | def test_cancel_stoploss_order(default_conf, mocker, exchange_name): |
| 2093 | default_conf['dry_run'] = False |
| 2094 | api_mock = MagicMock() |
| 2095 | api_mock.cancel_order = MagicMock(return_value={'id': '123'}) |
| 2096 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2097 | assert exchange.cancel_stoploss_order(order_id='_', pair='TKN/BTC') == {'id': '123'} |
| 2098 | |
| 2099 | with pytest.raises(InvalidOrderException): |
| 2100 | api_mock.cancel_order = MagicMock(side_effect=ccxt.InvalidOrder("Did not find order")) |
| 2101 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2102 | exchange.cancel_stoploss_order(order_id='_', pair='TKN/BTC') |
| 2103 | assert api_mock.cancel_order.call_count == 1 |
| 2104 | |
| 2105 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 2106 | "cancel_stoploss_order", "cancel_order", |
| 2107 | order_id='_', pair='TKN/BTC') |
| 2108 | |
| 2109 | |
| 2110 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2111 | def test_fetch_order(default_conf, mocker, exchange_name): |
| 2112 | default_conf['dry_run'] = True |
| 2113 | order = MagicMock() |
| 2114 | order.myid = 123 |
| 2115 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 2116 | exchange._dry_run_open_orders['X'] = order |
| 2117 | assert exchange.fetch_order('X', 'TKN/BTC').myid == 123 |
| 2118 | |
| 2119 | with pytest.raises(InvalidOrderException, match=r'Tried to get an invalid dry-run-order.*'): |
| 2120 | exchange.fetch_order('Y', 'TKN/BTC') |
| 2121 | |
| 2122 | default_conf['dry_run'] = False |
| 2123 | api_mock = MagicMock() |
| 2124 | api_mock.fetch_order = MagicMock(return_value=456) |
| 2125 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2126 | assert exchange.fetch_order('X', 'TKN/BTC') == 456 |
| 2127 | |
| 2128 | with pytest.raises(InvalidOrderException): |
| 2129 | api_mock.fetch_order = MagicMock(side_effect=ccxt.InvalidOrder("Order not found")) |
| 2130 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2131 | exchange.fetch_order(order_id='_', pair='TKN/BTC') |
| 2132 | assert api_mock.fetch_order.call_count == 1 |
| 2133 | |
| 2134 | api_mock.fetch_order = MagicMock(side_effect=ccxt.OrderNotFound("Order not found")) |
| 2135 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2136 | with patch('freqtrade.exchange.common.time.sleep') as tm: |
| 2137 | with pytest.raises(InvalidOrderException): |
| 2138 | exchange.fetch_order(order_id='_', pair='TKN/BTC') |
| 2139 | # Ensure backoff is called |
| 2140 | assert tm.call_args_list[0][0][0] == 1 |
| 2141 | assert tm.call_args_list[1][0][0] == 2 |
| 2142 | if API_FETCH_ORDER_RETRY_COUNT > 2: |
| 2143 | assert tm.call_args_list[2][0][0] == 5 |
| 2144 | if API_FETCH_ORDER_RETRY_COUNT > 3: |
| 2145 | assert tm.call_args_list[3][0][0] == 10 |
| 2146 | assert api_mock.fetch_order.call_count == API_FETCH_ORDER_RETRY_COUNT + 1 |
| 2147 | |
| 2148 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 2149 | 'fetch_order', 'fetch_order', retries=API_FETCH_ORDER_RETRY_COUNT + 1, |
| 2150 | order_id='_', pair='TKN/BTC') |
| 2151 | |
| 2152 | |
| 2153 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2154 | def test_fetch_stoploss_order(default_conf, mocker, exchange_name): |
| 2155 | # Don't test FTX here - that needs a seperate test |
| 2156 | if exchange_name == 'ftx': |
| 2157 | return |
| 2158 | default_conf['dry_run'] = True |
| 2159 | order = MagicMock() |
| 2160 | order.myid = 123 |
| 2161 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 2162 | exchange._dry_run_open_orders['X'] = order |
| 2163 | assert exchange.fetch_stoploss_order('X', 'TKN/BTC').myid == 123 |
| 2164 | |
| 2165 | with pytest.raises(InvalidOrderException, match=r'Tried to get an invalid dry-run-order.*'): |
| 2166 | exchange.fetch_stoploss_order('Y', 'TKN/BTC') |
| 2167 | |
| 2168 | default_conf['dry_run'] = False |
| 2169 | api_mock = MagicMock() |
| 2170 | api_mock.fetch_order = MagicMock(return_value=456) |
| 2171 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2172 | assert exchange.fetch_stoploss_order('X', 'TKN/BTC') == 456 |
| 2173 | |
| 2174 | with pytest.raises(InvalidOrderException): |
| 2175 | api_mock.fetch_order = MagicMock(side_effect=ccxt.InvalidOrder("Order not found")) |
| 2176 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2177 | exchange.fetch_stoploss_order(order_id='_', pair='TKN/BTC') |
| 2178 | assert api_mock.fetch_order.call_count == 1 |
| 2179 | |
| 2180 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 2181 | 'fetch_stoploss_order', 'fetch_order', |
| 2182 | retries=API_FETCH_ORDER_RETRY_COUNT + 1, |
| 2183 | order_id='_', pair='TKN/BTC') |
| 2184 | |
| 2185 | |
| 2186 | def test_fetch_order_or_stoploss_order(default_conf, mocker): |
| 2187 | exchange = get_patched_exchange(mocker, default_conf, id='binance') |
| 2188 | fetch_order_mock = MagicMock() |
| 2189 | fetch_stoploss_order_mock = MagicMock() |
| 2190 | mocker.patch.multiple('freqtrade.exchange.Exchange', |
| 2191 | fetch_order=fetch_order_mock, |
| 2192 | fetch_stoploss_order=fetch_stoploss_order_mock, |
| 2193 | ) |
| 2194 | |
| 2195 | exchange.fetch_order_or_stoploss_order('1234', 'ETH/BTC', False) |
| 2196 | assert fetch_order_mock.call_count == 1 |
| 2197 | assert fetch_order_mock.call_args_list[0][0][0] == '1234' |
| 2198 | assert fetch_order_mock.call_args_list[0][0][1] == 'ETH/BTC' |
| 2199 | assert fetch_stoploss_order_mock.call_count == 0 |
| 2200 | |
| 2201 | fetch_order_mock.reset_mock() |
| 2202 | fetch_stoploss_order_mock.reset_mock() |
| 2203 | |
| 2204 | exchange.fetch_order_or_stoploss_order('1234', 'ETH/BTC', True) |
| 2205 | assert fetch_order_mock.call_count == 0 |
| 2206 | assert fetch_stoploss_order_mock.call_count == 1 |
| 2207 | assert fetch_stoploss_order_mock.call_args_list[0][0][0] == '1234' |
| 2208 | assert fetch_stoploss_order_mock.call_args_list[0][0][1] == 'ETH/BTC' |
| 2209 | |
| 2210 | |
| 2211 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2212 | def test_name(default_conf, mocker, exchange_name): |
| 2213 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 2214 | |
| 2215 | assert exchange.name == exchange_name.title() |
| 2216 | assert exchange.id == exchange_name |
| 2217 | |
| 2218 | |
| 2219 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2220 | def test_get_trades_for_order(default_conf, mocker, exchange_name): |
| 2221 | |
| 2222 | order_id = 'ABCD-ABCD' |
| 2223 | since = datetime(2018, 5, 5, 0, 0, 0) |
| 2224 | default_conf["dry_run"] = False |
| 2225 | mocker.patch('freqtrade.exchange.Exchange.exchange_has', return_value=True) |
| 2226 | api_mock = MagicMock() |
| 2227 | |
| 2228 | api_mock.fetch_my_trades = MagicMock(return_value=[{'id': 'TTR67E-3PFBD-76IISV', |
| 2229 | 'order': 'ABCD-ABCD', |
| 2230 | 'info': {'pair': 'XLTCZBTC', |
| 2231 | 'time': 1519860024.4388, |
| 2232 | 'type': 'buy', |
| 2233 | 'ordertype': 'limit', |
| 2234 | 'price': '20.00000', |
| 2235 | 'cost': '38.62000', |
| 2236 | 'fee': '0.06179', |
| 2237 | 'vol': '5', |
| 2238 | 'id': 'ABCD-ABCD'}, |
| 2239 | 'timestamp': 1519860024438, |
| 2240 | 'datetime': '2018-02-28T23:20:24.438Z', |
| 2241 | 'symbol': 'LTC/BTC', |
| 2242 | 'type': 'limit', |
| 2243 | 'side': 'buy', |
| 2244 | 'price': 165.0, |
| 2245 | 'amount': 0.2340606, |
| 2246 | 'fee': {'cost': 0.06179, 'currency': 'BTC'} |
| 2247 | }]) |
| 2248 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2249 | |
| 2250 | orders = exchange.get_trades_for_order(order_id, 'LTC/BTC', since) |
| 2251 | assert len(orders) == 1 |
| 2252 | assert orders[0]['price'] == 165 |
| 2253 | assert api_mock.fetch_my_trades.call_count == 1 |
| 2254 | # since argument should be |
| 2255 | assert isinstance(api_mock.fetch_my_trades.call_args[0][1], int) |
| 2256 | assert api_mock.fetch_my_trades.call_args[0][0] == 'LTC/BTC' |
| 2257 | # Same test twice, hardcoded number and doing the same calculation |
| 2258 | assert api_mock.fetch_my_trades.call_args[0][1] == 1525478395000 |
| 2259 | assert api_mock.fetch_my_trades.call_args[0][1] == int(since.replace( |
| 2260 | tzinfo=timezone.utc).timestamp() - 5) * 1000 |
| 2261 | |
| 2262 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 2263 | 'get_trades_for_order', 'fetch_my_trades', |
| 2264 | order_id=order_id, pair='LTC/BTC', since=since) |
| 2265 | |
| 2266 | mocker.patch('freqtrade.exchange.Exchange.exchange_has', MagicMock(return_value=False)) |
| 2267 | assert exchange.get_trades_for_order(order_id, 'LTC/BTC', since) == [] |
| 2268 | |
| 2269 | |
| 2270 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2271 | def test_get_fee(default_conf, mocker, exchange_name): |
| 2272 | api_mock = MagicMock() |
| 2273 | api_mock.calculate_fee = MagicMock(return_value={ |
| 2274 | 'type': 'taker', |
| 2275 | 'currency': 'BTC', |
| 2276 | 'rate': 0.025, |
| 2277 | 'cost': 0.05 |
| 2278 | }) |
| 2279 | exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) |
| 2280 | exchange._config.pop('fee', None) |
| 2281 | |
| 2282 | assert exchange.get_fee('ETH/BTC') == 0.025 |
| 2283 | assert api_mock.calculate_fee.call_count == 1 |
| 2284 | |
| 2285 | ccxt_exceptionhandlers(mocker, default_conf, api_mock, exchange_name, |
| 2286 | 'get_fee', 'calculate_fee', symbol="ETH/BTC") |
| 2287 | |
| 2288 | api_mock.calculate_fee.reset_mock() |
| 2289 | exchange._config['fee'] = 0.001 |
| 2290 | |
| 2291 | assert exchange.get_fee('ETH/BTC') == 0.001 |
| 2292 | assert api_mock.calculate_fee.call_count == 0 |
| 2293 | |
| 2294 | |
| 2295 | def test_stoploss_order_unsupported_exchange(default_conf, mocker): |
| 2296 | exchange = get_patched_exchange(mocker, default_conf, id='bittrex') |
| 2297 | with pytest.raises(OperationalException, match=r"stoploss is not implemented .*"): |
| 2298 | exchange.stoploss(pair='ETH/BTC', amount=1, stop_price=220, order_types={}) |
| 2299 | |
| 2300 | with pytest.raises(OperationalException, match=r"stoploss is not implemented .*"): |
| 2301 | exchange.stoploss_adjust(1, {}) |
| 2302 | |
| 2303 | |
| 2304 | def test_merge_ft_has_dict(default_conf, mocker): |
| 2305 | mocker.patch.multiple('freqtrade.exchange.Exchange', |
| 2306 | _init_ccxt=MagicMock(return_value=MagicMock()), |
| 2307 | _load_async_markets=MagicMock(), |
| 2308 | validate_pairs=MagicMock(), |
| 2309 | validate_timeframes=MagicMock(), |
| 2310 | validate_stakecurrency=MagicMock() |
| 2311 | ) |
| 2312 | ex = Exchange(default_conf) |
| 2313 | assert ex._ft_has == Exchange._ft_has_default |
| 2314 | |
| 2315 | ex = Kraken(default_conf) |
| 2316 | assert ex._ft_has != Exchange._ft_has_default |
| 2317 | assert ex._ft_has['trades_pagination'] == 'id' |
| 2318 | assert ex._ft_has['trades_pagination_arg'] == 'since' |
| 2319 | |
| 2320 | # Binance defines different values |
| 2321 | ex = Binance(default_conf) |
| 2322 | assert ex._ft_has != Exchange._ft_has_default |
| 2323 | assert ex._ft_has['stoploss_on_exchange'] |
| 2324 | assert ex._ft_has['order_time_in_force'] == ['gtc', 'fok', 'ioc'] |
| 2325 | assert ex._ft_has['trades_pagination'] == 'id' |
| 2326 | assert ex._ft_has['trades_pagination_arg'] == 'fromId' |
| 2327 | |
| 2328 | conf = copy.deepcopy(default_conf) |
| 2329 | conf['exchange']['_ft_has_params'] = {"DeadBeef": 20, |
| 2330 | "stoploss_on_exchange": False} |
| 2331 | # Use settings from configuration (overriding stoploss_on_exchange) |
| 2332 | ex = Binance(conf) |
| 2333 | assert ex._ft_has != Exchange._ft_has_default |
| 2334 | assert not ex._ft_has['stoploss_on_exchange'] |
| 2335 | assert ex._ft_has['DeadBeef'] == 20 |
| 2336 | |
| 2337 | |
| 2338 | def test_get_valid_pair_combination(default_conf, mocker, markets): |
| 2339 | mocker.patch.multiple('freqtrade.exchange.Exchange', |
| 2340 | _init_ccxt=MagicMock(return_value=MagicMock()), |
| 2341 | _load_async_markets=MagicMock(), |
| 2342 | validate_pairs=MagicMock(), |
| 2343 | validate_timeframes=MagicMock(), |
| 2344 | markets=PropertyMock(return_value=markets)) |
| 2345 | ex = Exchange(default_conf) |
| 2346 | |
| 2347 | assert ex.get_valid_pair_combination("ETH", "BTC") == "ETH/BTC" |
| 2348 | assert ex.get_valid_pair_combination("BTC", "ETH") == "ETH/BTC" |
| 2349 | with pytest.raises(DependencyException, match=r"Could not combine.* to get a valid pair."): |
| 2350 | ex.get_valid_pair_combination("NOPAIR", "ETH") |
| 2351 | |
| 2352 | |
| 2353 | @pytest.mark.parametrize( |
| 2354 | "base_currencies, quote_currencies, pairs_only, active_only, expected_keys", [ |
| 2355 | # Testing markets (in conftest.py): |
| 2356 | # 'BLK/BTC': 'active': True |
| 2357 | # 'BTT/BTC': 'active': True |
| 2358 | # 'ETH/BTC': 'active': True |
| 2359 | # 'ETH/USDT': 'active': True |
| 2360 | # 'LTC/BTC': 'active': False |
| 2361 | # 'LTC/ETH': 'active': True |
| 2362 | # 'LTC/USD': 'active': True |
| 2363 | # 'LTC/USDT': 'active': True |
| 2364 | # 'NEO/BTC': 'active': False |
| 2365 | # 'TKN/BTC': 'active' not set |
| 2366 | # 'XLTCUSDT': 'active': True, not a pair |
| 2367 | # 'XRP/BTC': 'active': False |
| 2368 | # all markets |
| 2369 | ([], [], False, False, |
| 2370 | ['BLK/BTC', 'BTT/BTC', 'ETH/BTC', 'ETH/USDT', 'LTC/BTC', 'LTC/ETH', 'LTC/USD', |
| 2371 | 'LTC/USDT', 'NEO/BTC', 'TKN/BTC', 'XLTCUSDT', 'XRP/BTC']), |
| 2372 | # active markets |
| 2373 | ([], [], False, True, |
| 2374 | ['BLK/BTC', 'ETH/BTC', 'ETH/USDT', 'LTC/BTC', 'LTC/ETH', 'LTC/USD', 'NEO/BTC', |
| 2375 | 'TKN/BTC', 'XLTCUSDT', 'XRP/BTC']), |
| 2376 | # all pairs |
| 2377 | ([], [], True, False, |
| 2378 | ['BLK/BTC', 'BTT/BTC', 'ETH/BTC', 'ETH/USDT', 'LTC/BTC', 'LTC/ETH', 'LTC/USD', |
| 2379 | 'LTC/USDT', 'NEO/BTC', 'TKN/BTC', 'XRP/BTC']), |
| 2380 | # active pairs |
| 2381 | ([], [], True, True, |
| 2382 | ['BLK/BTC', 'ETH/BTC', 'ETH/USDT', 'LTC/BTC', 'LTC/ETH', 'LTC/USD', 'NEO/BTC', |
| 2383 | 'TKN/BTC', 'XRP/BTC']), |
| 2384 | # all markets, base=ETH, LTC |
| 2385 | (['ETH', 'LTC'], [], False, False, |
| 2386 | ['ETH/BTC', 'ETH/USDT', 'LTC/BTC', 'LTC/ETH', 'LTC/USD', 'LTC/USDT', 'XLTCUSDT']), |
| 2387 | # all markets, base=LTC |
| 2388 | (['LTC'], [], False, False, |
| 2389 | ['LTC/BTC', 'LTC/ETH', 'LTC/USD', 'LTC/USDT', 'XLTCUSDT']), |
| 2390 | # all markets, quote=USDT |
| 2391 | ([], ['USDT'], False, False, |
| 2392 | ['ETH/USDT', 'LTC/USDT', 'XLTCUSDT']), |
| 2393 | # all markets, quote=USDT, USD |
| 2394 | ([], ['USDT', 'USD'], False, False, |
| 2395 | ['ETH/USDT', 'LTC/USD', 'LTC/USDT', 'XLTCUSDT']), |
| 2396 | # all markets, base=LTC, quote=USDT |
| 2397 | (['LTC'], ['USDT'], False, False, |
| 2398 | ['LTC/USDT', 'XLTCUSDT']), |
| 2399 | # all pairs, base=LTC, quote=USDT |
| 2400 | (['LTC'], ['USDT'], True, False, |
| 2401 | ['LTC/USDT']), |
| 2402 | # all markets, base=LTC, quote=USDT, NONEXISTENT |
| 2403 | (['LTC'], ['USDT', 'NONEXISTENT'], False, False, |
| 2404 | ['LTC/USDT', 'XLTCUSDT']), |
| 2405 | # all markets, base=LTC, quote=NONEXISTENT |
| 2406 | (['LTC'], ['NONEXISTENT'], False, False, |
| 2407 | []), |
| 2408 | ]) |
| 2409 | def test_get_markets(default_conf, mocker, markets, |
| 2410 | base_currencies, quote_currencies, pairs_only, active_only, |
| 2411 | expected_keys): |
| 2412 | mocker.patch.multiple('freqtrade.exchange.Exchange', |
| 2413 | _init_ccxt=MagicMock(return_value=MagicMock()), |
| 2414 | _load_async_markets=MagicMock(), |
| 2415 | validate_pairs=MagicMock(), |
| 2416 | validate_timeframes=MagicMock(), |
| 2417 | markets=PropertyMock(return_value=markets)) |
| 2418 | ex = Exchange(default_conf) |
| 2419 | pairs = ex.get_markets(base_currencies, quote_currencies, pairs_only, active_only) |
| 2420 | assert sorted(pairs.keys()) == sorted(expected_keys) |
| 2421 | |
| 2422 | |
| 2423 | def test_get_markets_error(default_conf, mocker): |
| 2424 | ex = get_patched_exchange(mocker, default_conf) |
| 2425 | mocker.patch('freqtrade.exchange.Exchange.markets', PropertyMock(return_value=None)) |
| 2426 | with pytest.raises(OperationalException, match="Markets were not loaded."): |
| 2427 | ex.get_markets('LTC', 'USDT', True, False) |
| 2428 | |
| 2429 | |
| 2430 | @pytest.mark.parametrize("exchange_name", EXCHANGES) |
| 2431 | def test_ohlcv_candle_limit(default_conf, mocker, exchange_name): |
| 2432 | exchange = get_patched_exchange(mocker, default_conf, id=exchange_name) |
| 2433 | timeframes = ('1m', '5m', '1h') |
| 2434 | expected = exchange._ft_has['ohlcv_candle_limit'] |
| 2435 | for timeframe in timeframes: |
| 2436 | if 'ohlcv_candle_limit_per_timeframe' in exchange._ft_has: |
| 2437 | expected = exchange._ft_has['ohlcv_candle_limit_per_timeframe'][timeframe] |
| 2438 | # This should only run for bittrex |
| 2439 | assert exchange_name == 'bittrex' |
| 2440 | assert exchange.ohlcv_candle_limit(timeframe) == expected |
| 2441 | |
| 2442 | |
| 2443 | def test_timeframe_to_minutes(): |
| 2444 | assert timeframe_to_minutes("5m") == 5 |
| 2445 | assert timeframe_to_minutes("10m") == 10 |
| 2446 | assert timeframe_to_minutes("1h") == 60 |
| 2447 | assert timeframe_to_minutes("1d") == 1440 |
| 2448 | |
| 2449 | |
| 2450 | def test_timeframe_to_seconds(): |
| 2451 | assert timeframe_to_seconds("5m") == 300 |
| 2452 | assert timeframe_to_seconds("10m") == 600 |
| 2453 | assert timeframe_to_seconds("1h") == 3600 |
| 2454 | assert timeframe_to_seconds("1d") == 86400 |
| 2455 | |
| 2456 | |
| 2457 | def test_timeframe_to_msecs(): |
| 2458 | assert timeframe_to_msecs("5m") == 300000 |
| 2459 | assert timeframe_to_msecs("10m") == 600000 |
| 2460 | assert timeframe_to_msecs("1h") == 3600000 |
| 2461 | assert timeframe_to_msecs("1d") == 86400000 |
| 2462 | |
| 2463 | |
| 2464 | def test_timeframe_to_prev_date(): |
| 2465 | # 2019-08-12 13:22:08 |
| 2466 | date = datetime.fromtimestamp(1565616128, tz=timezone.utc) |
| 2467 | |
| 2468 | tf_list = [ |
| 2469 | # 5m -> 2019-08-12 13:20:00 |
| 2470 | ("5m", datetime(2019, 8, 12, 13, 20, 0, tzinfo=timezone.utc)), |
| 2471 | # 10m -> 2019-08-12 13:20:00 |
| 2472 | ("10m", datetime(2019, 8, 12, 13, 20, 0, tzinfo=timezone.utc)), |
| 2473 | # 1h -> 2019-08-12 13:00:00 |
| 2474 | ("1h", datetime(2019, 8, 12, 13, 00, 0, tzinfo=timezone.utc)), |
| 2475 | # 2h -> 2019-08-12 12:00:00 |
| 2476 | ("2h", datetime(2019, 8, 12, 12, 00, 0, tzinfo=timezone.utc)), |
| 2477 | # 4h -> 2019-08-12 12:00:00 |
| 2478 | ("4h", datetime(2019, 8, 12, 12, 00, 0, tzinfo=timezone.utc)), |
| 2479 | # 1d -> 2019-08-12 00:00:00 |
| 2480 | ("1d", datetime(2019, 8, 12, 00, 00, 0, tzinfo=timezone.utc)), |
| 2481 | ] |
| 2482 | for interval, result in tf_list: |
| 2483 | assert timeframe_to_prev_date(interval, date) == result |
| 2484 | |
| 2485 | date = datetime.now(tz=timezone.utc) |
| 2486 | assert timeframe_to_prev_date("5m") < date |
| 2487 | # Does not round |
| 2488 | time = datetime(2019, 8, 12, 13, 20, 0, tzinfo=timezone.utc) |
| 2489 | assert timeframe_to_prev_date('5m', time) == time |
| 2490 | |
| 2491 | |
| 2492 | def test_timeframe_to_next_date(): |
| 2493 | # 2019-08-12 13:22:08 |
| 2494 | date = datetime.fromtimestamp(1565616128, tz=timezone.utc) |
| 2495 | tf_list = [ |
| 2496 | # 5m -> 2019-08-12 13:25:00 |
| 2497 | ("5m", datetime(2019, 8, 12, 13, 25, 0, tzinfo=timezone.utc)), |
| 2498 | # 10m -> 2019-08-12 13:30:00 |
| 2499 | ("10m", datetime(2019, 8, 12, 13, 30, 0, tzinfo=timezone.utc)), |
| 2500 | # 1h -> 2019-08-12 14:00:00 |
| 2501 | ("1h", datetime(2019, 8, 12, 14, 00, 0, tzinfo=timezone.utc)), |
| 2502 | # 2h -> 2019-08-12 14:00:00 |
| 2503 | ("2h", datetime(2019, 8, 12, 14, 00, 0, tzinfo=timezone.utc)), |
| 2504 | # 4h -> 2019-08-12 14:00:00 |
| 2505 | ("4h", datetime(2019, 8, 12, 16, 00, 0, tzinfo=timezone.utc)), |
| 2506 | # 1d -> 2019-08-13 00:00:00 |
| 2507 | ("1d", datetime(2019, 8, 13, 0, 0, 0, tzinfo=timezone.utc)), |
| 2508 | ] |
| 2509 | |
| 2510 | for interval, result in tf_list: |
| 2511 | assert timeframe_to_next_date(interval, date) == result |
| 2512 | |
| 2513 | date = datetime.now(tz=timezone.utc) |
| 2514 | assert timeframe_to_next_date("5m") > date |
| 2515 | |
| 2516 | date = datetime(2019, 8, 12, 13, 30, 0, tzinfo=timezone.utc) |
| 2517 | assert timeframe_to_next_date("5m", date) == date + timedelta(minutes=5) |
| 2518 | |
| 2519 | |
| 2520 | @pytest.mark.parametrize("market_symbol,base,quote,exchange,add_dict,expected_result", [ |
| 2521 | ("BTC/USDT", 'BTC', 'USDT', "binance", {}, True), |
| 2522 | ("USDT/BTC", 'USDT', 'BTC', "binance", {}, True), |
| 2523 | ("USDT/BTC", 'BTC', 'USDT', "binance", {}, False), # Reversed currencies |
| 2524 | ("BTCUSDT", 'BTC', 'USDT', "binance", {}, False), # No seperating / |
| 2525 | ("BTCUSDT", None, "USDT", "binance", {}, False), # |
| 2526 | ("USDT/BTC", "BTC", None, "binance", {}, False), |
| 2527 | ("BTCUSDT", "BTC", None, "binance", {}, False), |
| 2528 | ("BTC/USDT", "BTC", "USDT", "binance", {}, True), |
| 2529 | ("BTC/USDT", "USDT", "BTC", "binance", {}, False), # reversed currencies |
| 2530 | ("BTC/USDT", "BTC", "USD", "binance", {}, False), # Wrong quote currency |
| 2531 | ("BTC/", "BTC", 'UNK', "binance", {}, False), |
| 2532 | ("/USDT", 'UNK', 'USDT', "binance", {}, False), |
| 2533 | ("BTC/EUR", 'BTC', 'EUR', "kraken", {"darkpool": False}, True), |
| 2534 | ("EUR/BTC", 'EUR', 'BTC', "kraken", {"darkpool": False}, True), |
| 2535 | ("EUR/BTC", 'BTC', 'EUR', "kraken", {"darkpool": False}, False), # Reversed currencies |
| 2536 | ("BTC/EUR", 'BTC', 'USD', "kraken", {"darkpool": False}, False), # wrong quote currency |
| 2537 | ("BTC/EUR", 'BTC', 'EUR', "kraken", {"darkpool": True}, False), # no darkpools |
| 2538 | ("BTC/EUR.d", 'BTC', 'EUR', "kraken", {"darkpool": True}, False), # no darkpools |
| 2539 | ("BTC/USD", 'BTC', 'USD', "ftx", {'spot': True}, True), |
| 2540 | ("USD/BTC", 'USD', 'BTC', "ftx", {'spot': True}, True), |
| 2541 | ("BTC/USD", 'BTC', 'USDT', "ftx", {'spot': True}, False), # Wrong quote currency |
| 2542 | ("BTC/USD", 'USD', 'BTC', "ftx", {'spot': True}, False), # Reversed currencies |
| 2543 | ("BTC/USD", 'BTC', 'USD', "ftx", {'spot': False}, False), # Can only trade spot markets |
| 2544 | ("BTC-PERP", 'BTC', 'USD', "ftx", {'spot': False}, False), # Can only trade spot markets |
| 2545 | ]) |
| 2546 | def test_market_is_tradable(mocker, default_conf, market_symbol, base, |
| 2547 | quote, add_dict, exchange, expected_result) -> None: |
| 2548 | ex = get_patched_exchange(mocker, default_conf, id=exchange) |
| 2549 | market = { |
| 2550 | 'symbol': market_symbol, |
| 2551 | 'base': base, |
| 2552 | 'quote': quote, |
| 2553 | **(add_dict), |
| 2554 | } |
| 2555 | assert ex.market_is_tradable(market) == expected_result |
| 2556 | |
| 2557 | |
| 2558 | @pytest.mark.parametrize("market,expected_result", [ |
| 2559 | ({'symbol': 'ETH/BTC', 'active': True}, True), |
| 2560 | ({'symbol': 'ETH/BTC', 'active': False}, False), |
| 2561 | ({'symbol': 'ETH/BTC', }, True), |
| 2562 | ]) |
| 2563 | def test_market_is_active(market, expected_result) -> None: |
| 2564 | assert market_is_active(market) == expected_result |
| 2565 | |
| 2566 | |
| 2567 | @pytest.mark.parametrize("order,expected", [ |
| 2568 | ([{'fee'}], False), |
| 2569 | ({'fee': None}, False), |
| 2570 | ({'fee': {'currency': 'ETH/BTC'}}, False), |
| 2571 | ({'fee': {'currency': 'ETH/BTC', 'cost': None}}, False), |
| 2572 | ({'fee': {'currency': 'ETH/BTC', 'cost': 0.01}}, True), |
| 2573 | ]) |
| 2574 | def test_order_has_fee(order, expected) -> None: |
| 2575 | assert Exchange.order_has_fee(order) == expected |
| 2576 | |
| 2577 | |
| 2578 | @pytest.mark.parametrize("order,expected", [ |
| 2579 | ({'symbol': 'ETH/BTC', 'fee': {'currency': 'ETH', 'cost': 0.43}}, |
| 2580 | (0.43, 'ETH', 0.01)), |
| 2581 | ({'symbol': 'ETH/USDT', 'fee': {'currency': 'USDT', 'cost': 0.01}}, |
| 2582 | (0.01, 'USDT', 0.01)), |
| 2583 | ({'symbol': 'BTC/USDT', 'fee': {'currency': 'USDT', 'cost': 0.34, 'rate': 0.01}}, |
| 2584 | (0.34, 'USDT', 0.01)), |
| 2585 | ]) |
| 2586 | def test_extract_cost_curr_rate(mocker, default_conf, order, expected) -> None: |
| 2587 | mocker.patch('freqtrade.exchange.Exchange.calculate_fee_rate', MagicMock(return_value=0.01)) |
| 2588 | ex = get_patched_exchange(mocker, default_conf) |
| 2589 | assert ex.extract_cost_curr_rate(order) == expected |
| 2590 | |
| 2591 | |
| 2592 | @pytest.mark.parametrize("order,expected", [ |
| 2593 | # Using base-currency |
| 2594 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.05, |
| 2595 | 'fee': {'currency': 'ETH', 'cost': 0.004, 'rate': None}}, 0.1), |
| 2596 | ({'symbol': 'ETH/BTC', 'amount': 0.05, 'cost': 0.05, |
| 2597 | 'fee': {'currency': 'ETH', 'cost': 0.004, 'rate': None}}, 0.08), |
| 2598 | # Using quote currency |
| 2599 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.05, |
| 2600 | 'fee': {'currency': 'BTC', 'cost': 0.005}}, 0.1), |
| 2601 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.05, |
| 2602 | 'fee': {'currency': 'BTC', 'cost': 0.002, 'rate': None}}, 0.04), |
| 2603 | # Using foreign currency |
| 2604 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.05, |
| 2605 | 'fee': {'currency': 'NEO', 'cost': 0.0012}}, 0.001944), |
| 2606 | ({'symbol': 'ETH/BTC', 'amount': 2.21, 'cost': 0.02992561, |
| 2607 | 'fee': {'currency': 'NEO', 'cost': 0.00027452}}, 0.00074305), |
| 2608 | # Rate included in return - return as is |
| 2609 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.05, |
| 2610 | 'fee': {'currency': 'USDT', 'cost': 0.34, 'rate': 0.01}}, 0.01), |
| 2611 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.05, |
| 2612 | 'fee': {'currency': 'USDT', 'cost': 0.34, 'rate': 0.005}}, 0.005), |
| 2613 | # 0.1% filled - no costs (kraken - #3431) |
| 2614 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.0, |
| 2615 | 'fee': {'currency': 'BTC', 'cost': 0.0, 'rate': None}}, None), |
| 2616 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.0, |
| 2617 | 'fee': {'currency': 'ETH', 'cost': 0.0, 'rate': None}}, 0.0), |
| 2618 | ({'symbol': 'ETH/BTC', 'amount': 0.04, 'cost': 0.0, |
| 2619 | 'fee': {'currency': 'NEO', 'cost': 0.0, 'rate': None}}, None), |
| 2620 | ]) |
| 2621 | def test_calculate_fee_rate(mocker, default_conf, order, expected) -> None: |
| 2622 | mocker.patch('freqtrade.exchange.Exchange.fetch_ticker', return_value={'last': 0.081}) |
| 2623 | |
| 2624 | ex = get_patched_exchange(mocker, default_conf) |
| 2625 | assert ex.calculate_fee_rate(order) == expected |
| 2626 | |
| 2627 | |
| 2628 | @pytest.mark.parametrize('retrycount,max_retries,expected', [ |
| 2629 | (0, 3, 10), |
| 2630 | (1, 3, 5), |
| 2631 | (2, 3, 2), |
| 2632 | (3, 3, 1), |
| 2633 | (0, 1, 2), |
| 2634 | (1, 1, 1), |
| 2635 | (0, 4, 17), |
| 2636 | (1, 4, 10), |
| 2637 | (2, 4, 5), |
| 2638 | (3, 4, 2), |
| 2639 | (4, 4, 1), |
| 2640 | (0, 5, 26), |
| 2641 | (1, 5, 17), |
| 2642 | (2, 5, 10), |
| 2643 | (3, 5, 5), |
| 2644 | (4, 5, 2), |
| 2645 | (5, 5, 1), |
| 2646 | |
| 2647 | ]) |
| 2648 | def test_calculate_backoff(retrycount, max_retries, expected): |
| 2649 | assert calculate_backoff(retrycount, max_retries) == expected |