-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPnLBot.py
More file actions
1968 lines (1706 loc) · 74.4 KB
/
PnLBot.py
File metadata and controls
1968 lines (1706 loc) · 74.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import atexit
import datetime
import hashlib
import hmac
import json
import os
import threading
import time
from dataclasses import dataclass, field
from threading import Lock
from typing import Callable, Dict, List, Optional, Tuple, Union
import re
import html
import sys
import unicodedata
import psutil
import pytz
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from lunar_vn import solar_to_lunar, can_chi, holidays
OPENAI_COSTS_URL = "https://api.openai.com/v1/organization/costs"
OPENAI_USAGE_URL = "https://api.openai.com/v1/organization/usage/completions"
IQAIR_API_URL = "https://api.airvisual.com/v2/nearest_city"
ASCII_STARTUP_BANNER = (
"```\n"
"ʕ•ᴥ•ʔ\n"
" short it!\n"
"```"
)
STATE_FILE_PATH = "pnl-bot-state.json"
TODO_FILE_PATH = "pnl-bot-todo-db.txt"
TELEGRAM_API_URL = "https://api.telegram.org"
TELEGRAM_MAX_MESSAGE = 4096
OPENAI_REFRESH_SECONDS = 300
EVN_SPC_OUTAGE_URL = "https://www.cskh.evnspc.vn/TraCuu/GetThongTinLichNgungGiamCungCapDien"
# Cache outages for some time to avoid frequent calls
POWER_OUTAGE_REFRESH_SECONDS = 3600
TELEGRAM_POLL_TIMEOUT = 30
def env_str(name: str, default: str) -> str:
value = os.getenv(name)
return value if value not in (None, "") else default
def env_int(name: str, default: int) -> int:
value = os.getenv(name)
if value in (None, ""):
return default
try:
return int(value)
except ValueError as exc:
raise RuntimeError(f"Environment variable {name} must be an integer") from exc
def env_bool(name: str, default: bool) -> bool:
value = os.getenv(name)
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
def env_float(name: str, default: float) -> float:
value = os.getenv(name)
if value in (None, ""):
return default
try:
return float(value)
except ValueError as exc:
raise RuntimeError(f"Environment variable {name} must be a float") from exc
@dataclass
class BotSettings:
default_interval_seconds: int
default_pnl_alert_low: int
default_pnl_alert_high: int
default_night_mode_enabled: bool
night_mode_window: Tuple[int, int]
init_capital: Optional[float] = None
def load_bot_settings() -> BotSettings:
default_interval = env_int("PNL_BOT_DEFAULT_INTERVAL_SECONDS", 3600)
default_low = env_int("PNL_BOT_DEFAULT_PNL_ALERT_LOW", -20)
default_high = env_int("PNL_BOT_DEFAULT_PNL_ALERT_HIGH", 20)
night_mode_start = env_int("PNL_BOT_NIGHT_MODE_START_HOUR", 0)
night_mode_end = env_int("PNL_BOT_NIGHT_MODE_END_HOUR", 5)
default_night_mode = env_bool("PNL_BOT_DEFAULT_NIGHT_MODE_ENABLED", True)
init_capital = env_float("PNL_BOT_INIT_CAPITAL", 0.0)
if not (0 <= night_mode_start <= 23 and 0 <= night_mode_end <= 24):
raise RuntimeError("Night mode hours must be within 0-24 range")
if night_mode_start == night_mode_end:
raise RuntimeError("Night mode start and end hours must differ")
night_mode_window = (night_mode_start, night_mode_end)
return BotSettings(
default_interval_seconds=default_interval,
default_pnl_alert_low=default_low,
default_pnl_alert_high=default_high,
default_night_mode_enabled=default_night_mode,
night_mode_window=night_mode_window,
init_capital=(init_capital if init_capital > 0 else None),
)
@dataclass
class EnvConfig:
api_key: str
api_secret: str
telegram_token: str
telegram_chat_id: str
openai_admin_key: Optional[str] = None
iqair_api_key: Optional[str] = None
iqair_latitude: float = 10.8231
iqair_longitude: float = 106.6297
outage_street_filter: Optional[str] = None
evn_madvi: str = "PB0100"
evn_area_name: str = "Ho Chi Minh"
timezone: str = "Asia/Ho_Chi_Minh"
cpu_alert_threshold: int = 80
mem_alert_threshold: int = 80
disk_alert_threshold: int = 90
@dataclass
class BotState:
interval_seconds: int
night_mode_enabled: bool
pnl_alert_low: int
pnl_alert_high: int
night_mode_window: Tuple[int, int]
is_running: bool = True
last_update_id: Optional[int] = None
max_pnl: float = 0.0
min_pnl: float = 0.0
max_spot_balance: float = 0.0
min_spot_balance: float = 0.0
init_capital: Optional[float] = None
night_mode_active: bool = False
start_time: float = field(default_factory=time.time)
openai_usage: Optional[dict] = None
openai_usage_error: Optional[str] = None
openai_usage_lock: Lock = field(default_factory=Lock, repr=False)
power_outages: List[dict] = field(default_factory=list)
last_outage_check: float = 0.0
last_lunar_alert_date: Optional[str] = None
pinned_daily_message_id: Optional[int] = None
@dataclass
class ConfigDefinition:
description: str
parser: Callable[[str, BotState, BotSettings], object]
getter: Callable[[BotState, BotSettings], object]
applier: Callable[[object, BotState, BotSettings], Optional[str]]
def parse_bool_value(raw: str) -> bool:
normalized = raw.strip().lower()
if normalized in {"1", "true", "yes", "on"}:
return True
if normalized in {"0", "false", "no", "off"}:
return False
raise ValueError("Value must be true/false or on/off")
def parse_float_value(raw: str, *, minimum: Optional[float] = None, maximum: Optional[float] = None) -> float:
try:
value = float(raw)
except (TypeError, ValueError) as exc:
raise ValueError("Value must be a number") from exc
if minimum is not None and value < minimum:
raise ValueError(f"Value must be >= {minimum}")
if maximum is not None and value > maximum:
raise ValueError(f"Value must be <= {maximum}")
return value
def parse_int_value(raw: str, *, minimum: Optional[int] = None, maximum: Optional[int] = None) -> int:
try:
value = int(raw)
except (TypeError, ValueError) as exc:
raise ValueError("Value must be an integer") from exc
if minimum is not None and value < minimum:
raise ValueError(f"Value must be >= {minimum}")
if maximum is not None and value > maximum:
raise ValueError(f"Value must be <= {maximum}")
return value
def format_config_value(value: object) -> str:
if isinstance(value, bool):
return "on" if value else "off"
if isinstance(value, (list, tuple)) and len(value) == 2 and all(isinstance(v, (int, float)) for v in value):
return f"{value[0]} -> {value[1]}"
return str(value)
def create_retry_session() -> requests.Session:
session = requests.Session()
retries = Retry(
total=5,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "OPTIONS", "POST"],
)
session.mount("https://", HTTPAdapter(max_retries=retries))
return session
def epoch_utc(dt_obj: datetime.datetime) -> int:
return int(dt_obj.astimezone(datetime.timezone.utc).timestamp())
def sum_openai_costs(session: requests.Session, key: str, start_epoch: int, end_epoch: int) -> float:
headers = {"Authorization": f"Bearer {key}"}
params = {"start_time": start_epoch, "end_time": end_epoch, "limit": 31}
response = session.get(OPENAI_COSTS_URL, params=params, headers=headers, timeout=30)
response.raise_for_status()
payload = response.json()
total = 0.0
for bucket in payload.get("data", []):
rows = bucket.get("results") or bucket.get("result") or []
for row in rows:
amount = (row.get("amount") or {}).get("value", 0)
try:
total += float(amount or 0)
except (TypeError, ValueError):
continue
return total
def sum_openai_usage(session: requests.Session, key: str, start_epoch: int, end_epoch: int) -> Tuple[int, int]:
headers = {"Authorization": f"Bearer {key}"}
params = {
"start_time": start_epoch,
"end_time": end_epoch,
"bucket_width": "1d",
"limit": 31,
}
response = session.get(OPENAI_USAGE_URL, params=params, headers=headers, timeout=30)
response.raise_for_status()
payload = response.json()
total_requests = 0
total_tokens = 0
for bucket in payload.get("data", []):
rows = bucket.get("results") or bucket.get("result") or []
for row in rows:
requests_count = int(row.get("num_model_requests", 0) or 0)
input_tokens = int(row.get("input_tokens", 0) or 0)
output_tokens = int(row.get("output_tokens", 0) or 0)
total_requests += requests_count
total_tokens += input_tokens + output_tokens
input_details = row.get("input_tokens_details") or {}
cached_tokens = int(input_details.get("cached_tokens", 0) or 0)
total_tokens += cached_tokens
return total_requests, total_tokens
def retrieve_openai_usage(session: requests.Session, config: EnvConfig, settings: BotSettings, key: str, tzinfo: datetime.tzinfo):
tz = pytz.timezone(config.timezone)
now_local = datetime.datetime.now(tz)
month_start_local = now_local.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
month_start_epoch = epoch_utc(month_start_local)
current_epoch = int(datetime.datetime.now(datetime.timezone.utc).timestamp()) + 1
end_time_utc = datetime.datetime.fromtimestamp(current_epoch - 1, tz=datetime.timezone.utc)
end_time_local = end_time_utc.astimezone(tz)
previous_month_end_local = month_start_local - datetime.timedelta(seconds=1)
previous_month_start_local = previous_month_end_local.replace(
day=1, hour=0, minute=0, second=0, microsecond=0
)
previous_month_end_epoch = epoch_utc(
previous_month_end_local.replace(hour=23, minute=59, second=59, microsecond=0)
) + 1
previous_month_start_epoch = epoch_utc(previous_month_start_local)
mtd_cost = sum_openai_costs(session, key, month_start_epoch, current_epoch)
last_month_cost = sum_openai_costs(session, key, previous_month_start_epoch, previous_month_end_epoch)
mtd_requests, mtd_tokens = sum_openai_usage(session, key, month_start_epoch, current_epoch)
return {
"month_start_local": month_start_local,
"previous_month_start_local": previous_month_start_local,
"previous_month_end_local": previous_month_end_local,
"mtd_cost": mtd_cost,
"last_month_cost": last_month_cost,
"mtd_requests": mtd_requests,
"mtd_tokens": mtd_tokens,
"refreshed_at": now_local,
"end_time_local": end_time_local,
"end_time_utc": end_time_utc,
}
def format_openai_usage_report(usage: dict) -> str:
mtd_cost_str = f"${usage['mtd_cost']:,.4f}"
last_month_cost_str = f"${usage['last_month_cost']:,.4f}"
return (
"*📊 OpenAI Costs*\n"
f"• MTD Cost: `{mtd_cost_str}`\n"
f"• Last Month: `{last_month_cost_str}`"
)
def refresh_openai_usage(session: requests.Session, config: EnvConfig, settings: BotSettings, state: BotState) -> Optional[dict]:
if not config.openai_admin_key:
return None
# Perform retrieval outside of the lock to avoid blocking other status checks
try:
tz = pytz.timezone(config.timezone)
usage = retrieve_openai_usage(session, config, settings, config.openai_admin_key, tz)
with state.openai_usage_lock:
state.openai_usage = usage
state.openai_usage_error = None
return usage
except requests.RequestException as exc:
with state.openai_usage_lock:
state.openai_usage = None
state.openai_usage_error = f"OpenAI usage unavailable: {exc}"
return None
except Exception as exc:
with state.openai_usage_lock:
state.openai_usage = None
state.openai_usage_error = f"OpenAI usage error: {exc}"
return None
def start_openai_usage_worker(
session: requests.Session, config: EnvConfig, settings: BotSettings, state: BotState, interval_seconds: int
) -> Optional[threading.Thread]:
if not config.openai_admin_key:
return None
def worker():
sleep_interval = max(60, interval_seconds)
while True:
refresh_openai_usage(session, config, settings, state)
sleep_interval = max(60, OPENAI_REFRESH_SECONDS)
time.sleep(sleep_interval)
thread = threading.Thread(target=worker, name="openai-usage-worker", daemon=True)
thread.start()
return thread
def start_system_monitor_worker(
session: requests.Session, config: EnvConfig, settings: BotSettings, state: BotState
) -> threading.Thread:
def worker():
last_alert_time = 0
while True:
try:
time.sleep(5) # Near real-time check every 5 seconds
if not state.is_running:
continue
system_info = get_system_info_text(config, settings)
if system_info:
now = time.time()
# 5 minutes cooldown to avoid alert spam
if now - last_alert_time > 300:
send_telegram_message(session, config, settings, system_info, state=state, force_send=True)
last_alert_time = now
except Exception as exc:
print(f"System monitor worker error: {exc}")
time.sleep(10)
thread = threading.Thread(target=worker, name="system-monitor-worker", daemon=True)
thread.start()
return thread
def compose_status_message(
state: BotState,
config: EnvConfig,
status_info: Optional[str],
current_pnl: Union[float, str],
*,
openai_line: Optional[str] = None,
spot_balance: Optional[Union[float, str]] = None,
) -> str:
lines = [
"🧭 Status:",
f"• Running: `{state.is_running}`",
f"• Interval: `{state.interval_seconds / 60:.1f}m`",
f"• Night mode: `{state.night_mode_enabled}` (active: `{state.night_mode_active}`)",
f"• Alert limit: `{state.pnl_alert_low} USDT ~ {state.pnl_alert_high} USDT`",
f"• Uptime: `{get_uptime(state)}`",
f"• Lunar: `{get_lunar_date_string(config.timezone)}`",
]
todo_count = get_todo_count()
if todo_count > 0:
lines.append(f"• TODO Left: `{todo_count}`")
if state.init_capital:
lines.append(f"• Init Capital: `{state.init_capital:,.2f} USDT`")
if openai_line:
lines.append(openai_line)
lines.extend([
"",
"💰 *Spot Balance:*",
])
if spot_balance is not None:
if isinstance(spot_balance, dict):
total = spot_balance.get("total", 0.0)
pnl_perc_line = ""
if state.init_capital:
pnl_perc = (total - state.init_capital) / state.init_capital * 100
pnl_perc_line = f" ({pnl_perc:+.2f}%)"
lines.append(f"• Total: `{total:,.2f} USDT`{pnl_perc_line}")
lines.append(f"• Max: `{state.max_spot_balance:,.2f} USDT`, Min: `{state.min_spot_balance:,.2f} USDT`")
breakdown = spot_balance.get("breakdown", [])
for item in breakdown[:5]: # Show top 5 assets
price_str = f" @ {item['price']:,.4f}" if item['asset'] != "USDT" else ""
lines.append(f" ▫️ `{item['asset']}`: `{item['usdt_value']:,.2f} USDT`{price_str}")
if len(breakdown) > 5:
lines.append(f" ▫️ ... and {len(breakdown)-5} more assets")
elif isinstance(spot_balance, (int, float)):
total = float(spot_balance)
pnl_perc_line = ""
if state.init_capital:
pnl_perc = (total - state.init_capital) / state.init_capital * 100
pnl_perc_line = f" ({pnl_perc:+.2f}%)"
lines.append(f"• Total: `{total:,.2f} USDT`{pnl_perc_line}")
lines.append(f"• Max: `{state.max_spot_balance:,.2f} USDT`, Min: `{state.min_spot_balance:,.2f} USDT`")
else:
lines.append(f"• {spot_balance}")
lines.extend([
"",
"📊 *Futures PnL:*",
])
if isinstance(current_pnl, (int, float)):
lines.append(f"• Current PnL: `{current_pnl:,.2f} USDT`")
else:
lines.append(f"• Current PnL: `{current_pnl}`")
lines.extend([
f"• Max PnL: `{state.max_pnl} USDT`, Min: `{state.min_pnl} USDT`",
])
return "\n".join(lines)
def build_openai_status_line(state: BotState) -> Optional[str]:
with state.openai_usage_lock:
usage = state.openai_usage
error = state.openai_usage_error
if usage:
return (
f"• OpenAI cost (MTD): `${usage['mtd_cost']:,.4f}` "
f"(last month `${usage['last_month_cost']:,.4f}`)"
)
if error:
return f"• `{error}`"
return "• OpenAI usage: fetching..."
def load_env_config() -> EnvConfig:
def require_env(name: str) -> str:
value = os.getenv(name)
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
config = EnvConfig(
api_key=require_env("API_KEY"),
api_secret=require_env("API_SECRET"),
telegram_token=require_env("TELEGRAM_TOKEN"),
telegram_chat_id=require_env("TELEGRAM_CHAT_ID"),
openai_admin_key=os.getenv("OPENAI_ADMIN_KEY"),
iqair_api_key=os.getenv("IQAIR_API_KEY"),
iqair_latitude=env_float("IQAIR_LATITUDE", 10.8231),
iqair_longitude=env_float("IQAIR_LONGITUDE", 106.6297),
outage_street_filter=os.getenv("PNL_BOT_OUTAGE_STREET_FILTER"),
evn_madvi=env_str("PNL_BOT_EVN_MADVI", "PB0100"),
evn_area_name=env_str("PNL_BOT_EVN_AREA_NAME", "Ho Chi Minh"),
timezone=env_str("PNL_BOT_TIMEZONE", "Asia/Ho_Chi_Minh"),
cpu_alert_threshold=env_int("PNL_BOT_CPU_ALERT_THRESHOLD", 80),
mem_alert_threshold=env_int("PNL_BOT_MEM_ALERT_THRESHOLD", 80),
disk_alert_threshold=env_int("PNL_BOT_DISK_ALERT_THRESHOLD", 90),
)
return config
def load_persisted_state(path: str) -> Optional[dict]:
if not os.path.exists(path):
return None
try:
with open(path, "r", encoding="utf-8") as handle:
return json.load(handle)
except (OSError, json.JSONDecodeError) as exc:
print(f"Could not load persisted state: {exc}")
return None
def apply_persisted_configuration(persisted: dict, state: BotState, settings: BotSettings) -> None:
if not persisted:
return
state_data = persisted.get("state", persisted)
def _safe_int(value, default):
try:
return int(value)
except (TypeError, ValueError):
return default
def _safe_float(value, default):
try:
return float(value)
except (TypeError, ValueError):
return default
state.interval_seconds = _safe_int(state_data.get("interval_seconds"), state.interval_seconds)
state.night_mode_enabled = bool(state_data.get("night_mode_enabled", state.night_mode_enabled))
state.is_running = bool(state_data.get("is_running", state.is_running))
state.pnl_alert_low = _safe_int(state_data.get("pnl_alert_low"), state.pnl_alert_low)
state.pnl_alert_high = _safe_int(state_data.get("pnl_alert_high"), state.pnl_alert_high)
state.max_pnl = _safe_float(state_data.get("max_pnl"), state.max_pnl)
state.min_pnl = _safe_float(state_data.get("min_pnl"), state.min_pnl)
state.max_spot_balance = _safe_float(state_data.get("max_spot_balance"), state.max_spot_balance)
state.min_spot_balance = _safe_float(state_data.get("min_spot_balance"), state.min_spot_balance)
state.init_capital = _safe_float(state_data.get("init_capital"), state.init_capital)
state.last_lunar_alert_date = state_data.get("last_lunar_alert_date", state.last_lunar_alert_date)
state.pinned_daily_message_id = state_data.get("pinned_daily_message_id", state.pinned_daily_message_id)
night_window = state_data.get("night_mode_window")
if isinstance(night_window, (list, tuple)) and len(night_window) == 2:
try:
start_hour = int(night_window[0])
end_hour = int(night_window[1])
state.night_mode_window = (start_hour, end_hour)
settings.night_mode_window = state.night_mode_window
except (TypeError, ValueError):
pass
state.power_outages = state_data.get("power_outages", state.power_outages)
state.last_outage_check = _safe_float(state_data.get("last_outage_check"), state.last_outage_check)
def persist_runtime_state(path: str, state: BotState, settings: BotSettings) -> None:
state_data = {
"interval_seconds": state.interval_seconds,
"night_mode_enabled": state.night_mode_enabled,
"is_running": state.is_running,
"pnl_alert_low": state.pnl_alert_low,
"pnl_alert_high": state.pnl_alert_high,
"max_pnl": state.max_pnl,
"min_pnl": state.min_pnl,
"max_spot_balance": state.max_spot_balance,
"min_spot_balance": state.min_spot_balance,
"init_capital": state.init_capital,
"night_mode_window": list(state.night_mode_window),
"power_outages": state.power_outages,
"last_outage_check": state.last_outage_check,
"last_lunar_alert_date": state.last_lunar_alert_date,
"pinned_daily_message_id": state.pinned_daily_message_id,
}
payload = {
"state": state_data,
}
tmp_path = f"{path}.tmp"
try:
with open(tmp_path, "w", encoding="utf-8") as handle:
json.dump(payload, handle)
os.replace(tmp_path, path)
except OSError as exc:
print(f"Could not persist state: {exc}")
try:
if os.path.exists(tmp_path):
os.remove(tmp_path)
except OSError:
pass
def notify_exit(session: requests.Session, config: EnvConfig, settings: BotSettings) -> None:
try:
send_telegram_message(session, config, settings, "❌ Bot has been stopped.", force_send=True)
except Exception as exc:
print(f"Error while sending shutdown notification: {exc}")
def get_futures_pnl(session: requests.Session, config: EnvConfig) -> Union[float, str]:
base_url = "https://fapi.binance.com"
endpoint = "/fapi/v2/account"
timestamp = int(time.time() * 1000)
query_string = f"timestamp={timestamp}"
signature = hmac.new(config.api_secret.encode("utf-8"), query_string.encode("utf-8"), hashlib.sha256).hexdigest()
url = f"{base_url}{endpoint}?{query_string}&signature={signature}"
headers = {"X-MBX-APIKEY": config.api_key}
try:
response = session.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
positions = data.get("positions", [])
total_unrealized_pnl = sum(float(position.get("unrealizedProfit", 0.0)) for position in positions)
return round(total_unrealized_pnl, 2)
except Exception as exc:
return f"PnL fetch error: {exc}"
def get_spot_balance(session: requests.Session, config: EnvConfig) -> Union[dict, str]:
base_url = "https://api.binance.com"
endpoint = "/api/v3/account"
timestamp = int(time.time() * 1000)
query_string = f"timestamp={timestamp}"
signature = hmac.new(config.api_secret.encode("utf-8"), query_string.encode("utf-8"), hashlib.sha256).hexdigest()
url = f"{base_url}{endpoint}?{query_string}&signature={signature}"
headers = {"X-MBX-APIKEY": config.api_key}
try:
# 1. Get Account Balances
response = session.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
balances = data.get("balances", [])
# 2. Get Current Prices
price_url = "https://api.binance.com/api/v3/ticker/price"
price_response = session.get(price_url, timeout=10)
price_response.raise_for_status()
prices = {item["symbol"]: float(item["price"]) for item in price_response.json()}
total_usdt = 0.0
breakdown = []
for balance in balances:
asset = balance.get("asset")
free = float(balance.get("free", 0.0))
locked = float(balance.get("locked", 0.0))
amount = free + locked
if amount <= 0:
continue
asset_usdt_value = 0.0
if asset == "USDT":
asset_usdt_value = amount
else:
symbol = f"{asset}USDT"
if symbol in prices:
asset_usdt_value = amount * prices[symbol]
else:
# Try getting price from other pairs if needed, but USDT is usually the base
continue
if asset_usdt_value < 0.01: # Filter out dust
continue
total_usdt += asset_usdt_value
breakdown.append({
"asset": asset,
"amount": amount,
"usdt_value": asset_usdt_value,
"price": prices.get(symbol, 1.0) if asset != "USDT" else 1.0
})
# Sort breakdown by USDT value descending
breakdown.sort(key=lambda x: x["usdt_value"], reverse=True)
return {
"total": round(total_usdt, 2),
"breakdown": breakdown,
"btc_price": prices.get("BTCUSDT", 0.0)
}
except Exception as exc:
return f"Spot balance fetch error: {exc}"
def get_air_quality(session: requests.Session, config: EnvConfig) -> Union[dict, str]:
"""Fetch air quality data from IQAir API using GPS coordinates."""
if not config.iqair_api_key:
return "IQAir API key not configured"
try:
params = {
"lat": config.iqair_latitude,
"lon": config.iqair_longitude,
"key": config.iqair_api_key,
}
response = session.get(IQAIR_API_URL, params=params, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("status") != "success":
return f"IQAir API error: {data.get('message', 'Unknown error')}"
result_data = data.get("data", {})
current = result_data.get("current", {})
pollution = current.get("pollution", {})
weather = current.get("weather", {})
return {
"city": result_data.get("city", "Unknown"),
"country": result_data.get("country", "Unknown"),
"aqi_us": pollution.get("aqius", 0),
"temperature": weather.get("tp", 0),
"humidity": weather.get("hu", 0),
}
except Exception as exc:
return f"Air quality fetch error: {exc}"
def get_top_processes(n: int = 5) -> Tuple[str, str]:
processes = []
for proc in psutil.process_iter(attrs=["pid", "name", "cpu_percent", "memory_percent"]):
try:
processes.append(proc.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
top_cpu = sorted(processes, key=lambda x: x["cpu_percent"], reverse=True)[:n]
top_mem = sorted(processes, key=lambda x: x["memory_percent"], reverse=True)[:n]
cpu_info = "\n".join(
[f"• `{proc['name']}` (PID `{proc['pid']}`): `{proc['cpu_percent']}%` CPU" for proc in top_cpu]
)
mem_info = "\n".join(
[f"• `{proc['name']}` (PID `{proc['pid']}`): `{round(proc['memory_percent'], 1)}%` RAM" for proc in top_mem]
)
return cpu_info, mem_info
def get_system_info_text(config: EnvConfig, settings: BotSettings, show_all: bool = False) -> Optional[str]:
cpu = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory().percent
disk = psutil.disk_usage("/").percent
is_alert = (
cpu > config.cpu_alert_threshold
or mem > config.mem_alert_threshold
or disk > config.disk_alert_threshold
)
if not show_all and not is_alert:
return None
info_lines = []
title = "*🖥 System Alert:*" if is_alert else "*📊 Current system metrics:*"
info_lines.append(title)
def format_line(label, val, thresh):
exceeded = val > thresh
if exceeded:
return f"🔴 *{label}: `{val}%` (alert when > `{thresh}%`)*"
return f"• {label}: `{val}%` (alert when > `{thresh}%`)"
# Add lines: always if show_all, or only if exceeded if is_alert
for label, val, thresh in [
("CPU", cpu, config.cpu_alert_threshold),
("RAM", mem, config.mem_alert_threshold),
("Disk", disk, config.disk_alert_threshold),
]:
if show_all or val > thresh:
info_lines.append(format_line(label, val, thresh))
top_cpu, top_mem = get_top_processes()
info_lines.append("\n*⚙️ Top CPU processes:*\n" + top_cpu)
info_lines.append("\n*💾 Top RAM processes:*\n" + top_mem)
return "\n".join(info_lines)
def remove_accents(input_str: str) -> str:
"""Removes accents from Vietnamese characters, including the letter 'đ'."""
if not input_str:
return ""
# Normalize unicode to decompose accents
nfkd_form = unicodedata.normalize('NFKD', input_str)
# Filter out non-spacing marks (accents)
s = "".join([c for c in nfkd_form if not unicodedata.combining(c)])
# Specifically handle Vietnamese 'đ' and 'Đ'
s = s.replace('đ', 'd').replace('Đ', 'D')
return s
def send_telegram_message(
session: requests.Session,
config: EnvConfig,
settings: BotSettings,
message: str,
*,
chat_id: Optional[str] = None,
state: Optional[BotState] = None,
force_send: bool = False,
) -> Optional[dict]:
tz = pytz.timezone(config.timezone)
now_hour = datetime.datetime.now(tz).hour
if state and state.night_mode_enabled and not force_send:
start_hour, end_hour = state.night_mode_window
if start_hour <= end_hour:
if start_hour <= now_hour < end_hour:
return
else:
if now_hour >= start_hour or now_hour < end_hour:
return
url = f"{TELEGRAM_API_URL}/bot{config.telegram_token}/sendMessage"
payload = {
"chat_id": chat_id or config.telegram_chat_id,
"text": message,
"parse_mode": "Markdown",
}
try:
if len(message) > TELEGRAM_MAX_MESSAGE:
first_res = None
for idx in range(0, len(message), TELEGRAM_MAX_MESSAGE):
res = session.post(
url,
data={**payload, "text": message[idx : idx + TELEGRAM_MAX_MESSAGE]},
timeout=10,
)
res.raise_for_status()
if first_res is None:
first_res = res.json()
return first_res
else:
res = session.post(url, data=payload, timeout=10)
res.raise_for_status()
return res.json()
except Exception as exc:
print(f"Telegram send error: {exc}", flush=True)
return None
def pin_telegram_message(session: requests.Session, config: EnvConfig, message_id: int) -> None:
url = f"{TELEGRAM_API_URL}/bot{config.telegram_token}/pinChatMessage"
payload = {
"chat_id": config.telegram_chat_id,
"message_id": message_id,
"disable_notification": True,
}
try:
res = session.post(url, data=payload, timeout=10)
res.raise_for_status()
except Exception as exc:
print(f"Telegram pin error: {exc}", flush=True)
def unpin_telegram_message(session: requests.Session, config: EnvConfig, message_id: Optional[int] = None) -> None:
url = f"{TELEGRAM_API_URL}/bot{config.telegram_token}/unpinChatMessage"
payload = {"chat_id": config.telegram_chat_id}
if message_id:
payload["message_id"] = message_id
try:
res = session.post(url, data=payload, timeout=10)
res.raise_for_status()
except Exception as exc:
print(f"Telegram unpin error: {exc}", flush=True)
def get_uptime(state: BotState) -> str:
uptime_seconds = int(time.time() - state.start_time)
months, remainder = divmod(uptime_seconds, 2592000) # 30 days
days, remainder = divmod(remainder, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
parts = []
if months > 0:
parts.append(f"{months}mo")
if days > 0:
parts.append(f"{days}d")
if hours > 0 or (not parts):
parts.append(f"{hours}h")
if minutes > 0 or (not parts and hours == 0):
parts.append(f"{minutes}m")
if seconds > 0 or not parts:
parts.append(f"{seconds}s")
return ",".join(parts)
def get_lunar_date_string(timezone_name: str) -> str:
try:
now = datetime.datetime.now(pytz.timezone(timezone_name))
lunar = solar_to_lunar(now)
day_str = f"Mùng `{lunar.day}`" if lunar.day <= 10 else f"`{lunar.day}`"
month_str = f"Tháng `{lunar.month}`"
if lunar.leap:
month_str += " (Nhuận)"
year_can_chi = can_chi.get_year_can_chi(lunar.year)
holiday = holidays.get_holiday(now.date(), lunar)
holiday_str = f" - `{holiday}`" if holiday else ""
return f"{day_str} {month_str} Năm `{year_can_chi}`{holiday_str}"
except Exception as exc:
return f"Error: {exc}"
def get_power_outages(session: requests.Session, config: EnvConfig) -> List[dict]:
"""Fetches upcoming power outages from EVN SPC API, based on configured Ma Don Vi."""
tz = pytz.timezone(config.timezone)
now = datetime.datetime.now(tz)
tomorrow = now + datetime.timedelta(days=1)
end_date = now + datetime.timedelta(days=7)
params = {
"madvi": config.evn_madvi,
"tuNgay": now.strftime("%d-%m-%Y"),
"denNgay": end_date.strftime("%d-%m-%Y"),
"ChucNang": "MaDonVi",
}
try:
response = session.get(EVN_SPC_OUTAGE_URL, params=params, timeout=10)
response.raise_for_status()
html_content = response.text
# Robust parsing for the specific structure found in live responses
blocks = re.findall(r'<div class="entry">(.*?)</div>\s*<br />', html_content, re.DOTALL)
outages = []
for block in blocks:
# Area extraction
area_match = re.search(r'class="where"><b>KHU VỰC:</b>\s*(.*?)</span>', block, re.DOTALL)
# Time extraction (handling multi-line and whitespace)
time_match = re.search(r'class="time">.*?<span style="white-space:nowrap;">\s*(.*?)\s*</span>\s*</span>', block, re.DOTALL)
# Reason extraction
reason_match = re.search(r'class="cause">.*?<span>(.*?)</span>\s*</span>', block, re.DOTALL)
if area_match and time_match:
area = html.unescape(area_match.group(1).strip())
# Clean up time string (remove extra whitespace/newlines)
time_info = html.unescape(time_match.group(1).strip())
time_info = re.sub(r'\s+', ' ', time_info)
# Skip if filter is set and does not match area (accent-insensitive)
filter_str = config.outage_street_filter
if filter_str:
normalized_area = remove_accents(area).lower()
normalized_filter = remove_accents(filter_str).lower()
if normalized_filter not in normalized_area:
continue
reason = html.unescape(reason_match.group(1).strip()) if reason_match else "N/A"
reason = re.sub(r'\s+', ' ', reason)
# Use area + time as a unique key for deduplication
outage_id = hashlib.md5(f"{area}{time_info}".encode("utf-8")).hexdigest()
outages.append({
"id": outage_id,
"area": area,
"time": time_info,
"reason": reason
})
return outages
except Exception as exc:
print(f"Error fetching power outages: {exc}")
return []
def refresh_power_outages(session: requests.Session, config: EnvConfig, state: BotState) -> List[dict]:
"""Updates the state with new power outages and returns only the NEW ones."""
current_outages = get_power_outages(session, config)
if not current_outages:
return []
seen_ids = {o["id"] for o in state.power_outages}
new_outages = [o for o in current_outages if o["id"] not in seen_ids]
# Keep only current and future outages in state
# Since we don't have perfect date parsing here, we'll just keep the latest results
# and filter by ID to find truly new ones.
state.power_outages = current_outages
state.last_outage_check = time.time()
return new_outages
def get_todo_count() -> int:
if not os.path.exists(TODO_FILE_PATH):
return 0
try:
with open(TODO_FILE_PATH, "r", encoding="utf-8") as handle:
return sum(1 for line in handle if line.strip())
except Exception:
return 0
def ensure_todo_file_exists(todo_file: str) -> None:
if not os.path.exists(todo_file):
with open(todo_file, "w", encoding="utf-8") as handle: