| 1 | from unittest.mock import MagicMock |
| 2 | |
| 3 | import pytest |
| 4 | |
| 5 | from freqtrade.persistence import Trade |
| 6 | from freqtrade.rpc.rpc import RPC |
| 7 | from freqtrade.strategy.interface import SellCheckTuple, SellType |
| 8 | from tests.conftest import get_patched_freqtradebot, patch_get_signal |
| 9 | |
| 10 | |
| 11 | def test_may_execute_sell_stoploss_on_exchange_multi(default_conf, ticker, fee, |
| 12 | limit_buy_order, mocker) -> None: |
| 13 | """ |
| 14 | Tests workflow of selling stoploss_on_exchange. |
| 15 | Sells |
| 16 | * first trade as stoploss |
| 17 | * 2nd trade is kept |
| 18 | * 3rd trade is sold via sell-signal |
| 19 | """ |
| 20 | default_conf['max_open_trades'] = 3 |
| 21 | default_conf['exchange']['name'] = 'binance' |
| 22 | |
| 23 | stoploss = { |
| 24 | 'id': 123, |
| 25 | 'info': {} |
| 26 | } |
| 27 | stoploss_order_open = { |
| 28 | "id": "123", |
| 29 | "timestamp": 1542707426845, |
| 30 | "datetime": "2018-11-20T09:50:26.845Z", |
| 31 | "lastTradeTimestamp": None, |
| 32 | "symbol": "BTC/USDT", |
| 33 | "type": "stop_loss_limit", |
| 34 | "side": "sell", |
| 35 | "price": 1.08801, |
| 36 | "amount": 90.99181074, |
| 37 | "cost": 0.0, |
| 38 | "average": 0.0, |
| 39 | "filled": 0.0, |
| 40 | "remaining": 0.0, |
| 41 | "status": "open", |
| 42 | "fee": None, |
| 43 | "trades": None |
| 44 | } |
| 45 | stoploss_order_closed = stoploss_order_open.copy() |
| 46 | stoploss_order_closed['status'] = 'closed' |
| 47 | stoploss_order_closed['filled'] = stoploss_order_closed['amount'] |
| 48 | |
| 49 | # Sell first trade based on stoploss, keep 2nd and 3rd trade open |
| 50 | stoploss_order_mock = MagicMock( |
| 51 | side_effect=[stoploss_order_closed, stoploss_order_open, stoploss_order_open]) |
| 52 | # Sell 3rd trade (not called for the first trade) |
| 53 | should_sell_mock = MagicMock(side_effect=[ |
| 54 | SellCheckTuple(sell_flag=False, sell_type=SellType.NONE), |
| 55 | SellCheckTuple(sell_flag=True, sell_type=SellType.SELL_SIGNAL)] |
| 56 | ) |
| 57 | cancel_order_mock = MagicMock() |
| 58 | mocker.patch('freqtrade.exchange.Binance.stoploss', stoploss) |
| 59 | mocker.patch.multiple( |
| 60 | 'freqtrade.exchange.Exchange', |
| 61 | fetch_ticker=ticker, |
| 62 | get_fee=fee, |
| 63 | amount_to_precision=lambda s, x, y: y, |
| 64 | price_to_precision=lambda s, x, y: y, |
| 65 | fetch_stoploss_order=stoploss_order_mock, |
| 66 | cancel_stoploss_order=cancel_order_mock, |
| 67 | ) |
| 68 | |
| 69 | mocker.patch.multiple( |
| 70 | 'freqtrade.freqtradebot.FreqtradeBot', |
| 71 | create_stoploss_order=MagicMock(return_value=True), |
| 72 | _notify_sell=MagicMock(), |
| 73 | ) |
| 74 | mocker.patch("freqtrade.strategy.interface.IStrategy.should_sell", should_sell_mock) |
| 75 | wallets_mock = mocker.patch("freqtrade.wallets.Wallets.update", MagicMock()) |
| 76 | mocker.patch("freqtrade.wallets.Wallets.get_free", MagicMock(return_value=1000)) |
| 77 | |
| 78 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 79 | freqtrade.strategy.order_types['stoploss_on_exchange'] = True |
| 80 | # Switch ordertype to market to close trade immediately |
| 81 | freqtrade.strategy.order_types['sell'] = 'market' |
| 82 | freqtrade.strategy.confirm_trade_entry = MagicMock(return_value=True) |
| 83 | freqtrade.strategy.confirm_trade_exit = MagicMock(return_value=True) |
| 84 | patch_get_signal(freqtrade) |
| 85 | |
| 86 | # Create some test data |
| 87 | freqtrade.enter_positions() |
| 88 | assert freqtrade.strategy.confirm_trade_entry.call_count == 3 |
| 89 | freqtrade.strategy.confirm_trade_entry.reset_mock() |
| 90 | assert freqtrade.strategy.confirm_trade_exit.call_count == 0 |
| 91 | wallets_mock.reset_mock() |
| 92 | |
| 93 | trades = Trade.query.all() |
| 94 | # Make sure stoploss-order is open and trade is bought (since we mock update_trade_state) |
| 95 | for trade in trades: |
| 96 | trade.stoploss_order_id = 3 |
| 97 | trade.open_order_id = None |
| 98 | |
| 99 | n = freqtrade.exit_positions(trades) |
| 100 | assert n == 2 |
| 101 | assert should_sell_mock.call_count == 2 |
| 102 | assert freqtrade.strategy.confirm_trade_entry.call_count == 0 |
| 103 | assert freqtrade.strategy.confirm_trade_exit.call_count == 1 |
| 104 | freqtrade.strategy.confirm_trade_exit.reset_mock() |
| 105 | |
| 106 | # Only order for 3rd trade needs to be cancelled |
| 107 | assert cancel_order_mock.call_count == 1 |
| 108 | # Wallets must be updated between stoploss cancellation and selling, and will be updated again |
| 109 | # during update_trade_state |
| 110 | assert wallets_mock.call_count == 4 |
| 111 | |
| 112 | trade = trades[0] |
| 113 | assert trade.sell_reason == SellType.STOPLOSS_ON_EXCHANGE.value |
| 114 | assert not trade.is_open |
| 115 | |
| 116 | trade = trades[1] |
| 117 | assert not trade.sell_reason |
| 118 | assert trade.is_open |
| 119 | |
| 120 | trade = trades[2] |
| 121 | assert trade.sell_reason == SellType.SELL_SIGNAL.value |
| 122 | assert not trade.is_open |
| 123 | |
| 124 | |
| 125 | @pytest.mark.parametrize("balance_ratio,result1", [ |
| 126 | (1, 200), |
| 127 | (0.99, 198), |
| 128 | ]) |
| 129 | def test_forcebuy_last_unlimited(default_conf, ticker, fee, limit_buy_order, mocker, balance_ratio, |
| 130 | result1) -> None: |
| 131 | """ |
| 132 | Tests workflow unlimited stake-amount |
| 133 | Buy 4 trades, forcebuy a 5th trade |
| 134 | Sell one trade, calculated stake amount should now be lower than before since |
| 135 | one trade was sold at a loss. |
| 136 | """ |
| 137 | default_conf['max_open_trades'] = 5 |
| 138 | default_conf['forcebuy_enable'] = True |
| 139 | default_conf['stake_amount'] = 'unlimited' |
| 140 | default_conf['tradable_balance_ratio'] = balance_ratio |
| 141 | default_conf['dry_run_wallet'] = 1000 |
| 142 | default_conf['exchange']['name'] = 'binance' |
| 143 | default_conf['telegram']['enabled'] = True |
| 144 | mocker.patch('freqtrade.rpc.telegram.Telegram', MagicMock()) |
| 145 | mocker.patch.multiple( |
| 146 | 'freqtrade.exchange.Exchange', |
| 147 | fetch_ticker=ticker, |
| 148 | get_fee=fee, |
| 149 | amount_to_precision=lambda s, x, y: y, |
| 150 | price_to_precision=lambda s, x, y: y, |
| 151 | ) |
| 152 | |
| 153 | mocker.patch.multiple( |
| 154 | 'freqtrade.freqtradebot.FreqtradeBot', |
| 155 | create_stoploss_order=MagicMock(return_value=True), |
| 156 | _notify_sell=MagicMock(), |
| 157 | ) |
| 158 | should_sell_mock = MagicMock(side_effect=[ |
| 159 | SellCheckTuple(sell_flag=False, sell_type=SellType.NONE), |
| 160 | SellCheckTuple(sell_flag=True, sell_type=SellType.SELL_SIGNAL), |
| 161 | SellCheckTuple(sell_flag=False, sell_type=SellType.NONE), |
| 162 | SellCheckTuple(sell_flag=False, sell_type=SellType.NONE), |
| 163 | SellCheckTuple(sell_flag=None, sell_type=SellType.NONE)] |
| 164 | ) |
| 165 | mocker.patch("freqtrade.strategy.interface.IStrategy.should_sell", should_sell_mock) |
| 166 | |
| 167 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 168 | rpc = RPC(freqtrade) |
| 169 | freqtrade.strategy.order_types['stoploss_on_exchange'] = True |
| 170 | # Switch ordertype to market to close trade immediately |
| 171 | freqtrade.strategy.order_types['sell'] = 'market' |
| 172 | patch_get_signal(freqtrade) |
| 173 | |
| 174 | # Create 4 trades |
| 175 | n = freqtrade.enter_positions() |
| 176 | assert n == 4 |
| 177 | |
| 178 | trades = Trade.query.all() |
| 179 | assert len(trades) == 4 |
| 180 | assert freqtrade.wallets.get_trade_stake_amount( |
| 181 | 'XRP/BTC', freqtrade.get_free_open_trades()) == result1 |
| 182 | |
| 183 | rpc._rpc_forcebuy('TKN/BTC', None) |
| 184 | |
| 185 | trades = Trade.query.all() |
| 186 | assert len(trades) == 5 |
| 187 | |
| 188 | for trade in trades: |
| 189 | assert trade.stake_amount == result1 |
| 190 | # Reset trade open order id's |
| 191 | trade.open_order_id = None |
| 192 | trades = Trade.get_open_trades() |
| 193 | assert len(trades) == 5 |
| 194 | bals = freqtrade.wallets.get_all_balances() |
| 195 | |
| 196 | n = freqtrade.exit_positions(trades) |
| 197 | assert n == 1 |
| 198 | trades = Trade.get_open_trades() |
| 199 | # One trade sold |
| 200 | assert len(trades) == 4 |
| 201 | # stake-amount should now be reduced, since one trade was sold at a loss. |
| 202 | assert freqtrade.wallets.get_trade_stake_amount( |
| 203 | 'XRP/BTC', freqtrade.get_free_open_trades()) < result1 |
| 204 | # Validate that balance of sold trade is not in dry-run balances anymore. |
| 205 | bals2 = freqtrade.wallets.get_all_balances() |
| 206 | assert bals != bals2 |
| 207 | assert len(bals) == 6 |
| 208 | assert len(bals2) == 5 |
| 209 | assert 'LTC' in bals |
| 210 | assert 'LTC' not in bals2 |