Skip to content

Commit c5a95dc

Browse files
committed
refactor: reuse logic from get-status for get status-table
1 parent d7ccbfe commit c5a95dc

File tree

2 files changed

+67
-70
lines changed

2 files changed

+67
-70
lines changed

freqtrade/rpc/rpc.py

Lines changed: 65 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,14 @@
3939
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
4040
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
4141
from freqtrade.rpc.rpc_types import RPCSendMsg
42-
from freqtrade.util import decimals_per_coin, dt_now, dt_ts_def, format_date, shorten_date
42+
from freqtrade.util import (
43+
decimals_per_coin,
44+
dt_from_ts,
45+
dt_now,
46+
dt_ts_def,
47+
format_date,
48+
shorten_date,
49+
)
4350
from freqtrade.util.datetime_helpers import dt_humanize_delta
4451
from freqtrade.wallets import PositionWallet, Wallet
4552

@@ -272,6 +279,7 @@ def _rpc_trade_status(self, trade_ids: list[int] | None = None) -> list[dict[str
272279
stoploss_entry_dist=stoploss_entry_dist,
273280
stoploss_entry_dist_ratio=round(stoploss_entry_dist_ratio, 8),
274281
open_orders=oo_details,
282+
nr_of_successful_entries=trade.nr_of_successful_entries,
275283
)
276284
)
277285
results.append(trade_dict)
@@ -283,82 +291,70 @@ def _rpc_status_table(
283291
"""
284292
:return: list of trades, list of columns, sum of fiat profit
285293
"""
286-
trades: list[Trade] = Trade.get_open_trades()
287294
nonspot = self._config.get("trading_mode", TradingMode.SPOT) != TradingMode.SPOT
288-
if not trades:
295+
if not Trade.get_open_trades():
289296
raise RPCException("no active trade")
290-
else:
291-
trades_list = []
292-
fiat_profit_sum = nan
293-
for trade in trades:
294-
# calculate profit and send message to user
295-
try:
296-
current_rate = self._freqtrade.exchange.get_rate(
297-
trade.pair, side="exit", is_short=trade.is_short, refresh=False
298-
)
299-
except (PricingError, ExchangeError):
300-
current_rate = nan
301-
trade_profit = nan
302-
profit_str = f"{nan:.2%}"
303-
else:
304-
if trade.nr_of_successful_entries > 0:
305-
profit = trade.calculate_profit(current_rate)
306-
trade_profit = profit.profit_abs
307-
profit_str = f"{profit.profit_ratio:.2%}"
308-
else:
309-
trade_profit = 0.0
310-
profit_str = f"{0.0:.2f}"
311-
leverage = f"{trade.leverage:.3g}"
312-
direction_str = (
313-
(f"S {leverage}x" if trade.is_short else f"L {leverage}x") if nonspot else ""
297+
298+
trades_list = []
299+
fiat_profit_sum = nan
300+
for trade in self._rpc_trade_status():
301+
# Format profit as a string with the right sign
302+
profit = f"{trade['profit_ratio']:.2%}"
303+
fiat_profit = trade.get("profit_fiat", None)
304+
if isnan(fiat_profit):
305+
fiat_profit: float = trade.get("profit_abs", 0.0)
306+
if not isnan(fiat_profit):
307+
profit += f" ({fiat_profit:.2f})"
308+
fiat_profit_sum = (
309+
fiat_profit if isnan(fiat_profit_sum) else fiat_profit_sum + fiat_profit
314310
)
315-
if self._fiat_converter:
316-
fiat_profit = self._fiat_converter.convert_amount(
317-
trade_profit, stake_currency, fiat_display_currency
318-
)
319-
if not isnan(fiat_profit):
320-
profit_str += f" ({fiat_profit:.2f})"
321-
fiat_profit_sum = (
322-
fiat_profit if isnan(fiat_profit_sum) else fiat_profit_sum + fiat_profit
323-
)
324-
else:
325-
profit_str += f" ({trade_profit:.2f})"
326-
fiat_profit_sum = (
327-
trade_profit if isnan(fiat_profit_sum) else fiat_profit_sum + trade_profit
328-
)
329311

330-
active_attempt_side_symbols = [
331-
"*" if (oo and oo.ft_order_side == trade.entry_side) else "**"
332-
for oo in trade.open_orders
333-
]
312+
# Format the active order side symbols
313+
active_order_side = ""
314+
orders = trade.get("orders", [])
315+
if orders:
316+
active_order_side = ".".join(
317+
"*"
318+
if (o.get("ft_is_open") and o.get("ft_order_side") == trade.get("entry_side"))
319+
else "**"
320+
for o in orders
321+
if o.get("ft_is_open")
322+
)
334323

335-
# example: '*.**.**' trying to enter, exit and exit with 3 different orders
336-
active_attempt_side_symbols_str = ".".join(active_attempt_side_symbols)
324+
# Direction string for non-spot
325+
direction_str = ""
326+
if nonspot:
327+
leverage = trade.get("leverage", 1.0)
328+
direction_str = f"{'S' if trade.get('is_short') else 'L'} {leverage:.3g}x"
329+
330+
detail_trade = [
331+
f"{trade['trade_id']} {direction_str}",
332+
f"{trade['pair']}{active_order_side}",
333+
shorten_date(dt_humanize_delta(dt_from_ts(trade["open_timestamp"]))),
334+
profit,
335+
]
337336

338-
detail_trade = [
339-
f"{trade.id} {direction_str}",
340-
trade.pair + active_attempt_side_symbols_str,
341-
shorten_date(dt_humanize_delta(trade.open_date_utc)),
342-
profit_str,
343-
]
337+
# Add number of entries if position adjustment is enabled
338+
if self._config.get("position_adjustment_enable", False):
339+
max_entry_str = ""
340+
if self._config.get("max_entry_position_adjustment", -1) > 0:
341+
max_entry_str = f"/{self._config['max_entry_position_adjustment'] + 1}"
342+
filled_entries = trade.get("nr_of_successful_entries", 0)
343+
detail_trade.append(f"{filled_entries}{max_entry_str}")
344+
345+
trades_list.append(detail_trade)
346+
347+
columns = [
348+
"ID L/S" if nonspot else "ID",
349+
"Pair",
350+
"Since",
351+
f"Profit ({fiat_display_currency if self._fiat_converter else stake_currency})",
352+
]
344353

345-
if self._config.get("position_adjustment_enable", False):
346-
max_entry_str = ""
347-
if self._config.get("max_entry_position_adjustment", -1) > 0:
348-
max_entry_str = f"/{self._config['max_entry_position_adjustment'] + 1}"
349-
filled_entries = trade.nr_of_successful_entries
350-
detail_trade.append(f"{filled_entries}{max_entry_str}")
351-
trades_list.append(detail_trade)
352-
profitcol = "Profit"
353-
if self._fiat_converter:
354-
profitcol += " (" + fiat_display_currency + ")"
355-
else:
356-
profitcol += " (" + stake_currency + ")"
354+
if self._config.get("position_adjustment_enable", False):
355+
columns.append("# Entries")
357356

358-
columns = ["ID L/S" if nonspot else "ID", "Pair", "Since", profitcol]
359-
if self._config.get("position_adjustment_enable", False):
360-
columns.append("# Entries")
361-
return trades_list, columns, fiat_profit_sum
357+
return trades_list, columns, fiat_profit_sum
362358

363359
def _rpc_timeunit_profit(
364360
self,

tests/rpc/test_rpc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None:
9999
"precision_mode_price": 2,
100100
"contract_size": 1,
101101
"has_open_orders": False,
102+
"nr_of_successful_entries": ANY,
102103
"orders": [
103104
{
104105
"amount": 91.07468123,
@@ -255,7 +256,7 @@ def test_rpc_status_table(default_conf, ticker, fee, mocker) -> None:
255256
assert "Pair" in headers
256257
assert "now" == result[0][2]
257258
assert "ETH/BTC" in result[0][1]
258-
assert "0.00 (0.00)" == result[0][3]
259+
assert "0.00% (0.00)" == result[0][3]
259260
assert "0.00" == f"{fiat_profit_sum:.2f}"
260261

261262
mocker.patch(f"{EXMS}._dry_is_price_crossed", return_value=True)

0 commit comments

Comments
 (0)