-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1107 lines (947 loc) · 34.2 KB
/
main.py
File metadata and controls
1107 lines (947 loc) · 34.2 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
"""Live strategy orchestration entrypoint.
The live cycle remains here so the execution flow is easy to follow in one file.
Pure strategy math, state normalization, upstream contract handling, exchange
helpers, and live service adapters live in dedicated modules.
"""
import os
import time
import sys
import traceback
from entrypoints.cli import run_cli_entrypoint
from notify_i18n_support import build_strategy_display_name, translate as t
from degraded_mode_support import (
format_trend_pool_source_logs as dm_format_trend_pool_source_logs,
load_trend_universe_from_live_pool as dm_load_trend_universe_from_live_pool,
resolve_trend_pool_source as dm_resolve_trend_pool_source,
update_trend_pool_state as dm_update_trend_pool_state,
)
from quant_platform_kit.binance import (
connect_client as qpk_connect_client,
ensure_asset_available as qpk_ensure_asset_available,
fetch_btc_market_snapshot as qpk_fetch_btc_market_snapshot,
fetch_daily_indicators as qpk_fetch_daily_indicators,
format_qty as qpk_format_qty,
get_total_balance as qpk_get_total_balance,
manage_usdt_earn_buffer as qpk_manage_usdt_earn_buffer,
)
from live_services import (
get_firestore_client as live_get_firestore_client,
get_state_doc_ref as live_get_state_doc_ref,
send_tg_msg as live_send_tg_msg,
)
from market_snapshot_support import (
capture_market_snapshot as ms_capture_market_snapshot,
)
from runtime_support import (
ExecutionRuntime as _ExecutionRuntime,
append_report_error,
build_execution_report,
next_order_id,
runtime_call_client,
runtime_notify,
runtime_set_trade_state,
)
from runtime_config_support import (
build_live_runtime as rc_build_live_runtime,
get_env_bool as rc_get_env_bool,
get_env_csv as rc_get_env_csv,
get_env_int as rc_get_env_int,
load_cycle_execution_settings as rc_load_cycle_execution_settings,
)
from application.cycle_service import execute_strategy_cycle
from application.execution_service import (
execute_trend_buys as app_execute_trend_buys,
execute_trend_sells as app_execute_trend_sells,
execute_btc_dca_cycle as app_execute_btc_dca_cycle,
execute_trend_rotation as app_execute_trend_rotation,
run_daily_circuit_breaker as app_run_daily_circuit_breaker,
)
from application.portfolio_service import (
append_portfolio_report as app_append_portfolio_report,
build_balance_snapshot as app_build_balance_snapshot,
compute_daily_pnls as app_compute_daily_pnls,
maybe_rebase_daily_state_for_balance_change as app_maybe_rebase_daily_state_for_balance_change,
maybe_reset_daily_state as app_maybe_reset_daily_state,
)
from application.state_service import (
append_trend_pool_source_logs as app_append_trend_pool_source_logs,
load_cycle_state as app_load_cycle_state,
)
from application.trend_pool_service import (
resolve_runtime_trend_pool as app_resolve_runtime_trend_pool,
)
from infra.binance_runtime import (
ensure_asset_available_runtime as infra_ensure_asset_available_runtime,
ensure_runtime_client as infra_ensure_runtime_client,
manage_usdt_earn_buffer_runtime as infra_manage_usdt_earn_buffer_runtime,
resolve_runtime_btc_snapshot as infra_resolve_runtime_btc_snapshot,
resolve_runtime_trend_indicators as infra_resolve_runtime_trend_indicators,
)
from infra.state_store import (
load_runtime_trade_state as infra_load_runtime_trade_state,
save_runtime_trade_state as infra_save_runtime_trade_state,
)
from reporting.status_reports import (
append_portfolio_report as report_append_portfolio_report,
append_rotation_summary as report_append_rotation_summary,
append_trend_symbol_status as report_append_trend_symbol_status,
build_btc_manual_hint as report_build_btc_manual_hint,
get_periodic_report_bucket as report_get_periodic_report_bucket,
maybe_send_periodic_btc_status_report as report_maybe_send_periodic_btc_status_report,
)
from decision_mapper import (
map_strategy_decision_to_allocation as map_decision_to_allocation,
map_strategy_decision_to_rotation_plan as map_decision_to_rotation_plan,
)
from strategy_runtime import load_strategy_runtime
from trade_state_support import (
build_default_state as ts_build_default_state,
default_trend_symbol_state as ts_default_trend_symbol_state,
get_runtime_trend_universe as ts_get_runtime_trend_universe,
get_symbol_trade_state as ts_get_symbol_trade_state,
has_active_position as ts_has_active_position,
infer_base_asset as ts_infer_base_asset,
is_trend_symbol_state as ts_is_trend_symbol_state,
normalize_symbol_state as ts_normalize_symbol_state,
normalize_trade_state as ts_normalize_trade_state,
record_trend_action as ts_record_trend_action,
safe_float as ts_safe_float,
set_symbol_trade_state as ts_set_symbol_trade_state,
should_skip_duplicate_trend_action as ts_should_skip_duplicate_trend_action,
)
from trend_pool_support import (
build_static_trend_pool_resolution as tp_build_static_trend_pool_resolution,
build_trend_pool_resolution as tp_build_trend_pool_resolution,
extract_trend_pool_symbols as tp_extract_trend_pool_symbols,
get_default_live_pool_candidates as tp_get_default_live_pool_candidates,
get_last_known_good_trend_pool as tp_get_last_known_good_trend_pool,
get_trend_pool_contract_settings as tp_get_trend_pool_contract_settings,
load_trend_pool_from_file as tp_load_trend_pool_from_file,
load_trend_pool_from_firestore as tp_load_trend_pool_from_firestore,
parse_trend_pool_date as tp_parse_trend_pool_date,
parse_trend_universe_mapping as tp_parse_trend_universe_mapping,
validate_trend_pool_payload as tp_validate_trend_pool_payload,
)
ExecutionRuntime = _ExecutionRuntime
STRATEGY_RUNTIME = load_strategy_runtime(os.getenv("STRATEGY_PROFILE"))
SEPARATOR = "━━━━━━━━━━━━━━━━━━"
STATIC_TREND_UNIVERSE = {
"ETHUSDT": {"base_asset": "ETH"},
"SOLUSDT": {"base_asset": "SOL"},
"XRPUSDT": {"base_asset": "XRP"},
"LINKUSDT": {"base_asset": "LINK"},
"AVAXUSDT": {"base_asset": "AVAX"},
"ADAUSDT": {"base_asset": "ADA"},
"DOGEUSDT": {"base_asset": "DOGE"},
"TRXUSDT": {"base_asset": "TRX"},
"ATOMUSDT": {"base_asset": "ATOM"},
"LTCUSDT": {"base_asset": "LTC"},
"BCHUSDT": {"base_asset": "BCH"},
}
TREND_UNIVERSE = STATIC_TREND_UNIVERSE.copy()
TREND_POOL_SIZE = STRATEGY_RUNTIME.trend_pool_size
BNB_FUEL_SYMBOL = "BNBUSDT"
BNB_FUEL_ASSET = "BNB"
DEFAULT_LIVE_POOL_LEGACY_PATH = STRATEGY_RUNTIME.default_local_artifact_path
DEFAULT_TREND_POOL_FIRESTORE_COLLECTION = "strategy"
DEFAULT_TREND_POOL_FIRESTORE_DOCUMENT = "CRYPTO_LEADER_ROTATION_LIVE_POOL"
RETIRED_TREND_POSITIONS_KEY = "retired_trend_positions"
TREND_POOL_LAST_GOOD_PAYLOAD_KEY = "trend_pool_last_good_payload"
TREND_POOL_ACTION_HISTORY_KEY = "trend_action_history"
DEFAULT_TREND_POOL_MAX_AGE_DAYS = int(STRATEGY_RUNTIME.artifact_contract["max_age_days"])
DEFAULT_TREND_POOL_ACCEPTABLE_MODES = tuple(STRATEGY_RUNTIME.artifact_contract["acceptable_modes"])
class BalanceFetchError(RuntimeError):
pass
def get_env_int(name, default):
return rc_get_env_int(name, default)
def get_env_bool(name, default=False):
return rc_get_env_bool(name, default)
def get_env_csv(name, default_values):
return rc_get_env_csv(name, default_values)
def default_trend_symbol_state():
return ts_default_trend_symbol_state()
def safe_float(value, default=0.0):
return ts_safe_float(value, default)
def infer_base_asset(symbol):
return ts_infer_base_asset(symbol)
def is_trend_symbol_state(value):
return ts_is_trend_symbol_state(value)
def normalize_symbol_state(value):
return ts_normalize_symbol_state(value)
def has_active_position(position_state):
return ts_has_active_position(position_state)
def parse_trend_pool_date(value):
return tp_parse_trend_pool_date(value)
def parse_trend_universe_mapping(payload):
return tp_parse_trend_universe_mapping(payload)
def extract_trend_pool_symbols(payload, symbol_map):
return tp_extract_trend_pool_symbols(payload, symbol_map)
def get_trend_pool_contract_settings():
return tp_get_trend_pool_contract_settings(
max_age_days_default=DEFAULT_TREND_POOL_MAX_AGE_DAYS,
acceptable_modes_default=DEFAULT_TREND_POOL_ACCEPTABLE_MODES,
expected_pool_size_default=TREND_POOL_SIZE,
)
def validate_trend_pool_payload(
payload,
source_label,
*,
now_utc=None,
max_age_days=DEFAULT_TREND_POOL_MAX_AGE_DAYS,
acceptable_modes=None,
expected_pool_size=TREND_POOL_SIZE,
enforce_freshness=True,
):
return tp_validate_trend_pool_payload(
payload,
source_label,
now_utc=now_utc,
max_age_days=max_age_days,
acceptable_modes=acceptable_modes,
expected_pool_size=expected_pool_size,
enforce_freshness=enforce_freshness,
)
def get_default_live_pool_candidates():
return list(STRATEGY_RUNTIME.local_artifact_candidates) or tp_get_default_live_pool_candidates(
DEFAULT_LIVE_POOL_LEGACY_PATH
)
def get_firestore_client():
return live_get_firestore_client()
def get_state_doc_ref():
return live_get_state_doc_ref(collection="strategy", document="MULTI_ASSET_STATE")
def load_trend_pool_from_firestore(*, now_utc=None, settings=None):
return tp_load_trend_pool_from_firestore(
now_utc=now_utc,
settings=settings or get_trend_pool_contract_settings(),
default_collection=DEFAULT_TREND_POOL_FIRESTORE_COLLECTION,
default_document=DEFAULT_TREND_POOL_FIRESTORE_DOCUMENT,
)
def load_trend_pool_from_file(path, *, now_utc=None, settings=None):
return tp_load_trend_pool_from_file(
path,
now_utc=now_utc,
settings=settings or get_trend_pool_contract_settings(),
)
def build_trend_pool_resolution(validated_payload, *, source_kind, degraded, now_utc=None, messages=None):
return tp_build_trend_pool_resolution(
validated_payload,
source_kind=source_kind,
degraded=degraded,
now_utc=now_utc,
messages=messages,
)
def get_last_known_good_trend_pool(state, *, now_utc=None, settings=None):
return tp_get_last_known_good_trend_pool(
state,
now_utc=now_utc,
settings=settings or get_trend_pool_contract_settings(),
last_good_payload_key=TREND_POOL_LAST_GOOD_PAYLOAD_KEY,
)
def build_static_trend_pool_resolution(*, now_utc=None, messages=None):
return tp_build_static_trend_pool_resolution(
now_utc=now_utc,
messages=messages,
static_trend_universe=STATIC_TREND_UNIVERSE,
)
def resolve_trend_pool_source(state=None, *, now_utc=None):
return dm_resolve_trend_pool_source(
state=state,
now_utc=now_utc,
default_live_pool_legacy_path=DEFAULT_LIVE_POOL_LEGACY_PATH,
default_firestore_collection=DEFAULT_TREND_POOL_FIRESTORE_COLLECTION,
default_firestore_document=DEFAULT_TREND_POOL_FIRESTORE_DOCUMENT,
last_good_payload_key=TREND_POOL_LAST_GOOD_PAYLOAD_KEY,
static_trend_universe=STATIC_TREND_UNIVERSE,
max_age_days_default=DEFAULT_TREND_POOL_MAX_AGE_DAYS,
acceptable_modes_default=DEFAULT_TREND_POOL_ACCEPTABLE_MODES,
expected_pool_size_default=TREND_POOL_SIZE,
)
def load_trend_universe_from_live_pool(state=None, *, now_utc=None):
return dm_load_trend_universe_from_live_pool(
state=state,
now_utc=now_utc,
default_live_pool_legacy_path=DEFAULT_LIVE_POOL_LEGACY_PATH,
default_firestore_collection=DEFAULT_TREND_POOL_FIRESTORE_COLLECTION,
default_firestore_document=DEFAULT_TREND_POOL_FIRESTORE_DOCUMENT,
last_good_payload_key=TREND_POOL_LAST_GOOD_PAYLOAD_KEY,
static_trend_universe=STATIC_TREND_UNIVERSE,
max_age_days_default=DEFAULT_TREND_POOL_MAX_AGE_DAYS,
acceptable_modes_default=DEFAULT_TREND_POOL_ACCEPTABLE_MODES,
expected_pool_size_default=TREND_POOL_SIZE,
)
def update_trend_pool_state(state, resolution):
dm_update_trend_pool_state(
state,
resolution,
last_good_payload_key=TREND_POOL_LAST_GOOD_PAYLOAD_KEY,
)
def build_default_state():
return ts_build_default_state(
trend_universe=TREND_UNIVERSE,
last_good_payload_key=TREND_POOL_LAST_GOOD_PAYLOAD_KEY,
action_history_key=TREND_POOL_ACTION_HISTORY_KEY,
retired_positions_key=RETIRED_TREND_POSITIONS_KEY,
)
def normalize_trade_state(state):
return ts_normalize_trade_state(
state,
trend_universe=TREND_UNIVERSE,
last_good_payload_key=TREND_POOL_LAST_GOOD_PAYLOAD_KEY,
action_history_key=TREND_POOL_ACTION_HISTORY_KEY,
retired_positions_key=RETIRED_TREND_POSITIONS_KEY,
)
def get_runtime_trend_universe(state):
return ts_get_runtime_trend_universe(
state,
trend_universe=TREND_UNIVERSE,
retired_positions_key=RETIRED_TREND_POSITIONS_KEY,
)
def get_symbol_trade_state(state, symbol):
return ts_get_symbol_trade_state(
state,
symbol,
trend_universe=TREND_UNIVERSE,
retired_positions_key=RETIRED_TREND_POSITIONS_KEY,
)
def set_symbol_trade_state(state, symbol, symbol_state):
ts_set_symbol_trade_state(
state,
symbol,
symbol_state,
trend_universe=TREND_UNIVERSE,
retired_positions_key=RETIRED_TREND_POSITIONS_KEY,
)
def should_skip_duplicate_trend_action(state, symbol, action, action_date):
return ts_should_skip_duplicate_trend_action(
state,
symbol,
action,
action_date,
action_history_key=TREND_POOL_ACTION_HISTORY_KEY,
)
def record_trend_action(state, symbol, action, action_date):
ts_record_trend_action(
state,
symbol,
action,
action_date,
action_history_key=TREND_POOL_ACTION_HISTORY_KEY,
)
# ==========================================
# 1. State persistence and Telegram
# ==========================================
def get_trade_state(normalize=True):
return infra_load_runtime_trade_state(
normalize_fn=normalize_trade_state,
default_state_factory=build_default_state,
normalize=normalize,
)
def set_trade_state(data):
infra_save_runtime_trade_state(
data,
normalize_fn=normalize_trade_state,
)
def append_log(log_buffer, message):
if log_buffer is not None:
log_buffer.append(str(message))
def send_tg_msg(token, chat_id, text):
live_send_tg_msg(token, chat_id, text)
# ==========================================
# 2. Earn and balance helpers
# ==========================================
def get_total_balance(client, asset, log_buffer=None):
"""Total balance for asset (spot + flexible earn)."""
return qpk_get_total_balance(
client,
asset,
on_spot_error=lambda exc: append_log(log_buffer, t("spot_balance_lookup_failed", asset=asset, error=exc)),
on_earn_error=lambda exc: append_log(log_buffer, t("earn_balance_lookup_failed", asset=asset, error=exc)),
balance_error_cls=BalanceFetchError,
)
def log_and_notify(log_buffer, tg_token, tg_chat_id, text):
append_log(log_buffer, text)
send_tg_msg(tg_token, tg_chat_id, text)
def ensure_asset_available(client, asset, required_amount, tg_token, tg_chat_id):
"""Redeem from flexible earn if spot balance is below required amount."""
return qpk_ensure_asset_available(
client,
asset,
required_amount,
on_redeem=lambda amount: send_tg_msg(
tg_token,
tg_chat_id,
t("execution_spot_short_redeeming_from_earn", asset=asset, amount=amount),
),
on_error=lambda exc: send_tg_msg(
tg_token,
tg_chat_id,
t("execution_redeem_failed_asset", asset=asset, error=exc),
),
sleep_fn=time.sleep,
)
def manage_usdt_earn_buffer(client, target_buffer, tg_token, tg_chat_id, log_buffer):
"""Keep USDT spot buffer near target by subscribing/redeeming flexible earn."""
qpk_manage_usdt_earn_buffer(
client,
target_buffer,
on_subscribe=lambda amount: append_log(log_buffer, t("cash_manager_subscribed_to_earn", amount=amount)),
on_redeem=lambda amount: append_log(log_buffer, t("cash_manager_redeeming_to_spot", amount=amount)),
on_error=lambda exc: append_log(log_buffer, t("usdt_earn_buffer_maintenance_failed", error=exc)),
)
def format_qty(client, symbol, qty):
"""Round quantity to exchange LOT_SIZE to avoid filter errors."""
return qpk_format_qty(client, symbol, qty)
def get_periodic_report_bucket(now_utc, interval_hours):
return report_get_periodic_report_bucket(now_utc, interval_hours)
def build_btc_manual_hint(btc_snapshot):
return report_build_btc_manual_hint(btc_snapshot, translate_fn=t)
def maybe_send_periodic_btc_status_report(
state,
tg_token,
tg_chat_id,
now_utc,
interval_hours,
total_equity,
trend_holdings_equity,
trend_daily_pnl,
btc_price,
btc_snapshot,
btc_target_ratio,
strategy_display_name=None,
notifier_fn=None,
):
resolved_strategy_display_name = strategy_display_name or build_strategy_display_name(t)(
getattr(STRATEGY_RUNTIME, "profile", "crypto_leader_rotation"),
fallback_name="Crypto Leader Rotation",
)
return report_maybe_send_periodic_btc_status_report(
state,
tg_token,
tg_chat_id,
now_utc,
interval_hours,
total_equity,
trend_holdings_equity,
trend_daily_pnl,
btc_price,
btc_snapshot,
btc_target_ratio,
resolved_strategy_display_name,
translate_fn=t,
separator=SEPARATOR,
notifier_fn=notifier_fn,
send_tg_msg_fn=send_tg_msg,
)
def fetch_daily_indicators(client, symbol, lookback_days=420):
"""Daily indicators for one symbol (rotation and risk)."""
return qpk_fetch_daily_indicators(client, symbol, lookback_days=lookback_days)
def fetch_btc_market_snapshot(client, btc_price, lookback_days=700, log_buffer=None):
"""Single BTC daily series for DCA and trend gate."""
return qpk_fetch_btc_market_snapshot(
client,
btc_price,
lookback_days=lookback_days,
on_fetch_error=lambda exc: log_buffer.append(t("btc_daily_fetch_failed", error=exc)) if log_buffer is not None else None,
on_empty=lambda: log_buffer.append(t("btc_daily_data_empty")) if log_buffer is not None else None,
on_insufficient=lambda length, last_time: log_buffer.append(
t("btc_data_insufficient", length=length, last_time=last_time)
)
if log_buffer is not None
else None,
)
def resolve_runtime_trend_pool(runtime, raw_state):
return app_resolve_runtime_trend_pool(
runtime,
raw_state,
load_trend_universe_from_live_pool_fn=load_trend_universe_from_live_pool,
get_trend_pool_contract_settings_fn=get_trend_pool_contract_settings,
validate_trend_pool_payload_fn=validate_trend_pool_payload,
build_trend_pool_resolution_fn=build_trend_pool_resolution,
translate_fn=t,
)
def resolve_runtime_btc_snapshot(runtime, btc_price, log_buffer):
return infra_resolve_runtime_btc_snapshot(
runtime,
btc_price,
log_buffer,
fetch_btc_market_snapshot_fn=fetch_btc_market_snapshot,
)
def resolve_runtime_trend_indicators(runtime):
return infra_resolve_runtime_trend_indicators(
runtime,
TREND_UNIVERSE,
fetch_daily_indicators_fn=fetch_daily_indicators,
)
def ensure_asset_available_runtime(runtime, report, asset, required_amount, log_buffer):
return infra_ensure_asset_available_runtime(
runtime,
report,
asset,
required_amount,
log_buffer,
runtime_call_client_fn=runtime_call_client,
append_log_fn=append_log,
runtime_notify_fn=runtime_notify,
translate_fn=t,
sleep_fn=time.sleep,
)
def manage_usdt_earn_buffer_runtime(runtime, report, target_buffer, log_buffer, spot_free_override=None):
infra_manage_usdt_earn_buffer_runtime(
runtime,
report,
target_buffer,
log_buffer,
runtime_call_client_fn=runtime_call_client,
append_log_fn=append_log,
translate_fn=t,
spot_free_override=spot_free_override,
)
def get_tradable_qty(symbol, total_qty, prices, min_bnb_value):
"""Reserve BNB for fees; rest is tradable."""
if symbol != "BNBUSDT":
return max(0.0, total_qty)
bnb_price = prices.get("BNBUSDT", 0.0)
if bnb_price <= 0:
return 0.0
reserve_qty = (min_bnb_value * 1.2) / bnb_price
return max(0.0, total_qty - reserve_qty)
# ==========================================
# 3. Core strategy
# ==========================================
def build_live_runtime(now_utc=None):
return rc_build_live_runtime(
now_utc=now_utc,
state_loader=get_trade_state,
state_writer=set_trade_state,
notifier=lambda **kwargs: send_tg_msg(kwargs["token"], kwargs["chat_id"], kwargs["text"]),
)
def _set_runtime_trend_universe(resolved_trend_universe):
global TREND_UNIVERSE
TREND_UNIVERSE = resolved_trend_universe
def _ensure_runtime_client(runtime, report):
return infra_ensure_runtime_client(
runtime,
report,
connect_client_fn=qpk_connect_client,
append_report_error_fn=append_report_error,
runtime_notify_fn=runtime_notify,
translate_fn=t,
sleep_fn=time.sleep,
)
def _load_cycle_state(runtime, report, allow_new_trend_entries_on_degraded):
return app_load_cycle_state(
runtime,
report,
allow_new_trend_entries_on_degraded,
state_loader=runtime.state_loader,
resolve_runtime_trend_pool=resolve_runtime_trend_pool,
normalize_trade_state=normalize_trade_state,
update_trend_pool_state=update_trend_pool_state,
runtime_set_trade_state=runtime_set_trade_state,
get_runtime_trend_universe=get_runtime_trend_universe,
append_report_error=append_report_error,
trend_universe_setter=_set_runtime_trend_universe,
)
def _append_trend_pool_source_logs(log_buffer, trend_pool_resolution, allow_new_trend_entries):
app_append_trend_pool_source_logs(
log_buffer,
trend_pool_resolution,
allow_new_trend_entries,
formatter=dm_format_trend_pool_source_logs,
append_log_fn=append_log,
)
def _capture_market_snapshot(runtime, report, runtime_trend_universe, log_buffer, min_bnb_value, buy_bnb_amount):
return ms_capture_market_snapshot(
runtime,
report,
runtime_trend_universe,
log_buffer,
min_bnb_value,
buy_bnb_amount,
get_total_balance_fn=get_total_balance,
ensure_asset_available_fn=ensure_asset_available_runtime,
runtime_call_client_fn=runtime_call_client,
runtime_notify_fn=runtime_notify,
append_log_fn=append_log,
resolve_btc_snapshot_fn=resolve_runtime_btc_snapshot,
resolve_trend_indicators_fn=resolve_runtime_trend_indicators,
bnb_fuel_symbol=BNB_FUEL_SYMBOL,
bnb_fuel_asset=BNB_FUEL_ASSET,
)
def _resolve_strategy_evaluation(
runtime,
state,
runtime_trend_universe,
trend_indicators,
btc_snapshot,
prices,
balances,
u_total,
fuel_val,
*,
allow_new_trend_entries=True,
allow_pool_refresh=True,
):
account_metrics = STRATEGY_RUNTIME.compute_account_metrics(
runtime_trend_universe,
balances,
prices,
u_total,
fuel_val,
)
return STRATEGY_RUNTIME.evaluate(
prices=prices,
trend_indicators=trend_indicators,
btc_snapshot=btc_snapshot,
account_metrics=account_metrics,
trend_universe_symbols=tuple(runtime_trend_universe.keys()),
state=state,
translator=t,
balances=balances,
now_utc=runtime.now_utc,
allow_new_trend_entries=allow_new_trend_entries,
allow_rotation_refresh=allow_pool_refresh,
get_symbol_trade_state_fn=get_symbol_trade_state,
set_symbol_trade_state_fn=set_symbol_trade_state,
)
def _resolve_strategy_plan(
runtime,
state,
runtime_trend_universe,
trend_indicators,
btc_snapshot,
prices,
balances,
u_total,
fuel_val,
*,
allow_new_trend_entries,
allow_pool_refresh,
):
evaluation = _resolve_strategy_evaluation(
runtime,
state,
runtime_trend_universe,
trend_indicators,
btc_snapshot,
prices,
balances,
u_total,
fuel_val,
allow_new_trend_entries=allow_new_trend_entries,
allow_pool_refresh=allow_pool_refresh,
)
strategy_plan = map_decision_to_rotation_plan(evaluation.decision)
strategy_plan["allocation"] = map_decision_to_allocation(
evaluation.decision,
account_metrics=evaluation.account_metrics,
)
strategy_plan["decision"] = evaluation.decision
return strategy_plan
def _compute_portfolio_allocation(runtime, runtime_trend_universe, balances, prices, u_total, fuel_val, state, trend_indicators, btc_snapshot):
evaluation = _resolve_strategy_evaluation(
runtime,
state,
runtime_trend_universe,
trend_indicators,
btc_snapshot,
prices,
balances,
u_total,
fuel_val,
)
return map_decision_to_allocation(
evaluation.decision,
account_metrics=evaluation.account_metrics,
)
def _build_balance_snapshot(runtime_trend_universe, balances, u_total):
return app_build_balance_snapshot(runtime_trend_universe, balances, u_total)
def _maybe_reset_daily_state(state, runtime, report, today_utc, total_equity, trend_val_equity):
return app_maybe_reset_daily_state(
state,
runtime,
report,
today_utc,
total_equity,
trend_val_equity,
runtime_set_trade_state_fn=runtime_set_trade_state,
)
def _maybe_rebase_daily_state_for_balance_change(
state,
runtime,
report,
total_equity,
trend_val_equity,
current_balance_snapshot,
log_buffer,
):
return app_maybe_rebase_daily_state_for_balance_change(
state,
runtime,
report,
total_equity,
trend_val_equity,
current_balance_snapshot,
log_buffer,
runtime_set_trade_state_fn=runtime_set_trade_state,
append_log_fn=append_log,
translate_fn=t,
)
def _compute_daily_pnls(state, total_equity, trend_equity):
return app_compute_daily_pnls(state, total_equity, trend_equity)
def _append_portfolio_report(log_buffer, allocation, fuel_val, daily_pnl, trend_daily_pnl, btc_snapshot):
return app_append_portfolio_report(
log_buffer,
allocation,
fuel_val,
daily_pnl,
trend_daily_pnl,
btc_snapshot,
append_portfolio_report_fn=report_append_portfolio_report,
append_log_fn=append_log,
translate_fn=t,
separator="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
)
def _run_daily_circuit_breaker(
runtime,
report,
state,
runtime_trend_universe,
balances,
u_total,
prices,
trend_daily_pnl,
circuit_breaker_pct,
log_buffer,
):
return app_run_daily_circuit_breaker(
runtime,
report,
state,
runtime_trend_universe,
balances,
u_total,
prices,
trend_daily_pnl,
circuit_breaker_pct,
log_buffer,
format_qty_fn=format_qty,
runtime_notify_fn=runtime_notify,
ensure_asset_available_fn=ensure_asset_available_runtime,
runtime_call_client_fn=runtime_call_client,
set_symbol_trade_state_fn=set_symbol_trade_state,
runtime_set_trade_state_fn=runtime_set_trade_state,
build_balance_snapshot_fn=_build_balance_snapshot,
translate_fn=t,
)
def _append_rotation_summary(log_buffer, official_trend_pool, active_trend_pool, selected_candidates):
return report_append_rotation_summary(
log_buffer,
official_trend_pool,
active_trend_pool,
selected_candidates,
append_log_fn=append_log,
translate_fn=t,
)
def _execute_trend_sells(
runtime,
report,
state,
runtime_trend_universe,
sell_reasons,
prices,
balances,
u_total,
log_buffer,
today_id_str,
):
return app_execute_trend_sells(
runtime,
report,
state,
runtime_trend_universe,
sell_reasons,
prices,
balances,
u_total,
log_buffer,
today_id_str,
should_skip_duplicate_trend_action_fn=should_skip_duplicate_trend_action,
append_log_fn=append_log,
translate_fn=t,
format_qty_fn=format_qty,
ensure_asset_available_fn=ensure_asset_available_runtime,
runtime_call_client_fn=runtime_call_client,
next_order_id_fn=next_order_id,
set_symbol_trade_state_fn=set_symbol_trade_state,
record_trend_action_fn=record_trend_action,
runtime_set_trade_state_fn=runtime_set_trade_state,
runtime_notify_fn=runtime_notify,
)
def _execute_trend_buys(
runtime,
report,
state,
selected_candidates,
eligible_buy_symbols,
planned_trend_buys,
prices,
balances,
u_total,
log_buffer,
today_id_str,
):
return app_execute_trend_buys(
runtime,
report,
state,
selected_candidates,
eligible_buy_symbols,
planned_trend_buys,
prices,
balances,
u_total,
log_buffer,
today_id_str,
should_skip_duplicate_trend_action_fn=should_skip_duplicate_trend_action,
append_log_fn=append_log,
translate_fn=t,
format_qty_fn=format_qty,
ensure_asset_available_fn=ensure_asset_available_runtime,
runtime_call_client_fn=runtime_call_client,
next_order_id_fn=next_order_id,
set_symbol_trade_state_fn=set_symbol_trade_state,
record_trend_action_fn=record_trend_action,
runtime_set_trade_state_fn=runtime_set_trade_state,
runtime_notify_fn=runtime_notify,
)
def _append_trend_symbol_status(log_buffer, runtime_trend_universe, prices, trend_indicators, state, btc_snapshot):
return report_append_trend_symbol_status(
log_buffer,
runtime_trend_universe,
prices,
trend_indicators,
state,
btc_snapshot,
append_log_fn=append_log,
translate_fn=t,
get_symbol_trade_state_fn=get_symbol_trade_state,
)
def _execute_trend_rotation(
runtime,
report,
state,
runtime_trend_universe,
trend_indicators,
btc_snapshot,
prices,
balances,
u_total,
fuel_val,
log_buffer,
today_id_str,
allow_new_trend_entries,
allow_pool_refresh,
):
return app_execute_trend_rotation(
runtime,
report,
state,