Elffuss BraidHub

kikocis/freqtrade public

Merge pull request #4766 from freqtrade/fill_rpc

Add buy/sell fill messages to telegram
Changeset35f65cdea2904775d79fe15b99467205dbd08c0e5fb3562930a6f3082fe9e44d
AuthorMatthias <xmatthias@outlook.com> · 2021-04-20 20:39 +02:00
CommitterGitHub <noreply@github.com> · 2021-04-20 20:39 +02:00
Parentsc2b7079e6e91, 98a00ac2170c

Browse the files at this changeset

14 files changed

modified config_full.json.example +2 −0
@@ -163,7 +163,9 @@
163163 "warning": "on",
164164 "startup": "on",
165165 "buy": "on",
166+ "buy_fill": "on",
166167 "sell": "on",
168+ "sell_fill": "on",
167169 "buy_cancel": "on",
168170 "sell_cancel": "on"
169171 }
modified docs/telegram-usage.md +8 −1
@@ -82,12 +82,19 @@
8282 "buy": "silent",
8383 "sell": "on",
8484 "buy_cancel": "silent",
85- "sell_cancel": "on"
85+ "sell_cancel": "on",
86+ "buy_fill": "off",
87+ "sell_fill": "off"
8688 },
8789 "balance_dust_level": 0.01
8890 },
8991 ```
9092
93+`buy` notifications are sent when the order is placed, while `buy_fill` notifications are sent when the order is filled on the exchange.
94+`sell` notifications are sent when the order is placed, while `sell_fill` notifications are sent when the order is filled on the exchange.
95+`*_fill` notifications are off by default and must be explicitly enabled.
96+
97+
9198 `balance_dust_level` will define what the `/balance` command takes as "dust" - Currencies with a balance below this will be shown.
9299
93100 ## Create a custom keyboard (command shortcut buttons)
modified docs/webhook-config.md +46 −0
@@ -19,6 +19,11 @@
1919 "value1": "Cancelling Open Buy Order for {pair}",
2020 "value2": "limit {limit:8f}",
2121 "value3": "{stake_amount:8f} {stake_currency}"
22+ },
23+ "webhookbuyfill": {
24+ "value1": "Buy Order for {pair} filled",
25+ "value2": "at {open_rate:8f}",
26+ "value3": ""
2227 },
2328 "webhooksell": {
2429 "value1": "Selling {pair}",
@@ -30,6 +35,11 @@
3035 "value2": "limit {limit:8f}",
3136 "value3": "profit: {profit_amount:8f} {stake_currency} ({profit_ratio})"
3237 },
38+ "webhooksellfill": {
39+ "value1": "Sell Order for {pair} filled",
40+ "value2": "at {close_rate:8f}.",
41+ "value3": ""
42+ },
3343 "webhookstatus": {
3444 "value1": "Status: {status}",
3545 "value2": "",
@@ -91,6 +101,21 @@
91101 * `order_type`
92102 * `current_rate`
93103
104+### Webhookbuyfill
105+
106+The fields in `webhook.webhookbuyfill` are filled when the bot filled a buy order. Parameters are filled using string.format.
107+Possible parameters are:
108+
109+* `trade_id`
110+* `exchange`
111+* `pair`
112+* `open_rate`
113+* `amount`
114+* `open_date`
115+* `stake_amount`
116+* `stake_currency`
117+* `fiat_currency`
118+
94119 ### Webhooksell
95120
96121 The fields in `webhook.webhooksell` are filled when the bot sells a trade. Parameters are filled using string.format.
@@ -103,6 +128,27 @@
103128 * `limit`
104129 * `amount`
105130 * `open_rate`
131+* `profit_amount`
132+* `profit_ratio`
133+* `stake_currency`
134+* `fiat_currency`
135+* `sell_reason`
136+* `order_type`
137+* `open_date`
138+* `close_date`
139+
140+### Webhooksellfill
141+
142+The fields in `webhook.webhooksellfill` are filled when the bot fills a sell order (closes a Trae). Parameters are filled using string.format.
143+Possible parameters are:
144+
145+* `trade_id`
146+* `exchange`
147+* `pair`
148+* `gain`
149+* `close_rate`
150+* `amount`
151+* `open_rate`
106152 * `current_rate`
107153 * `profit_amount`
108154 * `profit_ratio`
modified freqtrade/constants.py +12 −2
@@ -246,14 +246,24 @@
246246 'balance_dust_level': {'type': 'number', 'minimum': 0.0},
247247 'notification_settings': {
248248 'type': 'object',
249+ 'default': {},
249250 'properties': {
250251 'status': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
251252 'warning': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
252253 'startup': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
253254 'buy': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
254- 'sell': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
255255 'buy_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
256- 'sell_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS}
256+ 'buy_fill': {'type': 'string',
257+ 'enum': TELEGRAM_SETTING_OPTIONS,
258+ 'default': 'off'
259+ },
260+ 'sell': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
261+ 'sell_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},
262+ 'sell_fill': {
263+ 'type': 'string',
264+ 'enum': TELEGRAM_SETTING_OPTIONS,
265+ 'default': 'off'
266+ },
257267 }
258268 }
259269 },
modified freqtrade/freqtradebot.py +31 −8
@@ -113,7 +113,7 @@
113113 via RPC about changes in the bot status.
114114 """
115115 self.rpc.send_msg({
116- 'type': RPCMessageType.STATUS_NOTIFICATION,
116+ 'type': RPCMessageType.STATUS,
117117 'status': msg
118118 })
119119
@@ -205,7 +205,7 @@
205205
206206 if len(open_trades) != 0:
207207 msg = {
208- 'type': RPCMessageType.WARNING_NOTIFICATION,
208+ 'type': RPCMessageType.WARNING,
209209 'status': f"{len(open_trades)} open trades active.\n\n"
210210 f"Handle these trades manually on {self.exchange.name}, "
211211 f"or '/start' the bot again and use '/stopbuy' "
@@ -634,7 +634,7 @@
634634 """
635635 msg = {
636636 'trade_id': trade.id,
637- 'type': RPCMessageType.BUY_NOTIFICATION,
637+ 'type': RPCMessageType.BUY,
638638 'exchange': self.exchange.name.capitalize(),
639639 'pair': trade.pair,
640640 'limit': trade.open_rate,
@@ -658,7 +658,7 @@
658658
659659 msg = {
660660 'trade_id': trade.id,
661- 'type': RPCMessageType.BUY_CANCEL_NOTIFICATION,
661+ 'type': RPCMessageType.BUY_CANCEL,
662662 'exchange': self.exchange.name.capitalize(),
663663 'pair': trade.pair,
664664 'limit': trade.open_rate,
@@ -675,6 +675,21 @@
675675 # Send the message
676676 self.rpc.send_msg(msg)
677677
678+ def _notify_buy_fill(self, trade: Trade) -> None:
679+ msg = {
680+ 'trade_id': trade.id,
681+ 'type': RPCMessageType.BUY_FILL,
682+ 'exchange': self.exchange.name.capitalize(),
683+ 'pair': trade.pair,
684+ 'open_rate': trade.open_rate,
685+ 'stake_amount': trade.stake_amount,
686+ 'stake_currency': self.config['stake_currency'],
687+ 'fiat_currency': self.config.get('fiat_display_currency', None),
688+ 'amount': trade.amount,
689+ 'open_date': trade.open_date,
690+ }
691+ self.rpc.send_msg(msg)
692+
678693 #
679694 # SELL / exit positions / close trades logic and methods
680695 #
@@ -1212,19 +1227,20 @@
12121227
12131228 return True
12141229
1215- def _notify_sell(self, trade: Trade, order_type: str) -> None:
1230+ def _notify_sell(self, trade: Trade, order_type: str, fill: bool = False) -> None:
12161231 """
12171232 Sends rpc notification when a sell occured.
12181233 """
12191234 profit_rate = trade.close_rate if trade.close_rate else trade.close_rate_requested
12201235 profit_trade = trade.calc_profit(rate=profit_rate)
12211236 # Use cached rates here - it was updated seconds ago.
1222- current_rate = self.get_sell_rate(trade.pair, False)
1237+ current_rate = self.get_sell_rate(trade.pair, False) if not fill else None
12231238 profit_ratio = trade.calc_profit_ratio(profit_rate)
12241239 gain = "profit" if profit_ratio > 0 else "loss"
12251240
12261241 msg = {
1227- 'type': RPCMessageType.SELL_NOTIFICATION,
1242+ 'type': (RPCMessageType.SELL_FILL if fill
1243+ else RPCMessageType.SELL),
12281244 'trade_id': trade.id,
12291245 'exchange': trade.exchange.capitalize(),
12301246 'pair': trade.pair,
@@ -1233,6 +1249,7 @@
12331249 'order_type': order_type,
12341250 'amount': trade.amount,
12351251 'open_rate': trade.open_rate,
1252+ 'close_rate': trade.close_rate,
12361253 'current_rate': current_rate,
12371254 'profit_amount': profit_trade,
12381255 'profit_ratio': profit_ratio,
@@ -1267,7 +1284,7 @@
12671284 gain = "profit" if profit_ratio > 0 else "loss"
12681285
12691286 msg = {
1270- 'type': RPCMessageType.SELL_CANCEL_NOTIFICATION,
1287+ 'type': RPCMessageType.SELL_CANCEL,
12711288 'trade_id': trade.id,
12721289 'exchange': trade.exchange.capitalize(),
12731290 'pair': trade.pair,
@@ -1344,9 +1361,15 @@
13441361
13451362 # Updating wallets when order is closed
13461363 if not trade.is_open:
1364+ if not stoploss_order and not trade.open_order_id:
1365+ self._notify_sell(trade, '', True)
13471366 self.protections.stop_per_pair(trade.pair)
13481367 self.protections.global_stop()
13491368 self.wallets.update()
1369+ elif not trade.open_order_id:
1370+ # Buy fill
1371+ self._notify_buy_fill(trade)
1372+
13501373 return False
13511374
13521375 def apply_fee_conditional(self, trade: Trade, trade_base_currency: str,
modified freqtrade/rpc/rpc.py +9 −7
@@ -31,13 +31,15 @@
3131
3232
3333 class RPCMessageType(Enum):
34- STATUS_NOTIFICATION = 'status'
35- WARNING_NOTIFICATION = 'warning'
36- STARTUP_NOTIFICATION = 'startup'
37- BUY_NOTIFICATION = 'buy'
38- BUY_CANCEL_NOTIFICATION = 'buy_cancel'
39- SELL_NOTIFICATION = 'sell'
40- SELL_CANCEL_NOTIFICATION = 'sell_cancel'
34+ STATUS = 'status'
35+ WARNING = 'warning'
36+ STARTUP = 'startup'
37+ BUY = 'buy'
38+ BUY_FILL = 'buy_fill'
39+ BUY_CANCEL = 'buy_cancel'
40+ SELL = 'sell'
41+ SELL_FILL = 'sell_fill'
42+ SELL_CANCEL = 'sell_cancel'
4143
4244 def __repr__(self):
4345 return self.value
modified freqtrade/rpc/rpc_manager.py +4 −4
@@ -67,7 +67,7 @@
6767 def startup_messages(self, config: Dict[str, Any], pairlist, protections) -> None:
6868 if config['dry_run']:
6969 self.send_msg({
70- 'type': RPCMessageType.WARNING_NOTIFICATION,
70+ 'type': RPCMessageType.WARNING,
7171 'status': 'Dry run is enabled. All trades are simulated.'
7272 })
7373 stake_currency = config['stake_currency']
@@ -79,7 +79,7 @@
7979 exchange_name = config['exchange']['name']
8080 strategy_name = config.get('strategy', '')
8181 self.send_msg({
82- 'type': RPCMessageType.STARTUP_NOTIFICATION,
82+ 'type': RPCMessageType.STARTUP,
8383 'status': f'*Exchange:* `{exchange_name}`\n'
8484 f'*Stake per trade:* `{stake_amount} {stake_currency}`\n'
8585 f'*Minimum ROI:* `{minimal_roi}`\n'
@@ -88,13 +88,13 @@
8888 f'*Strategy:* `{strategy_name}`'
8989 })
9090 self.send_msg({
91- 'type': RPCMessageType.STARTUP_NOTIFICATION,
91+ 'type': RPCMessageType.STARTUP,
9292 'status': f'Searching for {stake_currency} pairs to buy and sell '
9393 f'based on {pairlist.short_desc()}'
9494 })
9595 if len(protections.name_list) > 0:
9696 prots = '\n'.join([p for prot in protections.short_desc() for k, p in prot.items()])
9797 self.send_msg({
98- 'type': RPCMessageType.STARTUP_NOTIFICATION,
98+ 'type': RPCMessageType.STARTUP,
9999 'status': f'Using Protections: \n{prots}'
100100 })
modified freqtrade/rpc/telegram.py +65 −54
@@ -176,6 +176,53 @@
176176 """
177177 self._updater.stop()
178178
179+ def _format_buy_msg(self, msg: Dict[str, Any]) -> str:
180+ if self._rpc._fiat_converter:
181+ msg['stake_amount_fiat'] = self._rpc._fiat_converter.convert_amount(
182+ msg['stake_amount'], msg['stake_currency'], msg['fiat_currency'])
183+ else:
184+ msg['stake_amount_fiat'] = 0
185+
186+ message = (f"\N{LARGE BLUE CIRCLE} *{msg['exchange']}:* Buying {msg['pair']}"
187+ f" (#{msg['trade_id']})\n"
188+ f"*Amount:* `{msg['amount']:.8f}`\n"
189+ f"*Open Rate:* `{msg['limit']:.8f}`\n"
190+ f"*Current Rate:* `{msg['current_rate']:.8f}`\n"
191+ f"*Total:* `({round_coin_value(msg['stake_amount'], msg['stake_currency'])}")
192+
193+ if msg.get('fiat_currency', None):
194+ message += f", {round_coin_value(msg['stake_amount_fiat'], msg['fiat_currency'])}"
195+ message += ")`"
196+ return message
197+
198+ def _format_sell_msg(self, msg: Dict[str, Any]) -> str:
199+ msg['amount'] = round(msg['amount'], 8)
200+ msg['profit_percent'] = round(msg['profit_ratio'] * 100, 2)
201+ msg['duration'] = msg['close_date'].replace(
202+ microsecond=0) - msg['open_date'].replace(microsecond=0)
203+ msg['duration_min'] = msg['duration'].total_seconds() / 60
204+
205+ msg['emoji'] = self._get_sell_emoji(msg)
206+
207+ message = ("{emoji} *{exchange}:* Selling {pair} (#{trade_id})\n"
208+ "*Amount:* `{amount:.8f}`\n"
209+ "*Open Rate:* `{open_rate:.8f}`\n"
210+ "*Current Rate:* `{current_rate:.8f}`\n"
211+ "*Close Rate:* `{limit:.8f}`\n"
212+ "*Sell Reason:* `{sell_reason}`\n"
213+ "*Duration:* `{duration} ({duration_min:.1f} min)`\n"
214+ "*Profit:* `{profit_percent:.2f}%`").format(**msg)
215+
216+ # Check if all sell properties are available.
217+ # This might not be the case if the message origin is triggered by /forcesell
218+ if (all(prop in msg for prop in ['gain', 'fiat_currency', 'stake_currency'])
219+ and self._rpc._fiat_converter):
220+ msg['profit_fiat'] = self._rpc._fiat_converter.convert_amount(
221+ msg['profit_amount'], msg['stake_currency'], msg['fiat_currency'])
222+ message += (' `({gain}: {profit_amount:.8f} {stake_currency}'
223+ ' / {profit_fiat:.3f} {fiat_currency})`').format(**msg)
224+ return message
225+
179226 def send_msg(self, msg: Dict[str, Any]) -> None:
180227 """ Send a message to telegram channel """
181228
@@ -186,67 +233,31 @@
186233 # Notification disabled
187234 return
188235
189- if msg['type'] == RPCMessageType.BUY_NOTIFICATION:
190- if self._rpc._fiat_converter:
191- msg['stake_amount_fiat'] = self._rpc._fiat_converter.convert_amount(
192- msg['stake_amount'], msg['stake_currency'], msg['fiat_currency'])
193- else:
194- msg['stake_amount_fiat'] = 0
195-
196- message = (f"\N{LARGE BLUE CIRCLE} *{msg['exchange']}:* Buying {msg['pair']}"
197- f" (#{msg['trade_id']})\n"
198- f"*Amount:* `{msg['amount']:.8f}`\n"
199- f"*Open Rate:* `{msg['limit']:.8f}`\n"
200- f"*Current Rate:* `{msg['current_rate']:.8f}`\n"
201- f"*Total:* `({round_coin_value(msg['stake_amount'], msg['stake_currency'])}")
202-
203- if msg.get('fiat_currency', None):
204- message += f", {round_coin_value(msg['stake_amount_fiat'], msg['fiat_currency'])}"
205- message += ")`"
206-
207- elif msg['type'] == RPCMessageType.BUY_CANCEL_NOTIFICATION:
236+ if msg['type'] == RPCMessageType.BUY:
237+ message = self._format_buy_msg(msg)
238+
239+ elif msg['type'] in (RPCMessageType.BUY_CANCEL, RPCMessageType.SELL_CANCEL):
240+ msg['message_side'] = 'buy' if msg['type'] == RPCMessageType.BUY_CANCEL else 'sell'
208241 message = ("\N{WARNING SIGN} *{exchange}:* "
209- "Cancelling open buy Order for {pair} (#{trade_id}). "
242+ "Cancelling open {message_side} Order for {pair} (#{trade_id}). "
210243 "Reason: {reason}.".format(**msg))
211244
212- elif msg['type'] == RPCMessageType.SELL_NOTIFICATION:
213- msg['amount'] = round(msg['amount'], 8)
214- msg['profit_percent'] = round(msg['profit_ratio'] * 100, 2)
215- msg['duration'] = msg['close_date'].replace(
216- microsecond=0) - msg['open_date'].replace(microsecond=0)
217- msg['duration_min'] = msg['duration'].total_seconds() / 60
218-
219- msg['emoji'] = self._get_sell_emoji(msg)
220-
221- message = ("{emoji} *{exchange}:* Selling {pair} (#{trade_id})\n"
222- "*Amount:* `{amount:.8f}`\n"
223- "*Open Rate:* `{open_rate:.8f}`\n"
224- "*Current Rate:* `{current_rate:.8f}`\n"
225- "*Close Rate:* `{limit:.8f}`\n"
226- "*Sell Reason:* `{sell_reason}`\n"
227- "*Duration:* `{duration} ({duration_min:.1f} min)`\n"
228- "*Profit:* `{profit_percent:.2f}%`").format(**msg)
229-
230- # Check if all sell properties are available.
231- # This might not be the case if the message origin is triggered by /forcesell
232- if (all(prop in msg for prop in ['gain', 'fiat_currency', 'stake_currency'])
233- and self._rpc._fiat_converter):
234- msg['profit_fiat'] = self._rpc._fiat_converter.convert_amount(
235- msg['profit_amount'], msg['stake_currency'], msg['fiat_currency'])
236- message += (' `({gain}: {profit_amount:.8f} {stake_currency}'
237- ' / {profit_fiat:.3f} {fiat_currency})`').format(**msg)
238-
239- elif msg['type'] == RPCMessageType.SELL_CANCEL_NOTIFICATION:
240- message = ("\N{WARNING SIGN} *{exchange}:* Cancelling Open Sell Order "
241- "for {pair} (#{trade_id}). Reason: {reason}").format(**msg)
242-
243- elif msg['type'] == RPCMessageType.STATUS_NOTIFICATION:
245+ elif msg['type'] in (RPCMessageType.BUY_FILL, RPCMessageType.SELL_FILL):
246+ msg['message_side'] = 'Buy' if msg['type'] == RPCMessageType.BUY_FILL else 'Sell'
247+
248+ message = ("\N{LARGE CIRCLE} *{exchange}:* "
249+ "Buy order for {pair} (#{trade_id}) filled for {open_rate}.".format(**msg))
250+
251+ elif msg['type'] == RPCMessageType.SELL:
252+ message = self._format_sell_msg(msg)
253+
254+ elif msg['type'] == RPCMessageType.STATUS:
244255 message = '*Status:* `{status}`'.format(**msg)
245256
246- elif msg['type'] == RPCMessageType.WARNING_NOTIFICATION:
257+ elif msg['type'] == RPCMessageType.WARNING:
247258 message = '\N{WARNING SIGN} *Warning:* `{status}`'.format(**msg)
248259
249- elif msg['type'] == RPCMessageType.STARTUP_NOTIFICATION:
260+ elif msg['type'] == RPCMessageType.STARTUP:
250261 message = '{status}'.format(**msg)
251262
252263 else:
modified freqtrade/rpc/webhook.py +11 −7
@@ -45,17 +45,21 @@
4545 """ Send a message to telegram channel """
4646 try:
4747
48- if msg['type'] == RPCMessageType.BUY_NOTIFICATION:
48+ if msg['type'] == RPCMessageType.BUY:
4949 valuedict = self._config['webhook'].get('webhookbuy', None)
50- elif msg['type'] == RPCMessageType.BUY_CANCEL_NOTIFICATION:
50+ elif msg['type'] == RPCMessageType.BUY_CANCEL:
5151 valuedict = self._config['webhook'].get('webhookbuycancel', None)
52- elif msg['type'] == RPCMessageType.SELL_NOTIFICATION:
52+ elif msg['type'] == RPCMessageType.BUY_FILL:
53+ valuedict = self._config['webhook'].get('webhookbuyfill', None)
54+ elif msg['type'] == RPCMessageType.SELL:
5355 valuedict = self._config['webhook'].get('webhooksell', None)
54- elif msg['type'] == RPCMessageType.SELL_CANCEL_NOTIFICATION:
56+ elif msg['type'] == RPCMessageType.SELL_FILL:
57+ valuedict = self._config['webhook'].get('webhooksellfill', None)
58+ elif msg['type'] == RPCMessageType.SELL_CANCEL:
5559 valuedict = self._config['webhook'].get('webhooksellcancel', None)
56- elif msg['type'] in (RPCMessageType.STATUS_NOTIFICATION,
57- RPCMessageType.STARTUP_NOTIFICATION,
58- RPCMessageType.WARNING_NOTIFICATION):
60+ elif msg['type'] in (RPCMessageType.STATUS,
61+ RPCMessageType.STARTUP,
62+ RPCMessageType.WARNING):
5963 valuedict = self._config['webhook'].get('webhookstatus', None)
6064 else:
6165 raise NotImplementedError('Unknown message type: {}'.format(msg['type']))
modified tests/conftest.py +2 −1
@@ -314,7 +314,8 @@
314314 "telegram": {
315315 "enabled": True,
316316 "token": "token",
317- "chat_id": "0"
317+ "chat_id": "0",
318+ "notification_settings": {},
318319 },
319320 "datadir": str(testdatadir),
320321 "initial_state": "running",
modified tests/rpc/test_rpc_manager.py +3 −3
@@ -71,7 +71,7 @@
7171 freqtradebot = get_patched_freqtradebot(mocker, default_conf)
7272 rpc_manager = RPCManager(freqtradebot)
7373 rpc_manager.send_msg({
74- 'type': RPCMessageType.STATUS_NOTIFICATION,
74+ 'type': RPCMessageType.STATUS,
7575 'status': 'test'
7676 })
7777
@@ -86,7 +86,7 @@
8686 freqtradebot = get_patched_freqtradebot(mocker, default_conf)
8787 rpc_manager = RPCManager(freqtradebot)
8888 rpc_manager.send_msg({
89- 'type': RPCMessageType.STATUS_NOTIFICATION,
89+ 'type': RPCMessageType.STATUS,
9090 'status': 'test'
9191 })
9292
@@ -124,7 +124,7 @@
124124 rpc_manager = RPCManager(get_patched_freqtradebot(mocker, default_conf))
125125
126126 assert 'webhook' in [mod.name for mod in rpc_manager.registered_modules]
127- rpc_manager.send_msg({'type': RPCMessageType.STARTUP_NOTIFICATION,
127+ rpc_manager.send_msg({'type': RPCMessageType.STARTUP,
128128 'status': 'TestMessage'})
129129 assert log_has(
130130 "Message type 'startup' not implemented by handler webhook.",
modified tests/rpc/test_rpc_telegram.py +45 −23
@@ -683,10 +683,10 @@
683683 context.args = ["1"]
684684 telegram._forcesell(update=update, context=context)
685685
686- assert msg_mock.call_count == 3
686+ assert msg_mock.call_count == 4
687687 last_msg = msg_mock.call_args_list[-1][0][0]
688688 assert {
689- 'type': RPCMessageType.SELL_NOTIFICATION,
689+ 'type': RPCMessageType.SELL,
690690 'trade_id': 1,
691691 'exchange': 'Binance',
692692 'pair': 'ETH/BTC',
@@ -703,6 +703,7 @@
703703 'sell_reason': SellType.FORCE_SELL.value,
704704 'open_date': ANY,
705705 'close_date': ANY,
706+ 'close_rate': ANY,
706707 } == last_msg
707708
708709
@@ -743,11 +744,11 @@
743744 context.args = ["1"]
744745 telegram._forcesell(update=update, context=context)
745746
746- assert msg_mock.call_count == 3
747+ assert msg_mock.call_count == 4
747748
748749 last_msg = msg_mock.call_args_list[-1][0][0]
749750 assert {
750- 'type': RPCMessageType.SELL_NOTIFICATION,
751+ 'type': RPCMessageType.SELL,
751752 'trade_id': 1,
752753 'exchange': 'Binance',
753754 'pair': 'ETH/BTC',
@@ -764,6 +765,7 @@
764765 'sell_reason': SellType.FORCE_SELL.value,
765766 'open_date': ANY,
766767 'close_date': ANY,
768+ 'close_rate': ANY,
767769 } == last_msg
768770
769771
@@ -794,11 +796,11 @@
794796 context.args = ["all"]
795797 telegram._forcesell(update=update, context=context)
796798
797- # Called for each trade 3 times
798- assert msg_mock.call_count == 8
799- msg = msg_mock.call_args_list[1][0][0]
799+ # Called for each trade 4 times
800+ assert msg_mock.call_count == 12
801+ msg = msg_mock.call_args_list[2][0][0]
800802 assert {
801- 'type': RPCMessageType.SELL_NOTIFICATION,
803+ 'type': RPCMessageType.SELL,
802804 'trade_id': 1,
803805 'exchange': 'Binance',
804806 'pair': 'ETH/BTC',
@@ -815,6 +817,7 @@
815817 'sell_reason': SellType.FORCE_SELL.value,
816818 'open_date': ANY,
817819 'close_date': ANY,
820+ 'close_rate': ANY,
818821 } == msg
819822
820823
@@ -1195,7 +1198,7 @@
11951198 def test_send_msg_buy_notification(default_conf, mocker, caplog) -> None:
11961199
11971200 msg = {
1198- 'type': RPCMessageType.BUY_NOTIFICATION,
1201+ 'type': RPCMessageType.BUY,
11991202 'trade_id': 1,
12001203 'exchange': 'Binance',
12011204 'pair': 'ETH/BTC',
@@ -1240,7 +1243,7 @@
12401243 telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
12411244
12421245 telegram.send_msg({
1243- 'type': RPCMessageType.BUY_CANCEL_NOTIFICATION,
1246+ 'type': RPCMessageType.BUY_CANCEL,
12441247 'trade_id': 1,
12451248 'exchange': 'Binance',
12461249 'pair': 'ETH/BTC',
@@ -1251,6 +1254,25 @@
12511254 'Reason: cancelled due to timeout.')
12521255
12531256
1257+def test_send_msg_buy_fill_notification(default_conf, mocker) -> None:
1258+
1259+ default_conf['telegram']['notification_settings']['buy_fill'] = 'on'
1260+ telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
1261+
1262+ telegram.send_msg({
1263+ 'type': RPCMessageType.BUY_FILL,
1264+ 'trade_id': 1,
1265+ 'exchange': 'Binance',
1266+ 'pair': 'ETH/USDT',
1267+ 'open_rate': 200,
1268+ 'stake_amount': 100,
1269+ 'amount': 0.5,
1270+ 'open_date': arrow.utcnow().datetime
1271+ })
1272+ assert (msg_mock.call_args[0][0] == '\N{LARGE CIRCLE} *Binance:* '
1273+ 'Buy order for ETH/USDT (#1) filled for 200.')
1274+
1275+
12541276 def test_send_msg_sell_notification(default_conf, mocker) -> None:
12551277
12561278 telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
@@ -1258,7 +1280,7 @@
12581280 old_convamount = telegram._rpc._fiat_converter.convert_amount
12591281 telegram._rpc._fiat_converter.convert_amount = lambda a, b, c: -24.812
12601282 telegram.send_msg({
1261- 'type': RPCMessageType.SELL_NOTIFICATION,
1283+ 'type': RPCMessageType.SELL,
12621284 'trade_id': 1,
12631285 'exchange': 'Binance',
12641286 'pair': 'KEY/ETH',
@@ -1288,7 +1310,7 @@
12881310
12891311 msg_mock.reset_mock()
12901312 telegram.send_msg({
1291- 'type': RPCMessageType.SELL_NOTIFICATION,
1313+ 'type': RPCMessageType.SELL,
12921314 'trade_id': 1,
12931315 'exchange': 'Binance',
12941316 'pair': 'KEY/ETH',
@@ -1325,27 +1347,27 @@
13251347 old_convamount = telegram._rpc._fiat_converter.convert_amount
13261348 telegram._rpc._fiat_converter.convert_amount = lambda a, b, c: -24.812
13271349 telegram.send_msg({
1328- 'type': RPCMessageType.SELL_CANCEL_NOTIFICATION,
1350+ 'type': RPCMessageType.SELL_CANCEL,
13291351 'trade_id': 1,
13301352 'exchange': 'Binance',
13311353 'pair': 'KEY/ETH',
13321354 'reason': 'Cancelled on exchange'
13331355 })
13341356 assert msg_mock.call_args[0][0] \
1335- == ('\N{WARNING SIGN} *Binance:* Cancelling Open Sell Order for KEY/ETH (#1).'
1336- ' Reason: Cancelled on exchange')
1357+ == ('\N{WARNING SIGN} *Binance:* Cancelling open sell Order for KEY/ETH (#1).'
1358+ ' Reason: Cancelled on exchange.')
13371359
13381360 msg_mock.reset_mock()
13391361 telegram.send_msg({
1340- 'type': RPCMessageType.SELL_CANCEL_NOTIFICATION,
1362+ 'type': RPCMessageType.SELL_CANCEL,
13411363 'trade_id': 1,
13421364 'exchange': 'Binance',
13431365 'pair': 'KEY/ETH',
13441366 'reason': 'timeout'
13451367 })
13461368 assert msg_mock.call_args[0][0] \
1347- == ('\N{WARNING SIGN} *Binance:* Cancelling Open Sell Order for KEY/ETH (#1).'
1348- ' Reason: timeout')
1369+ == ('\N{WARNING SIGN} *Binance:* Cancelling open sell Order for KEY/ETH (#1).'
1370+ ' Reason: timeout.')
13491371 # Reset singleton function to avoid random breaks
13501372 telegram._rpc._fiat_converter.convert_amount = old_convamount
13511373
@@ -1354,7 +1376,7 @@
13541376
13551377 telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
13561378 telegram.send_msg({
1357- 'type': RPCMessageType.STATUS_NOTIFICATION,
1379+ 'type': RPCMessageType.STATUS,
13581380 'status': 'running'
13591381 })
13601382 assert msg_mock.call_args[0][0] == '*Status:* `running`'
@@ -1363,7 +1385,7 @@
13631385 def test_warning_notification(default_conf, mocker) -> None:
13641386 telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
13651387 telegram.send_msg({
1366- 'type': RPCMessageType.WARNING_NOTIFICATION,
1388+ 'type': RPCMessageType.WARNING,
13671389 'status': 'message'
13681390 })
13691391 assert msg_mock.call_args[0][0] == '\N{WARNING SIGN} *Warning:* `message`'
@@ -1372,7 +1394,7 @@
13721394 def test_startup_notification(default_conf, mocker) -> None:
13731395 telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
13741396 telegram.send_msg({
1375- 'type': RPCMessageType.STARTUP_NOTIFICATION,
1397+ 'type': RPCMessageType.STARTUP,
13761398 'status': '*Custom:* `Hello World`'
13771399 })
13781400 assert msg_mock.call_args[0][0] == '*Custom:* `Hello World`'
@@ -1391,7 +1413,7 @@
13911413 telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
13921414
13931415 telegram.send_msg({
1394- 'type': RPCMessageType.BUY_NOTIFICATION,
1416+ 'type': RPCMessageType.BUY,
13951417 'trade_id': 1,
13961418 'exchange': 'Binance',
13971419 'pair': 'ETH/BTC',
@@ -1417,7 +1439,7 @@
14171439 telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf)
14181440
14191441 telegram.send_msg({
1420- 'type': RPCMessageType.SELL_NOTIFICATION,
1442+ 'type': RPCMessageType.SELL,
14211443 'trade_id': 1,
14221444 'exchange': 'Binance',
14231445 'pair': 'KEY/ETH',
modified tests/rpc/test_rpc_webhook.py +72 −17
@@ -25,6 +25,11 @@
2525 "value2": "limit {limit:8f}",
2626 "value3": "{stake_amount:8f} {stake_currency}"
2727 },
28+ "webhookbuyfill": {
29+ "value1": "Buy Order for {pair} filled",
30+ "value2": "at {open_rate:8f}",
31+ "value3": "{stake_amount:8f} {stake_currency}"
32+ },
2833 "webhooksell": {
2934 "value1": "Selling {pair}",
3035 "value2": "limit {limit:8f}",
@@ -35,6 +40,11 @@
3540 "value2": "limit {limit:8f}",
3641 "value3": "profit: {profit_amount:8f} {stake_currency} ({profit_ratio})"
3742 },
43+ "webhooksellfill": {
44+ "value1": "Sell Order for {pair} filled",
45+ "value2": "at {close_rate:8f}",
46+ "value3": ""
47+ },
3848 "webhookstatus": {
3949 "value1": "Status: {status}",
4050 "value2": "",
@@ -49,7 +59,7 @@
4959 assert webhook._config == default_conf
5060
5161
52-def test_send_msg(default_conf, mocker):
62+def test_send_msg_webhook(default_conf, mocker):
5363 default_conf["webhook"] = get_webhook_dict()
5464 msg_mock = MagicMock()
5565 mocker.patch("freqtrade.rpc.webhook.Webhook._send_msg", msg_mock)
@@ -58,7 +68,7 @@
5868 msg_mock = MagicMock()
5969 mocker.patch("freqtrade.rpc.webhook.Webhook._send_msg", msg_mock)
6070 msg = {
61- 'type': RPCMessageType.BUY_NOTIFICATION,
71+ 'type': RPCMessageType.BUY,
6272 'exchange': 'Binance',
6373 'pair': 'ETH/BTC',
6474 'limit': 0.005,
@@ -76,10 +86,10 @@
7686 assert (msg_mock.call_args[0][0]["value3"] ==
7787 default_conf["webhook"]["webhookbuy"]["value3"].format(**msg))
7888 # Test buy cancel
79- msg_mock = MagicMock()
80- mocker.patch("freqtrade.rpc.webhook.Webhook._send_msg", msg_mock)
89+ msg_mock.reset_mock()
90+
8191 msg = {
82- 'type': RPCMessageType.BUY_CANCEL_NOTIFICATION,
92+ 'type': RPCMessageType.BUY_CANCEL,
8393 'exchange': 'Binance',
8494 'pair': 'ETH/BTC',
8595 'limit': 0.005,
@@ -96,11 +106,31 @@
96106 default_conf["webhook"]["webhookbuycancel"]["value2"].format(**msg))
97107 assert (msg_mock.call_args[0][0]["value3"] ==
98108 default_conf["webhook"]["webhookbuycancel"]["value3"].format(**msg))
109+ # Test buy fill
110+ msg_mock.reset_mock()
111+
112+ msg = {
113+ 'type': RPCMessageType.BUY_FILL,
114+ 'exchange': 'Binance',
115+ 'pair': 'ETH/BTC',
116+ 'open_rate': 0.005,
117+ 'stake_amount': 0.8,
118+ 'stake_amount_fiat': 500,
119+ 'stake_currency': 'BTC',
120+ 'fiat_currency': 'EUR'
121+ }
122+ webhook.send_msg(msg=msg)
123+ assert msg_mock.call_count == 1
124+ assert (msg_mock.call_args[0][0]["value1"] ==
125+ default_conf["webhook"]["webhookbuyfill"]["value1"].format(**msg))
126+ assert (msg_mock.call_args[0][0]["value2"] ==
127+ default_conf["webhook"]["webhookbuyfill"]["value2"].format(**msg))
128+ assert (msg_mock.call_args[0][0]["value3"] ==
129+ default_conf["webhook"]["webhookbuyfill"]["value3"].format(**msg))
99130 # Test sell
100- msg_mock = MagicMock()
101- mocker.patch("freqtrade.rpc.webhook.Webhook._send_msg", msg_mock)
131+ msg_mock.reset_mock()
102132 msg = {
103- 'type': RPCMessageType.SELL_NOTIFICATION,
133+ 'type': RPCMessageType.SELL,
104134 'exchange': 'Binance',
105135 'pair': 'ETH/BTC',
106136 'gain': "profit",
@@ -123,10 +153,9 @@
123153 assert (msg_mock.call_args[0][0]["value3"] ==
124154 default_conf["webhook"]["webhooksell"]["value3"].format(**msg))
125155 # Test sell cancel
126- msg_mock = MagicMock()
127- mocker.patch("freqtrade.rpc.webhook.Webhook._send_msg", msg_mock)
156+ msg_mock.reset_mock()
128157 msg = {
129- 'type': RPCMessageType.SELL_CANCEL_NOTIFICATION,
158+ 'type': RPCMessageType.SELL_CANCEL,
130159 'exchange': 'Binance',
131160 'pair': 'ETH/BTC',
132161 'gain': "profit",
@@ -148,9 +177,35 @@
148177 default_conf["webhook"]["webhooksellcancel"]["value2"].format(**msg))
149178 assert (msg_mock.call_args[0][0]["value3"] ==
150179 default_conf["webhook"]["webhooksellcancel"]["value3"].format(**msg))
151- for msgtype in [RPCMessageType.STATUS_NOTIFICATION,
152- RPCMessageType.WARNING_NOTIFICATION,
153- RPCMessageType.STARTUP_NOTIFICATION]:
180+ # Test Sell fill
181+ msg_mock.reset_mock()
182+ msg = {
183+ 'type': RPCMessageType.SELL_FILL,
184+ 'exchange': 'Binance',
185+ 'pair': 'ETH/BTC',
186+ 'gain': "profit",
187+ 'close_rate': 0.005,
188+ 'amount': 0.8,
189+ 'order_type': 'limit',
190+ 'open_rate': 0.004,
191+ 'current_rate': 0.005,
192+ 'profit_amount': 0.001,
193+ 'profit_ratio': 0.20,
194+ 'stake_currency': 'BTC',
195+ 'sell_reason': SellType.STOP_LOSS.value
196+ }
197+ webhook.send_msg(msg=msg)
198+ assert msg_mock.call_count == 1
199+ assert (msg_mock.call_args[0][0]["value1"] ==
200+ default_conf["webhook"]["webhooksellfill"]["value1"].format(**msg))
201+ assert (msg_mock.call_args[0][0]["value2"] ==
202+ default_conf["webhook"]["webhooksellfill"]["value2"].format(**msg))
203+ assert (msg_mock.call_args[0][0]["value3"] ==
204+ default_conf["webhook"]["webhooksellfill"]["value3"].format(**msg))
205+
206+ for msgtype in [RPCMessageType.STATUS,
207+ RPCMessageType.WARNING,
208+ RPCMessageType.STARTUP]:
154209 # Test notification
155210 msg = {
156211 'type': msgtype,
@@ -173,8 +228,8 @@
173228 del default_conf["webhook"]["webhookbuy"]
174229
175230 webhook = Webhook(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf)
176- webhook.send_msg({'type': RPCMessageType.BUY_NOTIFICATION})
177- assert log_has(f"Message type '{RPCMessageType.BUY_NOTIFICATION}' not configured for webhooks",
231+ webhook.send_msg({'type': RPCMessageType.BUY})
232+ assert log_has(f"Message type '{RPCMessageType.BUY}' not configured for webhooks",
178233 caplog)
179234
180235 default_conf["webhook"] = get_webhook_dict()
@@ -183,7 +238,7 @@
183238 mocker.patch("freqtrade.rpc.webhook.Webhook._send_msg", msg_mock)
184239 webhook = Webhook(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf)
185240 msg = {
186- 'type': RPCMessageType.BUY_NOTIFICATION,
241+ 'type': RPCMessageType.BUY,
187242 'exchange': 'Binance',
188243 'pair': 'ETH/BTC',
189244 'limit': 0.005,
modified tests/test_freqtradebot.py +18 −11
@@ -1710,6 +1710,7 @@
17101710 open_rate=0.01,
17111711 open_date=arrow.utcnow().datetime,
17121712 amount=11,
1713+ exchange="binance",
17131714 )
17141715 assert not freqtrade.update_trade_state(trade, None)
17151716 assert log_has_re(r'Orderid for trade .* is empty.', caplog)
@@ -2319,7 +2320,7 @@
23192320 # note this is for a partially-complete buy order
23202321 freqtrade.check_handle_timedout()
23212322 assert cancel_order_mock.call_count == 1
2322- assert rpc_mock.call_count == 1
2323+ assert rpc_mock.call_count == 2
23232324 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all()
23242325 assert len(trades) == 1
23252326 assert trades[0].amount == 23.0
@@ -2354,7 +2355,7 @@
23542355 assert log_has_re(r"Applying fee on amount for Trade.*", caplog)
23552356
23562357 assert cancel_order_mock.call_count == 1
2357- assert rpc_mock.call_count == 1
2358+ assert rpc_mock.call_count == 2
23582359 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all()
23592360 assert len(trades) == 1
23602361 # Verify that trade has been updated
@@ -2394,7 +2395,7 @@
23942395 assert log_has_re(r"Could not update trade amount: .*", caplog)
23952396
23962397 assert cancel_order_mock.call_count == 1
2397- assert rpc_mock.call_count == 1
2398+ assert rpc_mock.call_count == 2
23982399 trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all()
23992400 assert len(trades) == 1
24002401 # Verify that trade has been updated
@@ -2623,7 +2624,7 @@
26232624 last_msg = rpc_mock.call_args_list[-1][0][0]
26242625 assert {
26252626 'trade_id': 1,
2626- 'type': RPCMessageType.SELL_NOTIFICATION,
2627+ 'type': RPCMessageType.SELL,
26272628 'exchange': 'Binance',
26282629 'pair': 'ETH/BTC',
26292630 'gain': 'profit',
@@ -2639,6 +2640,7 @@
26392640 'sell_reason': SellType.ROI.value,
26402641 'open_date': ANY,
26412642 'close_date': ANY,
2643+ 'close_rate': ANY,
26422644 } == last_msg
26432645
26442646
@@ -2672,7 +2674,7 @@
26722674 assert rpc_mock.call_count == 2
26732675 last_msg = rpc_mock.call_args_list[-1][0][0]
26742676 assert {
2675- 'type': RPCMessageType.SELL_NOTIFICATION,
2677+ 'type': RPCMessageType.SELL,
26762678 'trade_id': 1,
26772679 'exchange': 'Binance',
26782680 'pair': 'ETH/BTC',
@@ -2689,6 +2691,7 @@
26892691 'sell_reason': SellType.STOP_LOSS.value,
26902692 'open_date': ANY,
26912693 'close_date': ANY,
2694+ 'close_rate': ANY,
26922695 } == last_msg
26932696
26942697
@@ -2729,7 +2732,7 @@
27292732 last_msg = rpc_mock.call_args_list[-1][0][0]
27302733
27312734 assert {
2732- 'type': RPCMessageType.SELL_NOTIFICATION,
2735+ 'type': RPCMessageType.SELL,
27332736 'trade_id': 1,
27342737 'exchange': 'Binance',
27352738 'pair': 'ETH/BTC',
@@ -2746,7 +2749,7 @@
27462749 'sell_reason': SellType.STOP_LOSS.value,
27472750 'open_date': ANY,
27482751 'close_date': ANY,
2749-
2752+ 'close_rate': ANY,
27502753 } == last_msg
27512754
27522755
@@ -2830,7 +2833,7 @@
28302833 trade = Trade.query.first()
28312834 assert trade
28322835 assert cancel_order.call_count == 1
2833- assert rpc_mock.call_count == 2
2836+ assert rpc_mock.call_count == 3
28342837
28352838
28362839 def test_may_execute_sell_after_stoploss_on_exchange_hit(default_conf, ticker, fee,
@@ -2898,7 +2901,10 @@
28982901 assert trade.stoploss_order_id is None
28992902 assert trade.is_open is False
29002903 assert trade.sell_reason == SellType.STOPLOSS_ON_EXCHANGE.value
2901- assert rpc_mock.call_count == 2
2904+ assert rpc_mock.call_count == 3
2905+ assert rpc_mock.call_args_list[0][0][0]['type'] == RPCMessageType.BUY
2906+ assert rpc_mock.call_args_list[1][0][0]['type'] == RPCMessageType.BUY_FILL
2907+ assert rpc_mock.call_args_list[2][0][0]['type'] == RPCMessageType.SELL
29022908
29032909
29042910 def test_execute_sell_market_order(default_conf, ticker, fee,
@@ -2932,10 +2938,10 @@
29322938 assert not trade.is_open
29332939 assert trade.close_profit == 0.0620716
29342940
2935- assert rpc_mock.call_count == 2
2941+ assert rpc_mock.call_count == 3
29362942 last_msg = rpc_mock.call_args_list[-1][0][0]
29372943 assert {
2938- 'type': RPCMessageType.SELL_NOTIFICATION,
2944+ 'type': RPCMessageType.SELL,
29392945 'trade_id': 1,
29402946 'exchange': 'Binance',
29412947 'pair': 'ETH/BTC',
@@ -2952,6 +2958,7 @@
29522958 'sell_reason': SellType.ROI.value,
29532959 'open_date': ANY,
29542960 'close_date': ANY,
2961+ 'close_rate': ANY,
29552962
29562963 } == last_msg
29572964