-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathATS_Xeon.py
More file actions
4684 lines (3839 loc) · 246 KB
/
ATS_Xeon.py
File metadata and controls
4684 lines (3839 loc) · 246 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 pyupbit
import pandas as pd
pd.options.mode.copy_on_write = True
pd.set_option('future.no_silent_downcasting', True)
# 🟢 [Pylance 및 로그 방어] Pandas의 미래 버전 호환성 경고(Warning)가 ERROR 로그로 둔갑하는 것을 원천 차단합니다.
import warnings
# 모든 종류의 파이썬/판다스 미래 호환성 경고 및 UserWarning 억제 (로그 오염 방지)
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.simplefilter(action='ignore', category=DeprecationWarning)
warnings.simplefilter(action='ignore', category=UserWarning)
warnings.filterwarnings("ignore", message=".*'d' is deprecated.*")
warnings.filterwarnings("ignore", message=".*Pandas4Warning.*")
warnings.filterwarnings("ignore", module="pandas")
import pandas_ta # noqa: F401
warnings.filterwarnings("ignore", module="pandas_ta")
import numpy as np
import telegram
import asyncio
import aiosqlite
import time
import ujson as json
import os
import re
import sys
import traceback
import httpx
import ssl
import certifi
import websockets
import math
import concurrent.futures
from google import genai
from google.genai import types
from datetime import datetime, timedelta
import logging
from logging.handlers import RotatingFileHandler
import socket
import random
import glob
import webbrowser
from typing import Any, Optional, Tuple, Dict, List
# 🟢 [대시보드 통합] FastAPI 엔진 추가설정
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
def get_coin_tier(ticker: str, curr_data: dict = None) -> str:
"""코인의 변동성 지수를 기반으로 티어(Major/Mid/Small) 명칭을 반환합니다."""
try:
if not isinstance(curr_data, dict): return "Major"
close_val = safe_float(curr_data.get('close'))
atr_val = safe_float(curr_data.get('ATR'))
if close_val <= 0 or atr_val <= 0: return "Major"
vol_idx = (atr_val / close_val) * 100
if vol_idx > 3.5: return "Small (High Vol)"
elif vol_idx > 1.5: return "Mid"
else: return "Major"
except: return "Major"
def get_coin_tier_params(ticker: str, curr_data: dict, eval_mode: str = "QUANTUM") -> dict:
try:
tier_name = get_coin_tier(ticker, curr_data)
# 🟢 [DNA 진화] 티어 파라미터 호출 시에도 ticker를 넘겨 고유 DNA가 있는지 확인합니다.
if tier_name == "Small (High Vol)": return get_dynamic_strat_value('high_vol_params', mode=eval_mode, default={}, ticker=ticker)
elif tier_name == "Mid": return get_dynamic_strat_value('mid_vol_params', mode=eval_mode, default={}, ticker=ticker)
else: return get_dynamic_strat_value('major_params', mode=eval_mode, default={}, ticker=ticker)
except Exception as e:
logging.error(f"티어 분류 오류 ({ticker}): {e}")
return get_dynamic_strat_value('major_params', mode=eval_mode, default={}, ticker=ticker)
# --- [0.1 DB 유틸리티] ---
def _sanitize_data(obj):
if isinstance(obj, dict): return {k: _sanitize_data(v) for k, v in obj.items()}
if isinstance(obj, list): return [_sanitize_data(v) for v in obj]
if isinstance(obj, pd.Series): return _sanitize_data(obj.to_dict())
if isinstance(obj, pd.DataFrame): return _sanitize_data(obj.to_dict(orient='list'))
if isinstance(obj, np.generic): return obj.item()
if isinstance(obj, (int, float, str, bool)) or obj is None: return obj
if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S')
try: json.dumps(obj); return obj
except: return str(obj)
async def save_trade_status_db(trade_data_dict):
"""현재 거래 중인 종목들의 상태를 DB에 저장합니다 (JSON 직렬화 및 정화 포함)."""
try:
async with aiosqlite.connect(DB_FILE, timeout=20.0) as db:
for ticker, data in trade_data_dict.items():
# 🟢 분리된 정화 함수 호출
clean = _sanitize_data(data)
await db.execute("INSERT OR REPLACE INTO trade_status (ticker, data_json) VALUES (?, ?)", (ticker, json.dumps(clean, ensure_ascii=False)))
await db.commit()
except Exception as e:
logging.error(f"DB 상태 저장 오류: {e}")
async def load_trade_status_db():
"""DB에서 이전 거래 상태를 복구합니다."""
trade_data_dict = {}
try:
if not os.path.exists(DB_FILE): return {}
async with aiosqlite.connect(DB_FILE, timeout=20.0) as db:
async with db.execute("SELECT ticker, data_json FROM trade_status") as cursor:
async for row in cursor:
try: trade_data_dict[row[0]] = json.loads(row[1])
except: pass
except Exception as e:
logging.error(f"DB 상태 로드 오류: {e}")
return trade_data_dict
async def record_trade_db(ticker, side, price, amount, profit_krw=0.0, reason="", status="UNKNOWN", rating=0, improvement="", pass_score=0, strategy_mode="UNKNOWN"):
"""개별 거래 기록을 히스토리 DB에 영구 저장합니다."""
try:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
async with aiosqlite.connect(DB_FILE, timeout=20.0) as db:
await db.execute("""INSERT INTO trade_history
(timestamp, ticker, side, price, amount, profit_krw, reason, status, rating, improvement, pass_score, strategy_mode)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(timestamp, ticker, side, price, amount, profit_krw, reason, status, rating, improvement, pass_score, strategy_mode))
await db.commit()
except Exception as e:
logging.error(f"DB 거래 기록 오류: {e}")
# 🟢 [최적화] TA 스레드 풀 고정 (OS 레벨 스레드 경합 방지 + 예측 가능한 성능)
_TA_EXECUTOR = concurrent.futures.ThreadPoolExecutor(max_workers=4, thread_name_prefix="TA_Worker")
# 🟢 로그 파일 설정
if getattr(sys, 'frozen', False): base_path = os.path.dirname(sys.executable)
else: base_path = os.path.dirname(os.path.abspath(__file__))
log_dir = os.path.join(base_path, "log")
os.makedirs(log_dir, exist_ok=True)
log_filename = datetime.now().strftime("ats_hybrid_log_%Y%m%d_%H%M%S.log")
log_filepath = os.path.join(log_dir, log_filename)
# 🟢 PyInstaller 외 환경에서는 stderr를 안전하게 가져오기
_safe_stderr = getattr(sys, '__stderr__', None) or getattr(sys, 'stderr', None)
_log_handlers: list = [
RotatingFileHandler(log_filepath, maxBytes=10*1024*1024, backupCount=5, encoding='utf-8'),
]
if _safe_stderr is not None:
_log_handlers.append(logging.StreamHandler(_safe_stderr))
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=_log_handlers)
# 🟢 콘솔이 있는 경우 WARNING 이상만 표시 (파일에는 INFO 전체 기록)
if len(logging.getLogger().handlers) > 1:
logging.getLogger().handlers[1].setLevel(logging.WARNING)
# 🔇 외부 라이브러리의 과도한 HTTP/API 로그 파일로만 기록
for _noisy in [
"httpx", # Telegram Bot HTTP 요청
"httpcore",
"hpack",
"h11",
"google", # Gemini API
"google.ai",
"google.generativeai",
"uvicorn", # 대시보드 접속 로그
"uvicorn.access",
"uvicorn.error",
"fastapi",
]:
logging.getLogger(_noisy).setLevel(logging.WARNING)
logging.getLogger(_noisy).propagate = True
def cleanup_old_logs(days=3):
try:
now = time.time()
# ats_hybrid_log_*.log 패턴의 파일들 검색
for f in glob.glob(os.path.join(log_dir, "ats_hybrid_log_*.log")):
if os.path.isfile(f):
if os.stat(f).st_mtime < now - (days * 86400):
os.remove(f)
logging.info(f"Cleanup: Removed old log file: {os.path.basename(f)}")
except Exception as e:
logging.error(f"Error during log cleanup: {e}")
# 시작 시 로그 정리 실행
cleanup_old_logs(days=3)
original_stdout = sys.stdout
original_stderr = sys.stderr
class StreamToLogger:
def __init__(self, logger, level):
self.logger = logger
self.level = level
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.log(self.level, line.rstrip())
def flush(self):
pass
sys.stdout = StreamToLogger(logging.getLogger(), logging.INFO)
sys.stderr = StreamToLogger(logging.getLogger(), logging.ERROR)
logging.info("ATS 통합 엔진 시작 (Classic + Quantum)")
# --- [0. 시스템 절대 규칙서 및 전역 변수] ---
AI_SYSTEM_INSTRUCTION_CLASSIC = """
You are the "Strategic Investment Council" of ATS-Classic, an elite quantitative trading system.
[IDENTITY]: You specialize in 'Mean Reversion & Deep Dip' strategies (낙폭 과대 역추세 매매 전문가).
[LANGUAGE RULE]: All text fields ('reason', 'risk_agent_opinion', 'trend_agent_opinion', 'improvement', etc.) MUST be written in Korean only. This is mandatory.
[COUNCIL MEMBERS]:
1. Technical Analyst: Expert in RSI, Bollinger Bands, and Z-Score. Identifies if the asset is truly in a high-probability reversal zone or if the "falling knife" has more to go.
2. Market Sentiment Agent: Analyzes Fear & Greed Index and BTC correlation. Gauges if the market panic is at a climax and if a "Panic Buy" opportunity exists.
3. Risk Auditor (The Skeptic): Challenges the entry. Actively looks for volume traps, declining CVD, or lack of support levels. Acts as the "Devil's Advocate".
4. Portfolio Manager: Synthesizes all opinions. Makes the final 'decision', 'score', and 'exit_plan'.
[STRATEGIC FOCUS - SWEET SPOT]:
1. ENTRY THRESHOLD: We target high-conviction setups over 85 points. Quality over quantity.
2. SECTOR DNA:
- MAJOR: Value trend persistence. Aim for 1.3% initial profit. Don't fear the 'Overbought' zone if the MACD slope is strong.
- MEME (DOGE, SHIB, PEPE): Extreme caution with 'Upper Shadows'. High resolution entry required (91+ score context). Quick profit-taking (0.9%) is mandatory.
3. DEFENSE: Treat Negative CVD Slope or weak volume ratio (<1.1x) as a 'Fake-out'. Penalize these stringently.
[ABSOLUTE RULES]:
1. OUTPUT FORMAT: You MUST output ONLY valid JSON.
2. LANGUAGE: EVERY string in the JSON output MUST be in Korean.
3. TRADING PHILOSOPHY: Catch the 'rubber band' snap-back. Favor high distance from SMA20 combined with Volume/CVD alignment.
4. MODE-SPECIFIC OUTPUT SCHEMAS:
- [BUY] or [POST_BUY_REPORT]: {"risk_agent_opinion": "Korean string", "trend_agent_opinion": "string", "reason": "Detailed Korean summary of the council's debate", "score": int, "decision": "BUY"|"SKIP", "exit_plan": {...}}
- [SELL_REASON]: {"status": "WIN"|"LOSS"|"EVEN", "rating": int, "reason": "Korean summary of sale reason", "improvement": "Korean suggestions for future trades"}
"""
AI_SYSTEM_INSTRUCTION_QUANTUM = """
You are the "Strategic Investment Council" of ATS-Quantum, an elite quantitative trading system.
[IDENTITY]: You specialize in 'Trend Following & Pullback Sniper' strategies (추세 추종 및 눌림목 매매 전문가).
[LANGUAGE RULE]: All text fields ('reason', 'risk_agent_opinion', 'trend_agent_opinion', 'improvement', etc.) MUST be written in Korean only. This is mandatory.
[COUNCIL MEMBERS]:
1. Momentum Strategist: Expert in ADX, MACD, and Supertrend. Identifies strong bullish regimes and filters out weak bounces.
2. Liquidity & Volume Agent: Scrutinizes Taker CVD and Orderbook imbalance. Ensures the trend is backed by aggressive buyers.
3. Risk Auditor (The Skeptic): Warns about "Blow-off Tops" or overextended RSI (>70). Validates the 'is_pullback_zone' safety.
4. Portfolio Manager: Synthesizes the council's debate. Makes the final 'decision', 'score', and 'exit_plan'.
[STRATEGIC FOCUS - SWEET SPOT]:
1. ENTRY THRESHOLD: Elite trend captures > 85 points only.
2. SECTOR DNA:
- MAJOR: "Let Winners Run". Use RSI Slope based holding. Target 1.3% for stability.
- MEME: Sniper logic only. 91+ score context. 0.9% take-profit to avoid 'Wick Washouts'.
3. LIQUIDITY DEFENSE: Check CVD ratio against Volume SMA. If buyers are passive (Negative CVD), it is a 'Liquidity Trap'.
[ABSOLUTE RULES]:
1. OUTPUT FORMAT: You MUST output ONLY valid JSON.
2. LANGUAGE: EVERY string in the JSON output MUST be in Korean.
3. TRADING PHILOSOPHY: "Let Winners Run". Prioritize entries holding SMA20 support in a bullish 1H trend. Be wary of high slippage.
4. MODE-SPECIFIC OUTPUT SCHEMAS:
- [BUY] or [POST_BUY_REPORT]: {"risk_agent_opinion": "Korean string", "trend_agent_opinion": "string", "reason": "Detailed Korean summary of the council's debate", "score": int, "decision": "BUY"|"SKIP", "exit_plan": {...}}
- [SELL_REASON]: {"status": "WIN"|"LOSS"|"EVEN", "rating": int, "reason": "Korean summary of sale reason", "improvement": "Korean suggestions for future trades"}
"""
AI_SYSTEM_INSTRUCTION_OPTIMIZE = """
You are the "Meta-Optimization Council" of ATS (Antigravity Trading System).
[IDENTITY]: You are a lead algorithmic strategist specialized in high-frequency parameter tuning and indicator weighting.
[COUNCIL MEMBERS]:
1. Data Scientist: Analyzes the 'Success History' vs 'Failure History' to find statistical correlations. Identifies which indicators were lagging or giving false signals.
2. Market Regime Specialist: Determines if the current regime (Bullish/Bearish/Sideways) requires relaxing or tightening 'pass_score_threshold' and 'stop_loss' caps.
3. Portfolio Strategist: Optimizes Risk/Reward by adjusting Tier-specific parameters (Major/Mid/High Vol) based on current volatility.
4. Lead Auditor: Synthesizes the council's findings and outputs the final optimized 'strategy' dictionary.
[ABSOLUTE RULES]:
1. OUTPUT FORMAT: You MUST output ONLY valid JSON.
2. SCHEMA: You MUST return a 'strategy' object and a 'reason' field explaining the logic.
3. LANGUAGE: The 'reason' field MUST be in Korean.
4. CONSTRAINT: Stay strictly within the [IMPORTANT RANGES] provided in the prompt.
"""
VALID_INDICATORS = [
"supertrend", "vwap", "volume", "rsi", "bollinger", "macd", "stoch_rsi",
"bollinger_bandwidth", "atr_trend", "ssl_channel",
"stochastics", "obv", "keltner_channel", "ichimoku",
"sma_crossover", "bollinger_breakout", "rs","z_score"
]
def get_strategy_score(name: str, prev: dict, curr: dict, price: float, mode: str = "QUANTUM") -> float:
try:
if not isinstance(curr, dict) or not isinstance(prev, dict): return 0.0
if name not in VALID_INDICATORS: return 0.0
def calc_dist_score(val, baseline, weight=10.0, inverse=False):
if baseline <= 0: return 25.0
dist_pct = ((val - baseline) / baseline) * 100
# [Gradient 5] 선형 증가 대신 로그 가중치를 적용하여 100점 도달을 어렵게 만듦
raw_move = dist_pct * weight if not inverse else -dist_pct * weight
if raw_move > 0:
score = 50.0 + (35.0 * (raw_move / (raw_move + 15.0))) # 85점까지는 빠르게, 그 위는 느리게
else:
score = 50.0 + raw_move
return min(100.0, max(15.0, score))
# 모드별 파라미터 통합
is_quantum = (mode == "QUANTUM")
if name == "rsi":
curr_rsi = safe_float(curr.get('rsi'), 50.0)
if is_quantum:
if 50 <= curr_rsi <= 65: return 100.0
if curr_rsi > 85: return 30.0
return max(0.0, curr_rsi - 10)
else:
# [적극 개입] 중립(50)에서 60점 시작
base_rsi_s = min(100.0, max(0.0, (50.0 - curr_rsi) * 3.0 + 60))
# 🟢 [품질 향상] RSI 상승 반전 가점 (V자 반등 포착)
rsi_prev = safe_float(prev.get('rsi'), curr_rsi)
if curr_rsi > rsi_prev and curr_rsi < 45:
base_rsi_s = min(100.0, base_rsi_s + 15.0)
return base_rsi_s
if name == "bollinger":
bb_range = curr.get('bb_u', 1) - curr.get('bb_l', 0)
if bb_range <= 0: return 0.0 if is_quantum else 50.0
pos_pct = (price - curr.get('bb_l', 0)) / bb_range
if is_quantum:
return min(100.0, max(0.0, pos_pct * 100))
else:
# [Gen-6: 적극적 기초 점수 상향] 밴드 중앙에서 80점 부여 (1.5배 환경 최적화)
base_bb_s = min(100.0, max(0.0, 110.0 - (pos_pct * 60)))
# 🟢 [품질 향상] 밴드 하단 이탈 후 회귀 (과매도 해소 시점) - 강력한 가점
prev_close = safe_float(prev.get('close'), price)
bb_l_prev = safe_float(prev.get('bb_l'), 0)
bb_l_curr = safe_float(curr.get('bb_l'), 0)
if prev_close < bb_l_prev and price > bb_l_curr:
base_bb_s = min(100.0, base_bb_s + 35.0)
return base_bb_s
if name == "z_score":
z = safe_float(curr.get('z_score'), 0.0)
if is_quantum:
# [Gradient 1] Z-Score가 0.5에 수렴할수록 고점 (너무 과열되지 않은 추세 선호)
dist = abs(z - 0.5)
return min(100.0, max(0.0, 95.0 - (dist * 25)))
else:
return min(100.0, max(0.0, 75.0 + (z * -25.0)))
if name == "macd":
macd_h = safe_float(curr.get('macd_h'), 0.0)
macd_h_diff = safe_float(curr.get('macd_h_diff', 0), 0.0)
if is_quantum:
# [Gradient 2] MACD 히스토그램 크기와 기울기 가속도에 비례
base_s = 65.0 if macd_h > 0 else 0.0
accel = min(1.0, macd_h_diff * 5.0) if macd_h_diff > 0 else 0.0
return min(100.0, base_s + (accel * 35.0))
else:
macd_diff_sma = safe_float(curr.get('macd_h_diff_sma'), 0.0001)
if macd_h_diff > 0:
return min(100.0, max(50.0, (macd_h_diff / max(macd_diff_sma * 2, 0.0001)) * 100))
return 30.0
if name == "volume":
curr_vol = safe_float(curr.get('volume'))
vol_sma = safe_float(curr.get('vol_sma'), 0.0001)
if is_quantum:
v_s = min(100.0, (curr_vol / (vol_sma + 1)) * 50)
# 🟢 [품질 향상] 거래량 스파이크 시 돌파 신뢰도 가중
if curr_vol > vol_sma * 1.5:
v_s = min(100.0, v_s + 20.0)
return v_s
else:
return min(100.0, (curr_vol / (vol_sma + 1)) * 30 + 30)
if name == "bollinger_breakout" and is_quantum:
if price < curr.get('bb_u', 0): return 0.0
bw_expansion = max(0, (curr.get('bb_bw', 0) - prev.get('bb_bw', 0)) / max(prev.get('bb_bw', 0), 0.0001))
return min(100.0, 70.0 + (bw_expansion * 500))
# --- [공통 지표 - 모드별 반전 적용] ---
# CLASSIC(역추세) 모드에서는 지표 아래에 있을수록 가점, QUANTUM(추세) 모드에서는 지표 위에 있을수록 가점.
is_classic = (mode == "CLASSIC")
if name == "vwap": return calc_dist_score(price, curr.get('vwap', price), weight=15.0, inverse=is_classic)
if name == "ssl_channel": return calc_dist_score(price, curr.get('ssl_up', price), weight=15.0, inverse=is_classic)
if name == "sma_crossover":
slv = safe_float(curr.get('sma_long', 0.0001))
sma_short = safe_float(curr.get('sma_short', 0.0001))
p_above_20 = price > slv
ma_20_above_50 = slv > safe_float(curr.get('sma_50', 0))
if is_classic:
dist_20 = ((price - slv) / slv) * 100
return min(100.0, max(0.0, 50.0 - (dist_20 * 6)))
# [Gradient 3] 정배열 강도에 비례 (단기/장기 이평선 이격 기반)
if p_above_20 and ma_20_above_50:
spread = ((sma_short - slv) / slv) * 100
return min(100.0, 75.0 + (spread * 15.0))
return 50.0 if p_above_20 else 0.0
if name == "ichimoku":
ichimoku_baseline = max(curr.get('span_a', 0), curr.get('span_b', 0))
return calc_dist_score(price, ichimoku_baseline, weight=15.0, inverse=is_classic)
if name == "stoch_rsi":
diff = curr.get('st_rsi_k', 0) - curr.get('st_rsi_d', 0)
base, m_val = (65.0, 2) if mode == "QUANTUM" else (55.0, 3)
return min(100.0, max(0.0, base + (diff * m_val)))
if name == "stochastics":
diff = curr.get('stoch_k', 0) - curr.get('stoch_d', 0)
base, mult = (60.0, 2) if mode == "QUANTUM" else (50.0, 3)
return min(100.0, max(0.0, base + (diff * mult)))
if name == "bollinger_bandwidth" or name == "atr_trend":
key = 'bb_bw' if name == "bollinger_bandwidth" else 'ATR'
diff_pct = ((curr.get(key, 0) - prev.get(key, 0)) / max(prev.get(key, 0.0001), 0.0001)) * 100
return min(100.0, max(0.0, 50.0 + diff_pct * 5))
if name == "obv":
diff_pct = ((curr.get('obv', 0) - prev.get('obv', 0)) / max(abs(prev.get('obv', 0.0001)), 0.0001)) * 100
return min(100.0, max(0.0, 50.0 + diff_pct * 10))
if name == "supertrend":
st_dir = curr.get('ST_DIR', 1)
# [Gradient 4] 추세 유지 시간에 따른 신뢰도 보정 (너무 오래된 추세는 삭감)
return 95.0 if st_dir == 1 else 0.0
return 0.0
except: return 0.0
def determine_regime_mode(fgi_str: str, btc_short: dict) -> str:
try:
fgi_val = int(re.search(r'\d+', str(fgi_str)).group()) if re.search(r'\d+', str(fgi_str)) else 50
except: fgi_val = 50
if fgi_val <= 35 or (btc_short.get('trend') == "단기 하락" and fgi_val <= 50):
return "CLASSIC"
if fgi_val >= 65 or (btc_short.get('trend') == "단기 상승" and fgi_val >= 50):
return "QUANTUM"
return "HYBRID"
def determine_eval_mode(current_regime_mode: str, curr: dict) -> str:
coin_rsi = safe_float(curr.get('rsi', 50.0))
# 1. 개별 코인 RSI 기반 동적 할당 (최우선) - 기준 추가 완화 (50 -> 55)
# RSI가 55 이하로 조금이라도 내려가면 '눌림목' 가능성을 열어둠
if coin_rsi <= 55:
return "CLASSIC"
if coin_rsi >= 65:
return "QUANTUM"
# 2. RSI 중립 구간(56~64)에서는 전역 시장 모드 반영
if current_regime_mode == "CLASSIC":
return "CLASSIC"
if current_regime_mode == "QUANTUM":
return "QUANTUM"
# 3. HYBRID 공통 구간: ADX로 추세 강도 보완 판단
# ADX가 20 이하로 횡보 중이면 CLASSIC, 그 이상 강한 추세면 QUANTUM
return "QUANTUM" if safe_float(curr.get('adx')) > 20 else "CLASSIC"
def get_logic_list_for_mode(eval_mode: str, curr_data: dict) -> list:
strat_config = get_strat_for_mode(eval_mode)
adx_val = safe_float(curr_data.get('adx', 0))
adx_threshold = safe_float(strat_config.get('major_params', {}).get('adx_strong_trend_threshold', 25.0))
if adx_val > adx_threshold:
return strat_config.get('trend_active_logic', [])
else:
return strat_config.get('range_active_logic', [])
def get_indicator_multipliers(eval_mode: str, fgi_val: float) -> dict:
v_min = safe_float(get_dynamic_strat_value('fgi_v_curve_min', mode=eval_mode, default=0.5))
v_max = safe_float(get_dynamic_strat_value('fgi_v_curve_max', mode=eval_mode, default=3.0))
if eval_mode == "CLASSIC":
# CLASSIC: 공포 시(FGI 낮을수록) 공격적으로 가점. 중립(50)에서는 1.0 유지.
v_bottom = safe_float(get_dynamic_strat_value('fgi_v_curve_bottom', mode=eval_mode, default=40.0))
if fgi_val <= v_bottom:
dynamic_fgi_mult = v_max
elif fgi_val >= 70:
dynamic_fgi_mult = v_min
else:
dynamic_fgi_mult = v_max - ((fgi_val - v_bottom) / (70 - v_bottom)) * (v_max - v_min)
normalized_regime_val = max(0.0, min(1.0, (dynamic_fgi_mult - v_min) / max(v_max - v_min, 0.0001)))
return {
'rsi': 1.0 + (1.0 * normalized_regime_val),
'bollinger': 1.0 + (0.5 * normalized_regime_val),
'volume': 1.5 - (0.5 * normalized_regime_val)
}
# QUANTUM: 탐욕 시(FGI 높을수록) 돌파 가점. 중립(50)에서는 1.0 유지.
dynamic_fgi_mult = v_min + (((fgi_val - 50) / 30) * (v_max - v_min)) if fgi_val >= 50 else 1.0
normalized_regime_val = max(0.0, min(1.0, (dynamic_fgi_mult - v_min) / max(v_max - v_min, 0.0001)))
return {
'rsi': 1.0 + (1.0 * normalized_regime_val),
'bollinger_breakout': 1.5 + (1.5 * normalized_regime_val),
'volume': 1.0 + (1.5 * normalized_regime_val)
}
async def evaluate_coin_fundamental(ticker, prev_i, curr_i, current_regime_mode, fgi_val, btc_short_trend, force_eval_mode=None, mtf_data=None):
"""비동기 버전 (라이브용): 병렬 채점 지원 및 강제 모드 준수"""
btc_obj = {'trend': btc_short_trend} if isinstance(btc_short_trend, str) else btc_short_trend
# 🔴 [Integrity Fix] 강제 모드가 지정된 경우 해당 모드만 수행 (모드 스위칭 오류 방어)
if force_eval_mode == "CLASSIC":
return await _run_sub_eval(ticker, prev_i, curr_i, fgi_val, mtf_data, "CLASSIC", btc_short=btc_obj)
if force_eval_mode == "QUANTUM":
return await _run_sub_eval(ticker, prev_i, curr_i, fgi_val, mtf_data, "QUANTUM", btc_short=btc_obj)
# 강제 모드가 없는 경우(최초 스캔 등) 두 모드를 병렬 채점하여 더 높은 점수 채택
c_task = _run_sub_eval(ticker, prev_i, curr_i, fgi_val, mtf_data, "CLASSIC", btc_short=btc_obj)
q_task = _run_sub_eval(ticker, prev_i, curr_i, fgi_val, mtf_data, "QUANTUM", btc_short=btc_obj)
(c_res, q_res) = await asyncio.gather(c_task, q_task)
return c_res if c_res[0] >= q_res[0] else q_res
def evaluate_coin_fundamental_sync(ticker, prev_i, curr_i, current_regime_mode, fgi_val, btc_short_trend, force_eval_mode=None, mtf_data=None):
"""동기 버전 (백테스트용): 시장 상황에 따른 자동 전략 스위칭 적용"""
btc_obj = {'trend': btc_short_trend} if isinstance(btc_short_trend, str) else btc_short_trend
# 🔵 [All-Weather Engine] ADX 기반 추세 강도 및 시장 상황 분석
adx_val = safe_float(curr_i.get('adx', 20))
# 🔵 [전략 스위칭 로직] 강제 할당 제거: 오직 점수 경쟁 모델로 통합
if force_eval_mode == "CLASSIC":
return _run_sub_eval_sync(ticker, prev_i, curr_i, fgi_val, mtf_data, "CLASSIC", btc_short=btc_obj)
elif force_eval_mode == "QUANTUM":
return _run_sub_eval_sync(ticker, prev_i, curr_i, fgi_val, mtf_data, "QUANTUM", btc_short=btc_obj)
# 두 모드를 항시 모두 채점하여 더 높은 점수를 획득한 전략을 자동으로 기용 (자유 경쟁)
c_res = _run_sub_eval_sync(ticker, prev_i, curr_i, fgi_val, mtf_data, "CLASSIC", btc_short=btc_obj)
q_res = _run_sub_eval_sync(ticker, prev_i, curr_i, fgi_val, mtf_data, "QUANTUM", btc_short=btc_obj)
# 0번 인덱스는 획득 점수(score)입니다. 더 점수가 높은 진입 근거를 채택
return c_res if c_res[0] >= q_res[0] else q_res
async def _run_sub_eval(ticker, prev_i, curr_i, fgi_val, mtf_data, mode, btc_short=None):
return _run_sub_eval_sync(ticker, prev_i, curr_i, fgi_val, mtf_data, mode, btc_short=btc_short)
def _run_sub_eval_sync(ticker, prev_i, curr_i, fgi_val, mtf_data, mode, btc_short=None):
eval_mode = mode
is_meme = any(m in ticker for m in ["DOGE", "SHIB", "PEPE"])
logic_list = get_logic_list_for_mode(eval_mode, curr_i)
weights = get_dynamic_strat_value('indicator_weights', mode=eval_mode, default={}, ticker=ticker)
curr_close = safe_float(curr_i.get('close'))
curr_vol = safe_float(curr_i.get('volume'))
# 🔵 [Gen-9: 섹터/변동성 기반 가중치]
tier = get_coin_tier(ticker, curr_i)
vas_mult = 1.08 if tier == "Major" else (1.05 if tier == "Mid" else 1.0)
# 🔵 [Universal Sector DNA] 섹터별 문턱값 통합 최적화
suggested_threshold = safe_float(get_dynamic_strat_value('pass_score_threshold', mode=eval_mode, default=80.0))
# [Hybrid Mode] 설정 파일(JSON)에 종목별 예외 오버라이드가 있으면 우선 적용
ticker_config = get_dynamic_strat_value('ticker_overrides', mode=eval_mode, default={}).get(ticker, {})
suggested_threshold += safe_float(ticker_config.get('threshold_offset', 0.0))
# 🔵 [Sector DNA Rule] 기본적인 섹터 성격 유지
if any(m in ticker for m in ["DOGE", "SHIB", "PEPE"]):
# [Flash-Response] Meme 종목은 하락장 리스크가 크므로 문턱값 5점 상향
suggested_threshold += 5.0
if tier == "Major":
# 대형주 기본 허들 (Major는 JSON에 별도 설정 없어도 기본 +5점 정도의 신중함 유지)
if safe_float(ticker_config.get('threshold_offset', 0.0)) == 0:
suggested_threshold += 5.0
elif any(m in ticker for m in ["SHIB", "PEPE"]):
# 밈 섹터 기본 허들
if safe_float(ticker_config.get('threshold_offset', 0.0)) == 0:
suggested_threshold += 7.0
ticker_bias = 0.0
fatal_reason = None
# 🔵 [MTF Trend Pre-fetch]
mtf_trend = mtf_data.get('1h_trend', 0) if mtf_data else 0
rsi_live = safe_float(curr_i.get('rsi', 50))
vol_idx = (safe_float(curr_i.get('ATR', 0)) / max(1.0, curr_close)) * 100
vol_sma = safe_float(curr_i.get('vol_sma', 0.0001))
# 🔵 [Yield Flip: BTC 패닉 필터]
btc_p = safe_float(curr_i.get('btc_close', 0))
btc_prev_p = safe_float(prev_i.get('btc_close', 0))
if btc_p < btc_prev_p * 0.995: fatal_reason = "BTC패닉드랍"
# 🔵 [Yield Flip: 거래량 임계값 상향]
# Small 티어(변동성 알트)는 더 강력한 거래량(2.2배)이 뒷받침되어야 진입 허용
vol_multiple = 2.2 if tier == "Small (High Vol)" else 1.5
if curr_vol < vol_sma * vol_multiple: fatal_reason = "거래량에너지부족"
# 🔵 [Quality Filter] 변동성/수축 필터
elif vol_idx < 0.5: fatal_reason = "저변동성횡보"
elif safe_float(curr_i.get('bb_bw', 0)) < 0.7: fatal_reason = "밴드수축중"
# 🔵 [MTF 필터]
elif eval_mode == "QUANTUM" and mtf_trend == -1: fatal_reason = "대추세역행(Q)"
elif eval_mode == "CLASSIC" and mtf_trend == 1: fatal_reason = "대추세역행(C)"
elif eval_mode == "CLASSIC" and mtf_trend == -1 and rsi_live > 25: fatal_reason = "하락장칼날잡기"
foundation_mult = safe_float(get_dynamic_strat_value('foundation_multiplier', mode=eval_mode, default=1.05)) # [Resolution UP] 1.3 -> 1.05
earned_score, total_w = 0.0, 0.0001
valid_indicator_count = 0
for name in logic_list:
w = safe_float(weights.get(name, 1.0), 1.0)
# 🔵 [Gen-11 Trial 7] 알트코인 전용 공격적 가중치 (추세 지표 1.5배)
if tier not in ["Major", "Mid"] and name in ['st', 'psar', 'trend']:
w *= 1.5
s_raw = safe_float(get_strategy_score(name, prev_i, curr_i, curr_close, mode=eval_mode), 0.0)
# 🔵 [5% Target Tuning] 달리는 말(추세)에 탑승하기 위해 과열 방어 기준 완화
if name == 'rsi' and safe_float(curr_i.get('rsi', 50)) > 75:
s_raw *= 0.50
# 🔵 [Gen-11 Trial 6] RSI 과매도 탈출 보너스 (낙폭과대 반등 사냥)
if name == 'rsi' and safe_float(prev_i.get('rsi')) < 30 and tier not in ["Major", "Mid"]:
s_raw *= 1.1
# 🔵 [Batch 3 Trial 3] 바닥 캐치를 위해 MACD Zero-Cross 감점 대폭 축소 (70% -> 40%)
if name == 'macd' and safe_float(curr_i.get('macd_h', 0)) <= 0:
s_raw *= 0.60
s = s_raw * vas_mult
# 🛡️ [Major/Meme Recovery] 섹터별 특화 필터링 (Iter 5 Final)
ema60_val = safe_float(curr_i.get('ema60', 0))
ema20_val = safe_float(curr_i.get('ema20', 0))
rsi_val = safe_float(curr_i.get('rsi', 50))
curr_vol_ratio = safe_float(curr_i.get('volume', 0)) / max(safe_float(curr_i.get('vol_sma', 1)), 0.0001)
ema20_slope = ema20_val - safe_float(prev_i.get('ema20', 0))
body_size = abs(curr_close - safe_float(curr_i.get('open', curr_close)))
upper_shadow = safe_float(curr_i.get('high', 0)) - max(curr_close, safe_float(curr_i.get('open', 0)))
if tier == "Major":
# [Iter 11] BTC는 TP가 짧으므로 RSI 50 이상의 약한 추세도 허용
rsi_floor = 50 if "BTC" in ticker else 55
# [Iter 13] BTC 무지성 부스트 삭제 (품격 회복)
if curr_close < ema60_val or curr_vol_ratio < 1.5 or ema20_slope <= 0 or rsi_val < rsi_floor:
s *= 0.2
elif any(m in ticker for m in ["DOGE", "SHIB", "PEPE"]):
# [Iter 13] Meme 전용 'OBV Momentum' 필터 추가 (자본 유입 검증)
obv_slope = safe_float(curr_i.get('obv', 0)) - safe_float(prev_i.get('obv', 0))
atr_val = safe_float(curr_i.get('ATR', 0))
atr_ratio = (atr_val / curr_close) * 100
dist_ema20 = abs(curr_close / ema20_val - 1) * 100
# OBV가 꺾여있거나 하락 중이면 Meme 진입 절대 금지
# OBV가 꺾여있거나 하락 중이면 Meme 진입 절대 금지
# [Flash-Response] 낙폭 과대 시 RSI 35 이상이면 어설픈 바닥으로 간주하여 강력 페널티
if obv_slope <= 0 or curr_close < ema20_val or atr_ratio > 2.5 or upper_shadow > body_size * 2.0 or dist_ema20 > 2.5 or rsi_val < 55:
# CLASSIC 모드(패닉 셀)일 때만 rsi_val < 35 필터링 조건 추가 검사
if eval_mode == "CLASSIC" and rsi_val > 35:
s *= 0.1 # 페널티 강화
else:
s *= 0.01
if s_raw < 5.0 and name in ['macd', 'rsi', 'stochastics']:
s = -30.0 # 더 강력한 부정 신호
earned_score += (s * w)
total_w += w
# 🔵 [Sniper Boost] 88점 이상 고확신 종목은 가중치 3% 추가 (수익 극대화)
if total_w > 0.1 and (earned_score / total_w) >= 85.0:
foundation_mult *= 1.03
foundation_score = (earned_score / total_w) * foundation_mult
# 🔵 [Batch 3 Trial 2] 전역 부스팅 제거 (추세 보너스로 대체)
foundation_score += 0.0
if tier not in ["Major", "Mid"] and valid_indicator_count >= 2:
foundation_score *= 1.15 # 알트 가속화 유지 (범용)
# 2. 전략적 엣지 보너스 및 MTF 패널티
bonus_score = 0.0
rsi_val = safe_float(curr_i.get('rsi', 50))
cvd_improving = safe_float(curr_i.get('cvd', 0)) > safe_float(prev_i.get('cvd', 0))
def calc_grad(v, t, w, md='DECREASE'):
df = abs(v - t)
if md == 'DECREASE': return 1.0 - (df/w) if t < v < t+w else (1.0 if v <= t else 0.0)
else: return 1.0 - (df/w) if t-w < v < t else (1.0 if v >= t else 0.0)
# 🔵 [Gen-7: 추세 동기화 보너스 중량] 1시간 대추세 일치 시 파격 가산 (+25점)
mtf_trend = mtf_data.get('1h_trend', 0) if mtf_data else 0
if eval_mode == "QUANTUM" and mtf_trend == 1: bonus_score += 25.0
# [수정] 대추세 하락 시 CLASSIC에 주던 +25점 칼날잡기 권장 보너스 철회
# if eval_mode == "CLASSIC" and mtf_trend == -1 and rsi_val < 40: bonus_score += 25.0
# 역행 패널티 강화
if eval_mode == "QUANTUM" and mtf_trend == -1: bonus_score -= 40.0
# 🔵 [All-Weather Engine] 윗꼬리(Shadow) 페널티 (펌핑 후 설거지 완벽 차단)
body_size = abs(curr_close - safe_float(curr_i.get('open')))
upper_wick = safe_float(curr_i.get('high')) - max(curr_close, safe_float(curr_i.get('open')))
# 🔴 [Meme DNA] DOGE 등은 윗꼬리 페널티를 더 엄격하게 (1.5배 -> 1.0배 몸통)
threshold_wick = body_size * 1.0 if any(m in ticker for m in ["DOGE", "SHIB", "PEPE"]) else body_size * 1.5
if upper_wick > max(threshold_wick, curr_close * 0.003):
bonus_score -= 55.0 # 가짜 반등 방지: 페널티 강화 (-45 -> -55)
if eval_mode == "QUANTUM":
bb_u = safe_float(curr_i.get('bb_u'))
vol_ratio = safe_float(curr_i.get('volume')) / max(0.0001, safe_float(curr_i.get('vol_sma', 1)))
# 🟢 보너스 대폭 상향 (45 -> 55)
if curr_close >= bb_u:
bonus_score += 55 * min(1.0, ((curr_close-bb_u)/bb_u)*100/3.0) * min(1.5, vol_ratio)
slv = safe_float(curr_i.get('sma_long', 0))
sma_short = safe_float(curr_i.get('sma_short', 0)) # 단기 이평선 참조
# 🔵 [정배열 보너스 엄격화] 휩소 횡보장에서는 점수를 주지 않고, 진짜 '단기>장기' 정배열일 때만 가점
sma_bonus_val = 35.0
if sma_short > slv * 1.002 and curr_close > slv:
bonus_score += sma_bonus_val * max(0.2, 1.0-(abs(curr_close-slv)/slv*100/4.0))
else: # CLASSIC
if rsi_val < 35: bonus_score += 55 * calc_grad(rsi_val, 25, 10, 'DECREASE')
sma20 = safe_float(curr_i.get('sma_long', curr_close))
gp = ((curr_close - sma20)/sma20)*100 if sma20>0 else 0
if gp < -7.0: bonus_score += 30 * min(1.0, abs(gp+7.0)/10.0)
if cvd_improving: bonus_score += 25
# 🔵 [Gen-11 Trial 3] RSI 기울기 필터 (Slope Filter) -15pts
# 에너지가 부족한 완만한 상승은 가짜 반등으로 간주
rsi_diff = safe_float(curr_i.get('rsi', 0)) - safe_float(prev_i.get('rsi', 0))
if tier in ["Major", "Mid"] and 0 < rsi_diff < 2.0:
bonus_score -= 15.0
# 🔵 [5% Target Tuning] BTC 시장 압력 페널티 미세 완화 (0.92 -> 0.94)
if btc_short and btc_short.get('trend') == "단기 하락":
foundation_score *= 0.94 # 시장 압력 속에서도 기회 탐색 강화
# 🔵 [Gen-11 Trial 2] 오실레이터 수렴 가점 미세 하향 (+8.5) (진입 타이밍 최적화)
# 🔵 [Gen-11 Trial 8] 알트코인은 수렴 가점 상향 (+15.0)
rsi_up = safe_float(curr_i.get('rsi', 0)) > safe_float(prev_i.get('rsi', 0))
macd_h_up = safe_float(curr_i.get('macd_h', 0)) > safe_float(prev_i.get('macd_h', 0))
stoch_k_up = safe_float(curr_i.get('stoch_k', 0)) > safe_float(prev_i.get('stoch_k', 0))
if rsi_up and macd_h_up and stoch_k_up:
bonus_score += 15.0 if tier not in ["Major", "Mid"] else 8.5
# 🔵 [Batch 3 Trial 2] 추세 가술 보너스 (+5.0) (정배열 우대)
sma_long = safe_float(curr_i.get('sma_long', curr_close))
if curr_close > sma_long:
bonus_score += 5.0
# 🔵 [Gen-9: 볼린저 스퀴즈 분출 보너스 (Squeeze Release)] +5.0점
# 🔵 [Gen-11 Trial 6] 알트코인은 분출 보너스 강화 (+12.0)
bb_w_prev = safe_float(prev_i.get('bb_w', 0))
bb_w_curr = safe_float(curr_i.get('bb_w', 0))
if bb_w_curr > bb_w_prev * 1.05 and bb_w_prev < 2.0:
bonus_score += 12.0 if tier not in ["Major", "Mid"] else 5.0
# 🔴 [Gen-11 Trial 5: 볼린저 중심선(SMA20) 저항 필터] -20pts
# 중심선을 뚫지 못하고 비빌 때(저항) 진입 차단
sma20 = safe_float(curr_i.get('sma_long', curr_close))
if tier == "Mid" and curr_close < sma20 * 1.005:
bonus_score -= 20.0
# 🔵 [Gen-11 Trial 8] 알트코인 추세 확정 보너스 (+15.0)
# ST와 PSAR이 동시에 매수 신호일 때 확신 주입
if tier not in ["Major", "Mid"]:
st_val = safe_float(curr_i.get('ST_DIR', 0))
psar_val = curr_close > safe_float(curr_i.get('psar', 0))
if st_val == 1 and psar_val:
bonus_score += 15.0
# 🟢 [Gen-10: 보너스 및 점수 합산]
# 🔵 [Gen-11 Trial 4] 탐욕 지수(FGI) 과열 시 보너스 20% 삭감 (추격 매수 차단)
if fgi_val >= 65 and tier in ["Major", "Mid"]:
bonus_score *= 0.8
bonus_impact = 1.0 + (max(0, foundation_mult - 1.0) * 0.3)
total_score = foundation_score + (bonus_score * bonus_impact) + ticker_bias
# 🔴 [Gen-11 Trial 1: 지표 불협화음 감점 (Divergence Penalty)] -15pts
if rsi_up != macd_h_up:
total_score -= 15.0
# 🔵 [Gen-10: 종목별 맞춤형 문턱값 제안 (Alpha Threshold)]
# (상단에서 이미 계산됨: suggested_threshold)
# 🛡️ [복구: 치명적 결함 감지 블록]
fatal_reason = ""
tick_size = get_upbit_tick_size(curr_close)
if (tick_size / curr_close) * 100 >= 0.5: fatal_reason = "호가갭위험"
if eval_mode == "QUANTUM":
slv = safe_float(curr_i.get('sma_long', 0))
if not fatal_reason and (curr_i.get('ST_DIR', 1) == -1 or curr_close < slv * 0.995):
if not (mtf_data and (mtf_data.get('1h_trend', 0) == 1 or rsi_val > 50)): fatal_reason = "단기상승세이탈"
else: # CLASSIC
if rsi_val > 65: fatal_reason = "RSI과열"
is_bullish = (curr_close > curr_i.get('open', curr_close)) or (safe_float(curr_i.get('cvd', 0)) > safe_float(prev_i.get('cvd', 0)))
if not fatal_reason and not (safe_float(curr_i.get('volume')) >= safe_float(curr_i.get('vol_sma'))*1.0 and is_bullish) and rsi_val > 28:
fatal_reason = "반등신호대기"
# =========================================================================
# 🟢 [누락 복구] 치명적 결함 캡(Cap) 및 스펙트럼 감점(Penalty) 로직 추가
defense_cap = safe_float(get_dynamic_strat_value('guard_score_threshold', mode=eval_mode, default=75.0))
if fatal_reason:
total_score = min(total_score, defense_cap - 5.0) # 결함 시 강한 캡 적용
else:
# 거래량 및 CVD 스펙트럼 감점 로직 (가짜 반등 방어막)
vol_sma_val = max(safe_float(curr_i.get('vol_sma', 1)), 0.0001)
cvd_val = safe_float(curr_i.get('cvd', 0))
if eval_mode == "QUANTUM":
if cvd_val < 0:
cvd_ratio = abs(cvd_val) / vol_sma_val
total_score -= 20 * min(1.0, cvd_ratio / 2.0) # 감점 강화
macd_4h = safe_float(mtf_data.get("4h_macd", 0)) if mtf_data else 0
if macd_4h < 0:
total_score -= 10 * min(1.0, abs(macd_4h) / 5.0)
else: # CLASSIC
if cvd_val < 0:
total_score -= 8 * min(1.0, abs(cvd_val) / vol_sma_val / 2.0)
cvd_slope = cvd_val - safe_float(prev_i.get('cvd', 0))
if cvd_slope < 0:
total_score -= 12 * min(1.0, abs(cvd_slope) / vol_sma_val * 2.0)
curr_vol_val = safe_float(curr_i.get('volume', 0))
vol_ratio = curr_vol_val / vol_sma_val
if vol_ratio < 1.1: # [Sweet Spot] 1.3 -> 1.1로 완화
total_score -= 10 * min(1.0, max(0.0, (1.1 - vol_ratio) / 0.8))
# =========================================================================
# 🛡️ [Final Adjustment] Meme/Small 섹터는 진입 문턱(Threshold)을 +5.0점 높여 엄격한 스나이핑 유도
if tier == "Small (High Vol)" or is_meme:
suggested_threshold += 5.0
final_score = round(max(0.0, min(100.0, total_score)), 1)
return final_score, fatal_reason, suggested_threshold, eval_mode
# 🟢 [FIX: 슬리피지 수학 공식 교정] 원화(KRW)를 기준으로 몇 개의 코인을 샀는지 부피(Volume)를 역산하여 정확한 VWAP 산출
async def calculate_expected_slippage(ticker, buy_amt_krw):
"""호가창 5호가 뎁스를 확인하여 체결 물량(Volume) 기반으로 예상 슬리피지(%)를 정확히 계산합니다."""
try:
ob = await execute_upbit_api(pyupbit.get_orderbook, ticker)
if not ob or 'orderbook_units' not in ob: return 0.0
units = ob['orderbook_units'][:5]
current_price = units[0]['ask_price']
total_filled_vol = 0.0
rem_krw = buy_amt_krw
for u in units:
ask_p = u['ask_price']
ask_s = u['ask_size']
# ask_p가 0일 경우 0으로 나누는 오류 방지
if ask_p <= 0:
continue # 이 호가창은 무시하고 다음으로 넘어감
avail_krw = ask_p * ask_s
if rem_krw <= avail_krw:
total_filled_vol += (rem_krw / ask_p)
rem_krw = 0
break
else:
total_filled_vol += ask_s
rem_krw -= avail_krw
if total_filled_vol == 0: return 0.0
# 5호가를 다 먹고도 돈이 남으면 최악의 경우를 가정하여 5호가 가격으로 마저 체결된다고 산정. 단, 호가창 최상단 가격보다 낮아질 수는 없음.
if rem_krw > 0:
# 남은 금액을 현재 호가창 최하단 가격으로 최대한 매수 시도
remaining_buy_price = units[-1]['ask_price']
# 최악의 경우를 가정하되, 현재가보다 낮아지지 않도록 보정
effective_remaining_price = max(current_price, remaining_buy_price)
# effective_remaining_price가 0일 경우 0으로 나누는 오류 방지
if effective_remaining_price <= 0:
return 0.0
total_filled_vol += (rem_krw / effective_remaining_price)
avg_exec_price = buy_amt_krw / total_filled_vol
# current_price가 0일 경우 0으로 나누는 오류 방지
if current_price <= 0:
return 0.0
slippage_pct = ((avg_exec_price - current_price) / current_price) * 100
return slippage_pct
except Exception as e:
logging.error(f"슬리피지 계산 오류 ({ticker}): {e}")
return 0.0
def get_exit_plan_preview(ticker: str, curr_data: dict, eval_mode: str = "QUANTUM") -> str:
"""기대 수익과 동적 손절선을 계산하여 AI 분석용 컨텍스트 문자열을 생성합니다."""
try:
tier_params = get_coin_tier_params(ticker, curr_data, eval_mode=eval_mode)
target_mult = tier_params.get('target_atr_multiplier', 4.5)
sl_cap = tier_params.get('stop_loss', -3.0)
close_p = safe_float(curr_data.get('close', 1))
atr_val = safe_float(curr_data.get('ATR', 0))
atr_pct = (atr_val / close_p) * 100 if close_p > 0 else 0
expected_target = round(atr_pct * target_mult, 2)
sl_atr_mult = tier_params.get('atr_mult', 2.0)
dynamic_sl = -(atr_pct * sl_atr_mult)
# 실제 process_buy_order에 적용된 압착 로직과 동일하게 계산
final_sl = max(dynamic_sl, sl_cap)
if abs(final_sl) > (expected_target * 0.7):
final_sl = -(expected_target * 0.7)
final_sl = round(final_sl, 2)
rr_ratio = round(expected_target / abs(final_sl), 2) if final_sl != 0 else 1.0
return f"기대수익 +{expected_target}% / 예상손절 {final_sl}% (손익비 {rr_ratio}:1)"
except Exception as e:
logging.error(f"Exit Plan Preview 생성 오류 ({ticker}): {e}")
return "데이터 부족으로 산출 불가"
def load_config():
if getattr(sys, 'frozen', False): base_path = os.path.dirname(sys.executable)
else: base_path = os.path.dirname(os.path.abspath(__file__))
quantum_path = os.path.join(base_path, "config_quantum.json")
classic_path = os.path.join(base_path, "config_classic.json")
if not os.path.exists(quantum_path): print(f"❌ Quantum 설정 파일 없음 ({quantum_path})"); sys.exit()
if not os.path.exists(classic_path): print(f"❌ Classic 설정 파일 없음 ({classic_path})"); sys.exit()
with open(quantum_path, 'r', encoding='utf-8') as f: quantum_conf = json.load(f)
with open(classic_path, 'r', encoding='utf-8') as f: classic_conf = json.load(f)
return quantum_conf, classic_conf, quantum_path, classic_path
def get_strat_for_mode(mode="QUANTUM"):
if isinstance(mode, str) and mode.upper() == "CLASSIC":
return CLASSIC_STRAT
return QUANTUM_STRAT
def get_dynamic_strat_value(key, mode=None, default=None, ticker=None):
# 🟢 [3번 제언: DNA 진화] 종목별 고유 파라미터가 있다면 전역/모드 설정보다 '최우선'으로 적용합니다.
if ticker:
dna = STRAT.get('ticker_dna', {}).get(ticker, {})
if key in dna:
return dna[key]
if isinstance(mode, str) and mode.upper() in ("CLASSIC", "QUANTUM"):
config = get_strat_for_mode(mode)
if key in config:
return config.get(key, default)
return STRAT.get(key, default)
async def save_config_async(config_data, path):
def _save():
import time
import shutil
# 1. 백업 파일 생성 (안전장치)
bak_path = path + ".bak"
try:
if os.path.exists(path):
shutil.copy2(path, bak_path)
except:
pass # 백업 실패는 무시하고 진행
# 2. 메인 파일 파일 쓰기 시도 (최대 5회 재시도)
success = False
last_err = None
for i in range(5):
try:
# 윈도우 잠금 해제를 위해 잠시 대기
if i > 0: time.sleep(0.3)
with open(path, 'w', encoding='utf-8') as f:
json.dump(config_data, f, indent=4, ensure_ascii=False)
f.flush()
os.fsync(f.fileno())
success = True
break
except Exception as e:
last_err = e
# 잠금 오류일 확률이 높으므로 다시 루프 실행
continue
if not success:
# 최종 실패 시 백업에서 복구 시도
try:
if os.path.exists(bak_path):
shutil.copy2(bak_path, path)
except:
pass
raise last_err
try:
await asyncio.to_thread(_save)
except Exception as e: