Skip to content

Commit

Permalink
Merge pull request #199 from lorcalhost/tabularize
Browse files Browse the repository at this point in the history
Bring tabularise to messages
  • Loading branch information
titulebolide authored Dec 16, 2021
2 parents e627a77 + 66e9349 commit 0b42041
Show file tree
Hide file tree
Showing 9 changed files with 245 additions and 41 deletions.
51 changes: 40 additions & 11 deletions btb_manager_telegram/buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import i18n
from btb_manager_telegram import BOUGHT, BUYING, SELLING, SOLD, logger, settings
from btb_manager_telegram.binance_api_utils import get_current_price
from btb_manager_telegram.table import tabularize
from btb_manager_telegram.utils import (
find_and_kill_binance_trade_bot_process,
format_float,
Expand Down Expand Up @@ -318,12 +319,26 @@ def current_ratios():
f"\n{i18n_format('ratios.last_update', update=last_update.strftime('%H:%M:%S %d/%m/%Y'))}\n\n"
f"{i18n_format('ratios.compared_ratios', coin=current_coin)}\n"
]
for coin in query:
m_list.append(
f"*{coin[1]}*:\n"
f"\t{i18n_format('ratios.bridge_value', value=coin[2], bridge=bridge)}\n"
f"\t{i18n_format('ratios.ratio', ratio=coin[3])}\n\n"
query = list(query)
max_length_ticker = max([len(i[1]) for i in query] + [4])

m_list.extend(
tabularize(
[
i18n_format("ratios.coin"),
i18n_format("ratios.price", bridge=bridge),
i18n_format("ratios.ratio"),
],
[
[c[1] for c in query],
[c[2] for c in query],
[c[3] for c in query],
],
[6, 12, 12],
align="left",
add_spaces=[True, True, False],
)
)

message = telegram_text_truncator(m_list)
con.close()
Expand Down Expand Up @@ -396,13 +411,27 @@ def next_coin():
query = cur.fetchall()
m_list = []
query = sorted(query, key=lambda x: x[3], reverse=True)
for coin in query:
percentage = round(coin[3] * 100, 2)
m_list.append(
f"*{coin[0]} \(`{format_float(percentage)}`%\)*\n"
f"\t{i18n_format('next_coin.current_price', price=round(coin[1], 8), coin=bridge)}\n"
f"\t{i18n_format('next_coin.target_price', price=round(coin[2], 8), coin=bridge)}\n\n"
query = list(query)

m_list.extend(
tabularize(
[
i18n_format("next_coin.coin"),
i18n_format("next_coin.percentage"),
i18n_format("next_coin.current_price"),
i18n_format("next_coin.target_price"),
],
[
[c[0] for c in query],
[str(round(c[3] * 100, 2)) for c in query],
[c[1] for c in query],
[c[2] for c in query],
],
[6, 7, 8, 8],
add_spaces=[True, True, False, False],
align=["center", "left", "left", "left"],
)
)

message = telegram_text_truncator(m_list)
con.close()
Expand Down
173 changes: 173 additions & 0 deletions btb_manager_telegram/table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
def scientific_notation(nb, maxchar):
nb_char = 6 if nb >= 0 else 7
operator = "{:." + str(maxchar - nb_char) + "E}"
ratio_srt = operator.format(nb).replace("E", "e")
return ratio_srt


def float_strip(nb, maxchar):
if maxchar < 8:
raise NotImplementedError(
"Tables does not support colum size of less than 8 for floats"
)
if nb == 0:
return 0
int_part = "-" if nb < 0 else ""
int_part += str(abs(int(nb)))
float_part = abs(nb) - abs(int(nb))
if len(int_part) > maxchar:
return scientific_notation(nb, maxchar)
if len(int_part) >= maxchar - 1:
return int_part
float_part = round(float_part, maxchar - len(int_part) - 1)
if abs(int(nb)) + float_part == 0:
return scientific_notation(nb, maxchar)
operator = "{:." + str(maxchar - len(int_part) - 1) + "f}"
float_part = operator.format(float_part)[1:].rstrip(".0")
return int_part + float_part


def string_srip(st, maxchar):
if maxchar < 1:
raise NotImplementedError(
"Tables does not support colum size of less than 1 for strings"
)
if len(st) > maxchar:
return st[: maxchar - 1] + "…"
return st


def strip_data(data, maxchar):
if type(data) in (float, int):
return float_strip(data, maxchar)
if type(data) == str:
return string_srip(data, maxchar)
else:
raise NotImplementedError(f"Cannot handle data of type {str(type(data))}")


def fun_data_to_exact_size(data, size, add_spaces=True, align="left"):
remove_size = 2 if add_spaces else 0
data = strip_data(data, size - remove_size)
nb_spaces = size - len(data)
if align == "center":
spaces_before = " " * (nb_spaces // 2)
spaces_after = " " * (nb_spaces - nb_spaces // 2)
elif align in ("left", "right"):
spaces_before = " " * int(add_spaces)
spaces_after = " " * (nb_spaces - int(add_spaces))
if align == "right":
spaces_after, spaces_before = spaces_before, spaces_after
else:
ValueError("'align' must be either 'center', 'left' or 'right'")
return spaces_before + data + spaces_after


def data_to_exact_size(
data, size, add_spaces=True, align="left", split_across_lines=False
):
if split_across_lines:
result = ""
data = data.split(" ")
index = 0
while index < len(data):
buffer = data[index]
index += 1
if index < len(data):
while len(buffer + data[index]) < size:
buffer += " " + data[index]
index += 1
if index >= len(data):
break
result += fun_data_to_exact_size(buffer, size, add_spaces, align)
result += "\n" if index < len(data) else ""
return result
else:
return fun_data_to_exact_size(data, size, add_spaces, align)


def fun_tabularize(col_head, col_data, col_size, add_spaces=True, align="left"):

dash = "−"

if type(align) is not list:
align = [align] * len(col_head)

if type(add_spaces) is not list:
add_spaces = [add_spaces] * len(col_head)

for i, size in enumerate(col_size):
if size == 0:
col_size[i] = (
max([len(str(data)) for data in col_data[i]] + [len(str(col_head[i]))])
+ 2
)

table = "```\n"

table += "┌"
for i, size in enumerate(col_size):
if i > 0:
table += "┬"
table += dash * size
table += "┐\n"

col_head = [
data_to_exact_size(
header, col_size[i], add_spaces[i], align[i], split_across_lines=True
).split("\n")
for i, header in enumerate(col_head)
]
header_height = max([len(header) for header in col_head])

for line in range(header_height):
table += "│"
for i, size in enumerate(col_size):
if i > 0:
table += "│"
if line < len(col_head[i]):
table += col_head[i][line]
else:
table += " " * size
table += "│\n"

table += "├"
for i, size in enumerate(col_size):
if i > 0:
table += "┼"
table += dash * size
table += "┤\n"

for j in range(len(col_data[0])):
table += "│"
for i, size in enumerate(col_size):
if i > 0:
table += "│"
table += data_to_exact_size(col_data[i][j], size, add_spaces[i], align[i])
table += "│\n"

table += "└"
for i, size in enumerate(col_size):
if i > 0:
table += "┴"
table += dash * size
table += "┘\n"

table += "```\n"

return table


def tabularize(col_head, col_data, col_size, add_spaces=True, align="left", nb_row=50):
tables = []
for i in range(len(col_data[0]) // nb_row + 1):
tables.append(
fun_tabularize(
col_head,
[col_d[i * nb_row : i * nb_row + nb_row] for col_d in col_data],
col_size,
add_spaces,
align,
)
)
return tables
8 changes: 4 additions & 4 deletions i18n/de.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ progress:
ratios:
last_update: "Letztes Update: `%{update}`"
compared_ratios: "*Coinverhältnisse im Vergleich zu %{coin} in absteigender Reihenfolge:*"
bridge_value: "- Preis: `%{value}` %{bridge}"
ratio: "- Verhältnis: `%{ratio}`"
price: "Preis %{bridge}"
ratio: "Verhältnis"
gen_error: "❌ Etwas ist schief gelaufen, derzeit können keine Verhältnisse erstellt werden."
db_error: "❌ Verhältnisse können nicht aus der Datenbank abgerufen werden."


next_coin:
current_price: "- Aktueller Preis: `%{price}` %{coin}"
target_price: "- Zielpreis: `%{price}` %{coin}"
current_price: "Aktueller Preis"
target_price: "Zielpreis"
error: "❌ Etwas ist schief gelaufen, derzeit kann der nächste Coin nicht ermittelt werden."
db_error: "❌ Nächster Coin kann nicht aus der Datenbank ermittelt werden."

Expand Down
11 changes: 7 additions & 4 deletions i18n/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,18 @@ progress:
ratios:
last_update: "Last update: `%{update}`"
compared_ratios: "*Coin ratios compared to %{coin} in decreasing order:*"
bridge_value: "- Price: `%{value}` %{bridge}"
ratio: "- Ratio: `%{ratio}`"
price: "Price %{bridge}"
ratio: "Ratio"
coin: "Coin"
gen_error: "❌ Something went wrong, unable to generate ratios at this time."
db_error: "❌ Unable to fetch ratios from database."


next_coin:
current_price: "- Current Price: `%{price}` %{coin}"
target_price: "- Target Price: `%{price}` %{coin}"
current_price: "Current price"
target_price: "Target price"
percentage: "%"
coin: "Coin"
error: "❌ Something went wrong, unable to generate next coin at this time."
db_error: "❌ Unable to fetch next coin from database."

Expand Down
8 changes: 4 additions & 4 deletions i18n/es.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ progress:
ratios:
last_update: "Última actualización: `%{update}`"
compared_ratios: "*Ratios comparados a %{coin} en orden decreciente:*"
bridge_value: "- Precio: `%{value}` %{bridge}"
ratio: "- Ratio: `%{ratio}`"
price: "Precio %{bridge}"
ratio: "Ratio"
gen_error: "❌ Algo salió mal, no fue posible generar los ratios en este momento."
db_error: "❌ No fue posible obtener los ratios desde la base de datos."


next_coin:
current_price: "- Precio actual: `%{price}` %{coin}"
target_price: "- Precio objetivo: `%{price}` %{coin}"
current_price: "Precio actual"
target_price: "Precio objetivo"
error: "❌ Algo salió mal, no se pudo generar la próxima moneda en este momento."
db_error: "❌ No se pudo obtener la información desde la base de datos."

Expand Down
8 changes: 4 additions & 4 deletions i18n/fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@ progress:
ratios:
last_update: "Dernière mise à jour: `%{update}`"
compared_ratios: "*Ratio de monnaies à %{coin} en ordre décroissant :*"
bridge_value: "- Prix: `%{value}` %{bridge}"
ratio: "- Ratio: `%{ratio}`"
price: "Prix %{bridge}"
ratio: "Ratio"
gen_error: "❌ Quelque chose s'est mal passé, impossible de générer les ratios."
db_error: "❌ Impossible de récuperer les ratios depuis la base de données."

next_coin:
current_price: "- Prix actuel: `%{price}` %{coin}"
target_price: "- Prix visé: `%{price}` %{coin}"
current_price: "Prix actuel"
target_price: "Prix cible"
error: "❌ Quelque chose s'est mal passé, impossible de déterminer la prochaine monnaie."
db_error: "❌ Impossible de récuperer les prochaines monnaies depuis la base de données."

Expand Down
8 changes: 4 additions & 4 deletions i18n/id.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ progress:
ratios:
last_update: "Tanggal pembaruan data: `%{update}`"
compared_ratios: "*Rasio koin lain dibandingkan %{coin}:*"
bridge_value: "- Harga: `%{value}` %{bridge}"
ratio: "- Rasio: `%{ratio}`"
price: "Harga %{bridge}"
ratio: "Rasio"
gen_error: "❌ Terjadi kesalahan, tidak dapat menampilkan rasio saat ini."
db_error: "❌ tidak dapat menampilkan rasio dari database."


next_coin:
current_price: "- Harga saat ini: `%{price}` %{coin}"
target_price: "- Target harga pembelian: `%{price}` %{coin}"
current_price: "Harga saat ini"
target_price: "Target harga pembelian"
error: "❌Terjadi kesalahan, tidak dapat menampilkan data koin selanjutnya."
db_error: "❌ tidak dapat menampilkan koin selanjutnya dari database."

Expand Down
11 changes: 5 additions & 6 deletions i18n/nl.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ progress:
ratios:
last_update: "Laatste update: `%{update}`"
compared_ratios: "*Muntverhoudingen vergeleken met %{coin} in afnemende volgorde:*"
bridge_value: "- Prijs: `%{value}` %{bridge}"
ratio: "- Ratio: `%{ratio}`"
price: "Prijs %{bridge}"
ratio: "Ratio"
gen_error: "❌ Er ging iets mis, niet in staat om op dit moment ratio's te genereren."
db_error: "❌ Kan geen ratio ophalen uit database."


next_coin:
current_price: "- Huidige prijs: `%{price}` %{coin}"
target_price: "- Doel prijs: `%{price}` %{coin}"
current_price: "Huidige prijs"
target_price: "Doel prijs"
error: "❌ Er is iets misgegaan, niet in staat om op dit moment de volgende munt te genereren."
db_error: "❌ Kan volgende munt niet ophalen uit database."

Expand Down Expand Up @@ -180,7 +180,7 @@ script:
no_script: "Er is geen aangepast script gevonden in *BTB-manager-telegram* 's `/config/custom_scripts.json` bestand."
no_config: "Kan bestand `custom_scripts.json` niet vinden binnen in de *BTB-manager-telegram* 's `config/` map."
select: "Selecteer één van uw aangepaste scripts om deze uit te voeren."

graph:
msg_existing_graphs: "Kies een grafiek of maak een nieuwe. Tip : de opbouw is 'MUNT1,MUNT2,MUNT3 AantalDagen'"
msg_no_graphs: "Gebruik de knop 'Nieuwe grafiek' om een nieuwe grafiek te maken."
Expand Down Expand Up @@ -237,4 +237,3 @@ keyboard:
next_coin: "🔀 Volgende munt"
graph: "📊 Grafiek"
new_graph: "➕ Nieuwe grafiek"

Loading

0 comments on commit 0b42041

Please sign in to comment.