-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathmain.py
More file actions
313 lines (260 loc) Β· 16.4 KB
/
Copy pathmain.py
File metadata and controls
313 lines (260 loc) Β· 16.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
# ==========================================================
# FILE: main.py
# ==========================================================
# π¨ VERIFIED: [μ΅μ’
무결μ νμ ] 5λ νλ² λ° 40λ μ£μ§ μΌμ΄μ€ μλ²½ κ²°μ κ΅μ°¨ κ²μ¦ μλ£.
# π¨ MODIFIED: [Event Loop κ΅μ°© μμ ] post_init λ΄λΆ commands_handler λ° μ½λ°± νμ λλ©μΈ λ½μ¨ μ ν λλ½ λ§Ήμ μμ² λ΄μ.
# π¨ MODIFIED: [Phase 3 μ€μΌμ€λ¬ λ컀νλ§ λν΅ν©] 20:05 EST μ νν° μ μ°(scheduled_aftermarket_sync) ν¬λ‘ μ€μΌμ€ μꡬ μκ°.
# π¨ MODIFIED: [15:59 MOC λ€ν λ½μ¨] μμ΄μ μ λ‘-μ€λ²λμ΄νΈ κ°μ μ²μ°μ μν 15:59 EST μ μ© ν¬λ‘ μ€μΌμ€ μ μ§.
# π¨ MODIFIED: [16:05 νμ μ μ°λ§ λ¨μΌν] μμ΄μ λ¬Όλ 보μ μ μ€ν΅νλ λ‘μ§μ νκΈ°νκ³ , 15:59 λ€ν μλ£ ν 무쑰건 λΉμΌ 100% μ μ°λλλ‘ μ‘Έμ
μ€μΊλ§ λ¨μΌν.
# π¨ NEW: [Case 39 & 40 μ λ λ°©μ΄λ§ κ²°μ] μλ³Έ μ κΉ(Capital Lock-up) νμμΌλ‘ μ§μ° μ΄κ΄λ V-REV λ³Έμ§ νλμ 16:01 EST μ νν°μ₯μ μΌκ΄ ν격νλλ‘ μ κ· μ€μΌμ€ νμ΄νλΌμΈ(scheduled_aftermarket_vrev_trade) ν©νΈ μ΄μ.
# π¨ MODIFIED: [λ‘κΉ
μ¦λ° μμ² μ°¨λ¨] λ‘κΉ
μ€μ μ μ΅μλ¨(νκ²½ λ³μ μ€μΊ μ )μΌλ‘ μ μ§ λ°°μΉνμ¬ ν€λλ¦¬μ€ κ΅¬λ μ λ°μνλ λΆνΈμ€νΈλ© λ‘κ·Έ μ¦λ° μλ²½ μ°¨λ¨.
# π¨ MODIFIED: [μ 1νλ² μ² μ μ€μ] get_active_tickers νΈμΆλΆ λ± λͺ¨λ λκΈ° I/O ꡬκ°μ asyncio.wait_for μ‘±μ μλ²½ λν (μ΄λ²€νΈ 루ν κ΅μ°© μμ² λ΄μ).
# π¨ MODIFIED: [Case 34 μ μ GC λ½μ¨] λμ€ν¬ μ©λ κ³ κ° λΆκ΄΄ λ°©μ΄λ₯Ό μν΄ `TimedRotatingFileHandler` μ΄μ λ° 7μΌ μ΄κ³Ό λ‘κ·Έ μλ μꡬ μκ° λ°°μ μ μ§.
# π¨ MODIFIED: [V73.15 νμλΌμΈ λ컀νλ§] 17:05 KST V14 μ μ ν격 λ° V-REV μ€λ
μ· λΆλ¦¬ λ½μ¨.
# π¨ MODIFIED: [λ§Ήμ 4 μμ ] μλ¨Ένμ λν νμ ν¨λ¬λ
μ€ μ°¨λ¨ λ° KST λ€μ΄ν°λΈ μμ λ½μ¨.
# π¨ MODIFIED: [Case 26] ν
λ κ·Έλ¨ νμ λΆκ΄΄ λ°©μ΄μ© html λͺ¨λ κ²°μ.
# ==========================================================
import os
import logging
from logging.handlers import TimedRotatingFileHandler
import datetime
import asyncio
import math
import html
from zoneinfo import ZoneInfo
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, MessageHandler, filters, Defaults, ContextTypes
from dotenv import load_dotenv
from config import ConfigManager
from broker import KoreaInvestmentBroker
from strategy import InfiniteStrategy
from telegram_bot import TelegramController
from queue_ledger import QueueLedger
from strategy_reversion import ReversionStrategy
from volatility_engine import VolatilityEngine, determine_market_regime
from scheduler_core import (
scheduled_token_check,
scheduled_auto_sync,
scheduled_force_reset,
scheduled_self_cleaning,
perform_self_cleaning,
is_market_open
)
from scheduler_sniper import scheduled_sniper_monitor
# π¨ NEW: [Case 39 & 40] μ νν°μ₯ μ§μ° ν격 μμ§(scheduled_aftermarket_vrev_trade) μν¬νΈ κ²°μ
from scheduler_vwap import scheduled_vwap_trade, scheduled_vwap_init_and_cancel, scheduled_aftermarket_vrev_trade
from scheduler_regular import scheduled_early_regular_trade, scheduled_regular_trade_delayed
TICKER_BASE_MAP = {
"SOXL": "SOXX",
"TQQQ": "QQQ",
"TSLL": "TSLA",
"FNGU": "FNGS",
"BULZ": "FNGS"
}
if not os.path.exists('data'):
os.makedirs('data')
if not os.path.exists('logs'):
os.makedirs('logs')
# π¨ MODIFIED: [λ‘κΉ
μ¦λ° μμ² μ°¨λ¨] λ‘κΉ
μ€μ μ μ΅μλ¨(νκ²½ λ³μ μ€μΊ μ )μΌλ‘ μ μ§ λ°°μΉνμ¬ ν€λλ¦¬μ€ κ΅¬λ μ λ°μνλ λΆνΈμ€νΈλ© λ‘κ·Έ μ¦λ° μλ²½ μ°¨λ¨.
log_filename = "logs/bot_app.log"
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO,
handlers=[
# π¨ MODIFIED: [Case 34] λ‘κ·Έλͺ
λ¨μΌν λ° TimedRotatingFileHandler μ£Όμ
(7μΌμΉ λ°±μ
μ μ§, μ΄μ μꡬ μκ°)
TimedRotatingFileHandler(log_filename, when="midnight", interval=1, backupCount=7, encoding='utf-8'),
logging.StreamHandler()
]
)
logging.getLogger("yfinance").setLevel(logging.CRITICAL)
load_dotenv()
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
try:
ADMIN_CHAT_ID = int(os.getenv("ADMIN_CHAT_ID")) if os.getenv("ADMIN_CHAT_ID") else None
except ValueError:
ADMIN_CHAT_ID = None
APP_KEY = os.getenv("APP_KEY")
APP_SECRET = os.getenv("APP_SECRET")
CANO = os.getenv("CANO")
ACNT_PRDT_CD = os.getenv("ACNT_PRDT_CD", "01")
if not all([TELEGRAM_TOKEN, APP_KEY, APP_SECRET, CANO, ADMIN_CHAT_ID]):
# π¨ MODIFIED: [λ‘κΉ
μ¦λ° λ°©μ΄] print λ°λμ½λ μκ° λ° logging.critical λ½μ¨
logging.critical("β [μΉλͺ
μ μ€λ₯] .env νμΌμ λ΄ κ΅¬λ νμ ν€κ° λλ½λμμ΅λλ€. λ΄μ μ’
λ£ν©λλ€.")
os._exit(1)
est_zone = ZoneInfo('America/New_York')
async def global_error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
logging.error("π¨ [Global Error] Exception while handling an update:", exc_info=context.error)
async def scheduled_volatility_scan(context):
try:
is_open = await asyncio.wait_for(asyncio.to_thread(is_market_open), timeout=10.0)
except asyncio.TimeoutError:
logging.error("β οΈ [volatility_scan] λ¬λ ₯ API νμμμ. νμΌ κ°μ κ°μ₯ μ²λ¦¬ν©λλ€.")
est = ZoneInfo('America/New_York')
is_open = datetime.datetime.now(est).weekday() < 5
# π¨ MODIFIED: [κ΄μ νμ λμ λ°©μ΄] Fail-Open κ°λ μ ν
λ κ·Έλ¨ κ΄λ¦¬μ μ¦κ° νμ λ§ μ£Όμ
try:
if context.job and context.job.chat_id:
await context.bot.send_message(chat_id=context.job.chat_id, text="β οΈ <b>[μμ€ν
κ²½κ³ ] λ¬λ ₯ API ν΅μ νμμμ!</b>\nβ«οΈ νμΌ κ°μ κ°μ₯(Fail-Open) λ‘μ§μ΄ κ°λλμμ΅λλ€.", parse_mode='HTML')
except Exception: pass
except Exception as e:
logging.error(f"β οΈ [volatility_scan] λ¬λ ₯ API μλ¬. νμΌ κ°μ κ°μ₯ μ²λ¦¬ν©λλ€: {e}")
est = ZoneInfo('America/New_York')
is_open = datetime.datetime.now(est).weekday() < 5
# π¨ MODIFIED: [κ΄μ νμ λμ λ°©μ΄] Fail-Open κ°λ μ ν
λ κ·Έλ¨ κ΄λ¦¬μ μ¦κ° νμ λ§ μ£Όμ
try:
if context.job and context.job.chat_id:
safe_err = html.escape(str(e))
await context.bot.send_message(chat_id=context.job.chat_id, text=f"β οΈ <b>[μμ€ν
κ²½κ³ ] λ¬λ ₯ API ν΅μ μλ¬!</b>\nβ«οΈ μ¬μ : {safe_err}\nβ«οΈ νμΌ κ°μ κ°μ₯(Fail-Open) λ‘μ§μ΄ κ°λλμμ΅λλ€.", parse_mode='HTML')
except Exception: pass
if not is_open:
return
async def _do_scan():
app_data = context.job.data
cfg = app_data['cfg']
broker = app_data['broker']
base_map = app_data.get('base_map', TICKER_BASE_MAP)
logging.info("=" * 60)
logging.info("π [μμ¨μ£Όν λ³λμ± & μμ₯ κ΅λ©΄ μ€μΊ μλ£] (10:00 EST μ€λ
μ·)")
for attempt in range(3):
# π¨ NEW: [Case 32] μ΄λ λ§€νΈλ¦μ€ API ν΅μ μ TPS μΊ‘ν(0.06s) μλμμΉ κ°μ μ£Όμ
await asyncio.sleep(0.06)
regime_data = await determine_market_regime(broker)
if regime_data.get("status") == "success":
break
if attempt < 2:
# π¨ MODIFIED: [Case 33 μ λ κ·μΉ] 3λ¨ μ§μ λ°±μ€ν κ·κ²© ν©νΈ κ΅μ
logging.warning(f"β οΈ μ΄λ λ§€νΈλ¦μ€ μ€μΊ μ€ν¨ (μλ {attempt+1}/3). μ§μ λ°±μ€ν ν μ¬μλν©λλ€.")
await asyncio.sleep(1.0 * (2 ** attempt))
app_data['regime_data'] = regime_data
if regime_data.get("status") == "success":
regime = regime_data.get("regime")
target_ticker = regime_data.get("target_ticker")
close_p = regime_data.get("close", 0.0)
prev_vwap = regime_data.get("prev_vwap", 0.0)
curr_vwap = regime_data.get("curr_vwap", 0.0)
desc = regime_data.get("desc", "")
logging.info(f"ποΈ μ΄λ λ§€νΈλ¦μ€: [{regime}] νκ²: {target_ticker} ({desc}) | μ’
κ°: {close_p:.2f}, λΉμΌVWAP: {curr_vwap:.2f}, μ μΌVWAP: {prev_vwap:.2f}")
else:
logging.warning(f"β οΈ μ΄λ λ§€νΈλ¦μ€ νλ³ μ€ν¨: {regime_data.get('msg')}")
# π¨ MODIFIED: [μ 1νλ² μ² μ μ€μ] get_active_tickers νΈμΆ μ λλ½λμλ wait_for νμμμ μ‘±μ 100% κ²°μ
try:
active_tickers = await asyncio.wait_for(asyncio.to_thread(cfg.get_active_tickers), timeout=10.0)
except Exception as e:
logging.error(f"π¨ νμ± μ’
λͺ© μ€μΊ μ€ νμμμ/μλ¬: {e}")
active_tickers = []
if not active_tickers:
logging.info("π νμ¬ μ΄μ© μ€μΈ μ’
λͺ©μ΄ μμ΅λλ€.")
else:
briefing_lines = []
vol_engine = VolatilityEngine()
for ticker in active_tickers:
# π¨ MODIFIED: [Case 32 μ λ κ·μΉ] λ€μ€ μ’
λͺ© μ€μΊ μ TPS μΊ‘ν μλμμΉ κ°μ μ£Όμ
await asyncio.sleep(0.06)
target_base = base_map.get(ticker, ticker)
try:
weight_data = await asyncio.wait_for(
asyncio.to_thread(vol_engine.calculate_weight, target_base),
timeout=10.0
)
raw_weight = weight_data.get('weight', 1.0) if isinstance(weight_data, dict) else weight_data
real_weight = float(raw_weight)
if not math.isfinite(real_weight):
raise ValueError(f"λΉμ μ μν μμΉ μ°μΆ: {real_weight}")
except asyncio.TimeoutError:
real_weight = 1.0
except Exception as e:
# π¨ MODIFIED: [Silent Death μμ ] μμΈ λ°μ μ λ‘κ·Έ μΆλ ₯
logging.warning(f"β οΈ [{ticker}] κ°μ€μΉ μ°μ° μ€ μμΈ λ°μ (κΈ°λ³Έκ° 1.0 ν΄λ°±): {e}")
real_weight = 1.0
status_text = "OFF κΆμ₯" if real_weight <= 1.0 else "ON κΆμ₯"
briefing_lines.append(f"{ticker}({target_base}): {real_weight:.2f} ({status_text})")
logging.info(f"π [μμ¨μ£Όν μ§ν] {' | '.join(briefing_lines)}")
logging.info("=" * 60)
try:
# π¨ MODIFIED: [μ€μΌμ€λ¬ λΆκ΄΄ λ°©μ΄] λ€μ€ μ’
λͺ© μ€μΊ λ° 3λ¨ λ°±μ€ν κ³ λ € μ μ νμμμ 180μ΄ νμ₯ λ½μ¨
await asyncio.wait_for(_do_scan(), timeout=180.0)
except Exception as e:
logging.error(f"π¨ [volatility_scan] μ μ νμμμ(180μ΄) λλ λ°νμ λΆκ΄΄ λ°μ: {e}")
async def post_init(application: Application):
tx_lock = asyncio.Lock()
application.bot_data['app_data']['tx_lock'] = tx_lock
application.bot_data['bot_controller'].tx_lock = tx_lock
application.bot_data['bot_controller'].sync_engine.tx_lock = tx_lock
application.bot_data['bot_controller'].callbacks_handler.tx_lock = tx_lock
# π¨ MODIFIED: [Event Loop κ΅μ°© μμ ] commands_handler λ° μ½λ°± νμ λλ©μΈμ Lock κ°±μ μ ν λ½μ¨
application.bot_data['bot_controller'].commands_handler.tx_lock = tx_lock
application.bot_data['bot_controller'].callbacks_handler.order_handler.tx_lock = tx_lock
application.bot_data['bot_controller'].callbacks_handler.avwap_handler.tx_lock = tx_lock
application.bot_data['bot_controller'].callbacks_handler.config_handler.tx_lock = tx_lock
def main():
est_zone = ZoneInfo('America/New_York')
kst_zone = ZoneInfo('Asia/Seoul')
cfg = ConfigManager()
latest_version = cfg.get_latest_version()
logging.info("=" * 60)
logging.info(f"π μ΄λ λ§€νΈλ¦μ€ ννΈ μμ§ {latest_version} (V86.00 μμ 리λ²μ ν©νΈ λ½μ¨ μλμ
)")
logging.info("=" * 60)
perform_self_cleaning()
cfg.set_chat_id(ADMIN_CHAT_ID)
broker = KoreaInvestmentBroker(APP_KEY, APP_SECRET, CANO, ACNT_PRDT_CD)
strategy = InfiniteStrategy(cfg)
queue_ledger = QueueLedger()
strategy_rev = ReversionStrategy(cfg)
bot = TelegramController(
cfg, broker, strategy, tx_lock=None,
queue_ledger=queue_ledger, strategy_rev=strategy_rev
)
app_data = {
'cfg': cfg, 'broker': broker, 'strategy': strategy,
'queue_ledger': queue_ledger, 'strategy_rev': strategy_rev,
'bot': bot, 'tx_lock': None, 'base_map': TICKER_BASE_MAP,
'tz_est': est_zone, 'regime_data': {"status": "pending", "msg": "10:00 EST μ΄μ μ€νλ ν©μ λκΈ°"}
}
app = (
Application.builder()
.token(TELEGRAM_TOKEN)
.read_timeout(30.0)
.write_timeout(30.0)
.connection_pool_size(8)
.defaults(Defaults(tzinfo=est_zone))
.post_init(post_init)
.build()
)
app.bot_data['app_data'] = app_data
app.bot_data['bot_controller'] = bot
app.add_error_handler(global_error_handler)
for cmd, handler in [
("start", bot.cmd_start), ("record", bot.cmd_record), ("history", bot.cmd_history),
("sync", bot.cmd_sync), ("settlement", bot.cmd_settlement), ("seed", bot.cmd_seed),
("ticker", bot.cmd_ticker), ("mode", bot.cmd_mode), ("reset", bot.cmd_reset),
("version", bot.cmd_version), ("update", bot.cmd_update),
("avwap", bot.cmd_avwap), ("queue", bot.cmd_queue), ("add_q", bot.cmd_add_q), ("clear_q", bot.cmd_clear_q),
("log", bot.cmd_log), ("error", bot.cmd_log)
]:
app.add_handler(CommandHandler(cmd, handler))
app.add_handler(CallbackQueryHandler(bot.handle_callback))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, bot.handle_message))
jq = app.job_queue
jq.run_repeating(scheduled_token_check, interval=21600, first=10, chat_id=ADMIN_CHAT_ID, data=app_data)
jq.run_daily(scheduled_auto_sync, time=datetime.time(16, 5, tzinfo=est_zone), days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
now_est = datetime.datetime.now(est_zone)
if now_est.hour == 16 and 5 <= now_est.minute <= 35:
jq.run_once(scheduled_auto_sync, 5.0, chat_id=ADMIN_CHAT_ID, data=app_data)
jq.run_daily(scheduled_force_reset, time=datetime.time(4, 0, tzinfo=est_zone), days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
jq.run_daily(scheduled_volatility_scan, time=datetime.time(10, 0, tzinfo=est_zone), days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
# π¨ MODIFIED: [λ§Ήμ 4 μμ ] KST λν νμ ν¨λ¬λ
μ€(Time Paradox) μλ²½ κ΅μ λ° PTB λ€μ΄ν°λΈ νμμ‘΄ 100% μμ
early_trade_time = datetime.time(17, 5, tzinfo=kst_zone)
jq.run_daily(scheduled_early_regular_trade, time=early_trade_time, days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
# π¨ [15:26 EST] V-REV λ³Έμ§ λ« μ§μ° μ₯μ λ½μ¨
delayed_trade_time = datetime.time(15, 26, tzinfo=est_zone)
jq.run_daily(scheduled_regular_trade_delayed, time=delayed_trade_time, days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
jq.run_daily(scheduled_vwap_init_and_cancel, time=datetime.time(15, 26, tzinfo=est_zone), days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
jq.run_repeating(scheduled_sniper_monitor, interval=60, first=30, chat_id=ADMIN_CHAT_ID, data=app_data)
# π¨ MODIFIED: [15:59 EST] μμ΄μ μ λ‘-μ€λ²λμ΄νΈ κ°μ λ€ν μ μ© μ€μΌμ€ λ½μ¨ (λ¨μΌν νμ )
jq.run_daily(scheduled_sniper_monitor, time=datetime.time(15, 59, 0, tzinfo=est_zone), days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
# π¨ NEW: [16:01 EST] μλ³Έ μ κΉ(Capital Lock-up)μΌλ‘ μ§μ° μ΄κ΄λ V-REV λ³Έμ§ νλμ μ νν°μ₯μ μΌκ΄ ν격νλ μ€μΌμ€ νμ΄νλΌμΈ (Case 39, 40 λ°©μ΄)
jq.run_daily(scheduled_aftermarket_vrev_trade, time=datetime.time(16, 1, 0, tzinfo=est_zone), days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
jq.run_repeating(scheduled_vwap_trade, interval=60, first=30, chat_id=ADMIN_CHAT_ID, data=app_data)
jq.run_daily(scheduled_self_cleaning, time=datetime.time(17, 0, tzinfo=est_zone), days=tuple(range(7)), chat_id=ADMIN_CHAT_ID, data=app_data)
app.run_polling()
if __name__ == "__main__":
main()