File size: 31,974 Bytes
48097ce
 
 
 
 
 
deb7f13
48097ce
deb7f13
 
 
48097ce
 
 
 
 
 
 
 
 
8de969c
deb7f13
588034e
48097ce
 
 
 
deb7f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
cab04ab
 
48097ce
 
 
 
 
 
 
 
8de969c
 
 
48097ce
8de969c
48097ce
 
 
 
8de969c
 
 
 
 
 
 
48097ce
 
 
 
588034e
 
 
 
 
 
 
 
 
 
 
 
48097ce
588034e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
deb7f13
 
48097ce
deb7f13
48097ce
 
deb7f13
 
 
 
48097ce
deb7f13
 
 
 
48097ce
 
deb7f13
 
 
48097ce
 
 
deb7f13
48097ce
 
 
deb7f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
deb7f13
48097ce
 
 
 
 
 
 
cab04ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
a8694f1
 
 
 
 
 
48097ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8694f1
48097ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deb7f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
 
 
 
 
588034e
 
 
 
 
 
 
 
deb7f13
 
588034e
48097ce
 
 
 
 
25a9b72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
 
deb7f13
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
 
 
6216937
 
48097ce
deb7f13
6216937
 
 
 
 
deb7f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
588034e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
deb7f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
 
deb7f13
 
48097ce
deb7f13
48097ce
 
 
deb7f13
 
588034e
 
 
 
 
 
 
 
 
 
deb7f13
 
588034e
deb7f13
588034e
 
deb7f13
48097ce
 
 
deb7f13
48097ce
 
deb7f13
48097ce
 
 
deb7f13
48097ce
deb7f13
48097ce
 
 
 
 
 
 
 
 
deb7f13
48097ce
deb7f13
 
0922387
 
 
 
 
 
 
48097ce
 
 
 
 
 
deb7f13
 
48097ce
 
 
 
 
6216937
 
48097ce
deb7f13
6216937
 
deb7f13
48097ce
 
 
 
 
 
deb7f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83d14d7
 
48097ce
 
 
 
 
 
77a208f
 
 
b6dc399
 
 
77a208f
 
 
 
 
 
 
 
 
 
 
48097ce
 
77a208f
 
 
 
48097ce
 
 
 
 
8de969c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48097ce
 
efffe05
b6dc399
77a208f
 
 
 
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
# -*- coding: utf-8 -*-
"""FINCHAL ์„œ๋ฒ„ โ€” REST + MCP๋ฅผ ํ•œ ํ”„๋กœ์„ธ์Šค์—์„œ ์„œ๋น™ํ•œ๋‹ค.



REST ๋Š” ์‚ฌ๋žŒ๊ณผ ์›น ํ™”๋ฉด์ด ์“ฐ๊ณ , MCP ๋Š” ์—์ด์ „ํŠธ๊ฐ€ ์“ด๋‹ค.

๋‘˜์ด ๊ฐ™์€ ์›์žฅยท๊ฐ™์€ ์ฑ„์ ๊ธฐ๋ฅผ ๋ณธ๋‹ค. ๊ฒฝ๋กœ๊ฐ€ ๊ฐˆ๋ฆฌ๋ฉด ์„ฑ์ ์ด ๊ฐˆ๋ฆฐ๋‹ค.

"""
import os, sys, json, time, base64, hmac, hashlib, secrets, urllib.parse, urllib.request
import numpy as np, pandas as pd
from fastapi import FastAPI, Request, Header, HTTPException
from fastapi.responses import (JSONResponse, PlainTextResponse, FileResponse,
                               RedirectResponse)
from fastapi.staticfiles import StaticFiles

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path[:0] = [HERE, os.path.dirname(HERE)]
import seasons as S
import scoring as SC
import reference as RF
import ledger as L
import mcp as MCP
import fetch as FE
import i18n as I
import baselines as BL

CEIL = json.load(open(os.path.join(os.path.dirname(HERE), "announce_ceiling.json"),
                     encoding="utf-8"))["ceiling"]

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Hugging Face ๋กœ๊ทธ์ธ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ์‹ ์›์€ ์ฐธ๊ฐ€์ž๊ฐ€ ์œ„์กฐํ•  ์ˆ˜ ์—†๋Š” ๊ณณ์—์„œ ์™€์•ผ ํ•œ๋‹ค. ์ž์œ  ์ž…๋ ฅ ID๋ฅผ ๋‘๋ฉด
# ๋‚จ์˜ ์ด๋ฆ„์œผ๋กœ ์ œ์ถœํ•  ์ˆ˜ ์žˆ๊ณ , ๊ทธ๋Ÿฌ๋ฉด ์ˆœ์œ„ํ‘œ๊ฐ€ ์˜๋ฏธ๋ฅผ ์žƒ๋Š”๋‹ค.
OAUTH_ID = os.environ.get("OAUTH_CLIENT_ID", "")
OAUTH_SECRET = os.environ.get("OAUTH_CLIENT_SECRET", "")
OAUTH_ISS = os.environ.get("OPENID_PROVIDER_URL", "https://huggingface.co")
SPACE_HOST = os.environ.get("SPACE_HOST", "")
COOKIE = "finchal_session"
# ๋‹ค๋ฅธ ์ถœ์ฒ˜์˜ iframe ์•ˆ์—์„œ ๋œจ๋ฏ€๋กœ ์šฐ๋ฆฌ ์ฟ ํ‚ค๋Š” 3์ž ์ฟ ํ‚ค๋‹ค. Lax ๋Š” ๊ฑฐ๊ธฐ์„œ ๋ฒ„๋ ค์ง€๊ณ 
# None ์€ Secure ๋ฅผ ์š”๊ตฌํ•˜๋ฉฐ Secure ๋Š” HTTPS ๋ฅผ ์š”๊ตฌํ•œ๋‹ค โ€” Space ์—์„œ๋Š” ์ฐธ, ๋กœ์ปฌ์—์„œ๋Š” ๊ฑฐ์ง“.
IN_FRAME = bool(SPACE_HOST)
COOKIE_KW = ({"samesite": "none", "secure": True} if IN_FRAME
             else {"samesite": "lax", "secure": False})
# ๐Ÿ”ด ์žฌ์‹œ์ž‘ํ•  ๋•Œ๋งˆ๋‹ค ๋ฐ”๋€Œ๋ฉด ๋ชจ๋“  ์„ธ์…˜์ด ๋Š๊ธด๋‹ค. Space ๋ณ€์ˆ˜๋กœ ๊ณ ์ •ํ•  ๊ฒƒ.
SESSION_KEY = os.environ.get("FINCHAL_SESSION_KEY") or secrets.token_hex(16)

app = FastAPI(title="FINCHAL")
S1 = S.SEASONS[1]
# ๊ฐœ๋ฐœ ์ค‘ ํ™”๋ฉด ํ™•์ธ์šฉ. ์‹œ์ฆŒ ๊ฐœ๋ง‰์ผ์—๋Š” ์ฑ„์ ํ•  ๊ตฌ๊ฐ„์ด ์—†์–ด ์ฐจํŠธ์™€ ์ˆœ์œ„๊ฐ€ ๋น„๋ฏ€๋กœ,
# ๊ฐœ๋ง‰ ์ „์— ํ™”๋ฉด์„ ๊ฒ€์ฆํ•˜๋ ค๋ฉด ์‹œ์ž‘์ผ์„ ์•ž๋‹น๊ฒจ ๋„์šด๋‹ค.
if os.environ.get("FINCHAL_OPENS"):
    S1 = dict(S1, opens=os.environ["FINCHAL_OPENS"])
ASSETS = S1["assets"]

_PX = {"at": 0.0, "d": {}}
TTL = 900


_SRC = {}


def prices(asset, interval="1d", bars=800):
    """๊ฐ€๊ฒฉ ์บ์‹œ. ์–ด๋А ์†Œ์Šค๊ฐ€ ์‚ด์•„ ์žˆ๋“  ์ด ํ•จ์ˆ˜ ๋ฐ–์—์„œ๋Š” ์‹ ๊ฒฝ ์“ฐ์ง€ ์•Š๋Š”๋‹ค."""
    k = "%s|%s" % (asset, interval)
    if time.time() - _PX["at"] > TTL:
        _PX["d"].clear(); _PX["at"] = time.time()
    if k not in _PX["d"]:
        s, src, trail = FE.daily(asset, 2200)
        _SRC[asset] = {"source": src, "trail": trail,
                       "bars": 0 if s is None else len(s)}
        if s is None:
            # ๐Ÿ”ด ๋นˆ ์‹œ๋ฆฌ์ฆˆ๋ฅผ ์บ์‹œ์— ๋„ฃ์œผ๋ฉด TTL ๋™์•ˆ ๊ณ„์† ๋นˆ ๊ฐ’์„ ์ค€๋‹ค.
            #    ์†Œ์Šค๊ฐ€ ์ž ๊น ๋ง‰ํžŒ ๊ฒƒ๊ณผ ์˜์˜ ๋ง‰ํžŒ ๊ฒƒ์„ ๊ตฌ๋ถ„ํ•ด์•ผ ํ•œ๋‹ค.
            return pd.Series(dtype=float)
        _PX["d"][k] = s
    return _PX["d"][k].iloc[-bars:]


_HX = {"at": 0.0, "d": {}}


def hourly_px(asset):
    """์‹œ๊ฐ„๋ด‰ ์บ์‹œ. ์ฑ„์  ๊ฒฉ์ž๊ฐ€ ์ด๊ฑธ ์“ด๋‹ค."""
    if time.time() - _HX["at"] > 600:
        _HX["d"].clear(); _HX["at"] = time.time()
    if asset not in _HX["d"]:
        _HX["d"][asset] = FE.hourly(asset, 2000)
    return _HX["d"][asset]


def season_px(asset):
    """์‹œ์ฆŒ ๊ฐœ๋ง‰ ์ดํ›„ ๊ตฌ๊ฐ„. ์ฑ„์ ๊ณผ ๊ธฐ์ค€๋ถ„ํฌ๊ฐ€ ์ด๊ฑธ ๋ณธ๋‹ค.



    ๐Ÿ”‘ ์‹œ๊ฐ„๋ด‰์ด ์žˆ์œผ๋ฉด ์‹œ๊ฐ„๋ด‰์œผ๋กœ ์žฐ๋‹ค. ์ผ๋ด‰์œผ๋กœ ์ฑ„์ ํ•˜๋ฉด ๊ฐœ๋ง‰์ผ์— ํ•˜๋ฃจ๋ฅผ

       ํ†ต์งธ๋กœ ๊ธฐ๋‹ค๋ ค์•ผ ์ฒซ ์ˆ˜์ต๋ฅ ์ด ๋‚˜์˜ค๋Š”๋ฐ, ๊ทœ์น™์€ '๋งค์‹œ๊ฐ„ ๊ฐฑ์‹  ๊ฐ€๋Šฅ'์ด๋ผ๊ณ 

       ๋งํ•˜๊ณ  ์žˆ๋‹ค. ์žฌ๋Š” ๋‹จ์œ„์™€ ์•ฝ์†ํ•œ ๋‹จ์œ„๊ฐ€ ๋‹ค๋ฅด๋ฉด ์•ˆ ๋œ๋‹ค.

       ์‹œ๊ฐ„๋ด‰์ด ์•„์ง ์—†๋Š” ์ข…๋ชฉ์€ ์ผ๋ด‰์œผ๋กœ ๋‚ด๋ ค๊ฐ„๋‹ค โ€” ๋น„์–ด ์žˆ๋Š” ๊ฒƒ๋ณด๋‹ค ๋‚ซ๋‹ค.

    """
    op = pd.Timestamp(S1["opens"])
    h = hourly_px(asset)
    if h is not None and len(h):
        sub = h[h.index >= op]
        if len(sub) >= 2:
            return sub
    d = prices(asset, "1d", 2000)
    return d[d.index >= op]


def rules_doc(lang="ko"):
    T = lambda d: I.t(d, lang)
    return {
        "lang": lang,
        "season": S1["name"], "opens": S1["opens"], "closes": S1["closes"],
        "days": (pd.Timestamp(S1["closes"]) - pd.Timestamp(S1["opens"])).days,
        "prize": T(I.RULES["prize"]) % (S1["prize_usd_per_asset"],
                                        S1["prize_total_usd"]),
        "leverage": T(I.RULES["leverage"]),
        "update": T(I.RULES["update"]),
        "fees": {k: SC.fee_of(k) for k in ASSETS},
        "fee_note": T(I.RULES["fee_note"]),
        "scoring": T(I.RULES["scoring"]),
        "participation": T(I.RULES["participation"]),
        "assets": {k: {"label": T(I.ASSET[k]["label"]), "why": T(I.ASSET[k]["why"]),
                       "vol_annual": v["vol"], "hours": v["hours"]}
                   for k, v in ASSETS.items()},
        "types": {k: I.t(v, lang) for k, v in I.TYPE.items()},
        "warning": T(I.RULES["warning"]),
        "manifesto": T(I.MANIFESTO["title"]) + " โ€” " + T(I.MANIFESTO["sub"]),
        # ์šด์˜ ํ•œ๊ณ„์„ . ์‹ค๋ ฅ 0 ์ฐธ๊ฐ€์ž๋ฅผ 20,000ํšŒ ๋Œ๋ ค ๋‚ธ ์ƒ์œ„ 5% ์ง€์ ์ด๋‹ค.
        # ์ด ๊ฐ’ ์•„๋ž˜์˜ ์ˆ˜์ต์€ ์šด์œผ๋กœ๋„ ์„ค๋ช…๋œ๋‹ค.
        "luck_ceiling": {k: round(v["p95"], 4) for k, v in CEIL.items()},
        "luck_note": T(I.RULES["luck_note"]),
    }


def _sign(payload):
    raw = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
    sig = hmac.new(SESSION_KEY.encode(), raw.encode(), hashlib.sha256).hexdigest()[:32]
    return raw + "." + sig


def _unsign(token):
    try:
        raw, sig = (token or "").rsplit(".", 1)
    except ValueError:
        return None
    good = hmac.new(SESSION_KEY.encode(), raw.encode(), hashlib.sha256).hexdigest()[:32]
    if not hmac.compare_digest(sig, good):
        return None
    pad = "=" * (-len(raw) % 4)
    try:
        return json.loads(base64.urlsafe_b64decode(raw + pad))
    except Exception:
        return None


def current_user(request):
    return _unsign(request.cookies.get(COOKIE))


def _redirect_uri(request):
    if SPACE_HOST:
        return "https://%s/auth/callback" % SPACE_HOST
    return str(request.base_url).rstrip("/") + "/auth/callback"


def lang_of(request, explicit=None):
    """๋ธŒ๋ผ์šฐ์ € ์–ธ์–ด๋ฅผ ์ž๋™ ์‹๋ณ„ํ•œ๋‹ค. ์‚ฌ์šฉ์ž๊ฐ€ ๊ณ ๋ฅธ ๊ฐ’์ด ์žˆ์œผ๋ฉด ๊ทธ๊ฒŒ ์ด๊ธด๋‹ค."""
    return I.pick(request.headers.get("accept-language"),
                  explicit or request.cookies.get("finchal_lang")
                  or request.query_params.get("lang"))


def me_from(key, lang="ko"):
    u = L.user_by_key(key or "")
    if not u:
        raise PermissionError(I.t(I.HINT["need_key"], lang))
    return u


def score_asset(asset):
    """๊ทธ ์ข…๋ชฉ ์ฐธ๊ฐ€์ž ์ „์›์„ ์ฑ„์ ํ•œ๋‹ค. ๊ธฐ์ค€๋ถ„ํฌ๋Š” ์‹œ์ฆŒ ์‹ค์ œ ๊ฒฝ๋กœ๋กœ ๋งŒ๋“ ๋‹ค."""
    px = season_px(asset)
    if len(px) < 2:
        # ๐Ÿ”ด ๊ฐœ๋ง‰์ผ์—๋Š” ์ฑ„์ ํ•  ๊ตฌ๊ฐ„์ด ์—†๋‹ค. ๊ทธ๋ ‡๋‹ค๊ณ  ๋นˆ ํ‘œ๋ฅผ ๋‚ด๋ณด๋‚ด๋ฉด
        #    ์ด๋ฏธ ์ ‘์ˆ˜ํ•œ ์ฐธ๊ฐ€์ž์—๊ฒŒ "์•„๋ฌด๋„ ์—†๋‹ค"๊ณ  ๋งํ•˜๋Š” ์…ˆ์ด๊ณ , ๋ฐฉ๋ฌธ์ž์—๊ฒŒ๋Š”
        #    ๊ณ ์žฅ์œผ๋กœ ๋ณด์ธ๋‹ค. ์ ‘์ˆ˜๋œ ์‚ฌ์‹ค์€ ๊ทธ๋Œ€๋กœ ๋ณด์—ฌ ์ฃผ๊ณ  ์ˆ˜์น˜๋งŒ ๋น„์›Œ ๋‘”๋‹ค.
        users = {u["user"]: u for u in L.all_users()}
        seen, out = set(), []
        for r in L.positions(asset):
            seen.add(r["u"])
        for uid in seen:
            u = users.get(uid, {})
            last = L.latest(asset, uid)
            out.append({"user": uid, "strategy": u.get("strategy", "-"),
                        "type": u.get("type", "agent"),
                        "joined": u.get("joined", ""),
                        "ret": None, "score": None, "luck_p95": None,
                        "turnover": None, "fee_paid": None, "valid": None,
                        "position": last["p"] if last else None,
                        "pending": True,
                        "n_sub": len(L.positions(asset, uid))})
        out.sort(key=lambda x: x["joined"])
        for i, r in enumerate(out, 1):
            r["rank"] = i
        return out
    fee = SC.fee_of(asset)
    # ๐Ÿ”ด ํ‘œ๋ณธ์ด ์–‡์œผ๋ฉด ์‹ค์‹œ๊ฐ„ ๊ธฐ์ค€๋ถ„ํฌ์˜ ํญ์ด ๊ฑฐ์˜ 0์ด๋ผ, ์†์‹ค์„ ๋‚ธ ์ฐธ๊ฐ€์ž์—๊ฒŒ๋„
    #    '์šด์˜ ํ•œ๊ณ„์„  ๋ŒํŒŒ'๊ฐ€ ๋ถ™๋Š”๋‹ค. ์‹ค์ œ๋กœ ๊ธˆ์—์„œ โˆ’0.033%์— ํ‘œ์‹œ๊ฐ€ ๋ถ™์—ˆ๋‹ค.
    #    ์žก์Œ์„ ์„ฑ์ ์œผ๋กœ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒƒ์ด ์ด ๋Œ€ํšŒ๊ฐ€ ์—†์• ๋ ค๋Š” ๋ฌธ์ œ ๊ทธ ์ž์ฒด์ด๋ฏ€๋กœ,
    #    ๊ตฌ๊ฐ„์ด ์ถฉ๋ถ„ํžˆ ์Œ“์ด๊ธฐ ์ „์—๋Š” ํŒ์ • ์ž์ฒด๋ฅผ ๋‚ด๋ฆฌ์ง€ ์•Š๋Š”๋‹ค.
    span_days = (px.index[-1] - px.index[0]).days
    luck_ready = span_days >= 5 and len(px) >= 30
    recs = L.positions(asset)
    rows = []
    by_user = {}
    for r in recs:
        by_user.setdefault(r["u"], {})[pd.Timestamp(r["t"]).tz_localize(None)] = r["p"]
    users = {u["user"]: u for u in L.all_users()}
    for uid, pos in by_user.items():
        ret = SC.total_return(pos, px, asset)
        expo = float(np.abs(pd.Series(pos).reindex(
            px.index, method="ffill").fillna(0.0)).mean())
        refv = RF.live(px, fee, expo=max(expo, 0.05), n=3000)
        u = users.get(uid, {})
        rows.append({
            "user": uid, "strategy": u.get("strategy", "-"),
            "type": u.get("type", "agent"),
            "joined": u.get("joined", ""),
            "ret": ret, "score": SC.score(ret, refv),
            "luck_p95": float(np.percentile(refv, 95)),
            "luck_ready": luck_ready, "span_days": span_days,
            "turnover": SC.turnover(pos, px),
            "fee_paid": SC.fee_paid(pos, px, asset),
            "valid": SC.valid_ratio(pos, px),
            "n_sub": len(L.positions(asset, uid)),
        })
    rows.sort(key=lambda x: -x["ret"])
    for i, r in enumerate(rows, 1):
        r["rank"] = i
    return rows


_SC = {}
SC_TTL = 300


def score_cached(asset):
    """์ฑ„์ ์€ ์ฐธ๊ฐ€์ž๋งˆ๋‹ค ๊ธฐ์ค€๋ถ„ํฌ 3,000๊ฒฝ๋กœ๋ฅผ ๋Œ๋ฆฐ๋‹ค. ๋งค ์š”์ฒญ๋งˆ๋‹ค ํ•˜๋ฉด ํ™”๋ฉด์ด ์ฃฝ๋Š”๋‹ค."""
    e = _SC.get(asset)
    if e and time.time() - e[0] < SC_TTL:
        return e[1]
    r = score_asset(asset)
    _SC[asset] = (time.time(), r)
    return r


def curves(asset, top=12):
    """์ฐธ๊ฐ€์ž๋ณ„ ๋ˆ„์  ์ˆ˜์ต๋ฅ  ๊ณก์„ . ํ™”๋ฉด์˜ ๊บพ์€์„  ๊ทธ๋ž˜ํ”„๊ฐ€ ์ด๊ฑธ ๊ทธ๋ฆฐ๋‹ค."""
    px = season_px(asset)
    if len(px) < 2:
        return {"t": [], "series": []}
    rows = score_cached(asset)
    users = {u["user"]: u for u in L.all_users()}
    keep = [r["user"] for r in rows[:top]]
    ser = []
    for uid in keep:
        pos = {}
        for r in L.positions(asset, uid):
            pos[pd.Timestamp(r["t"]).tz_localize(None)] = r["p"]
        if not pos:
            continue
        eq, _ = SC.equity(pos, px, asset)
        u = users.get(uid, {})
        ser.append({"user": uid, "strategy": u.get("strategy", "-"),
                    "type": u.get("type", "agent"),
                    "v": [round(float(x - 1) * 100, 4) for x in eq]})
    # ์‹œ์žฅ ์ž์ฒด๋„ ํ•œ ์ค„๋กœ ๊น”์•„ ์ค€๋‹ค โ€” ์ฐธ๊ฐ€์ž๊ฐ€ ๋ฌด์—‡์„ ์ด๊ฒจ์•ผ ํ•˜๋Š”์ง€ ๋ณด์ด๊ฒŒ
    mk = (px / px.iloc[0] - 1) * 100
    return {"t": [t.isoformat() for t in px.index],
            "market": [round(float(x), 4) for x in mk],
            "series": ser}


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ REST โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@app.get("/api/rules")
def api_rules(request: Request, lang: str = None):
    return {"ok": True, **rules_doc(lang_of(request, lang))}


@app.get("/api/me")
def api_me(request: Request):
    u = current_user(request)
    out = {"signed_in": bool(u), "user": u,
           "oauth_configured": bool(OAUTH_ID and OAUTH_SECRET),
           "lang": lang_of(request)}
    if u:
        # ๋กœ๊ทธ์ธํ•œ ์‚ฌ๋žŒ์€ ๋“ฑ๋ก์„ ๋”ฐ๋กœ ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. ํ‚ค๋ฅผ ๋ฐ”๋กœ ์ค€๋‹ค.
        out["key"] = L.make_key(u["name"])
        rec = next((x for x in L.all_users() if x["user"] == u["name"]), None)
        out["strategy"] = (rec or {}).get("strategy", "")
        out["joined"] = (rec or {}).get("joined")
    return out


@app.get("/login")
def login(request: Request):
    if not (OAUTH_ID and OAUTH_SECRET):
        raise HTTPException(503, "OAuth is not configured (needs hf_oauth in README)")
    state = secrets.token_urlsafe(16)
    q = urllib.parse.urlencode({
        "client_id": OAUTH_ID, "redirect_uri": _redirect_uri(request),
        "response_type": "code", "scope": "openid profile", "state": state})
    r = RedirectResponse("%s/oauth/authorize?%s" % (OAUTH_ISS.rstrip("/"), q))
    # ์ œ๊ณต์ž๊ฐ€ ๋˜๋Œ๋ ค์ฃผ๋Š” state ๋ฅผ ์ด ์ฟ ํ‚ค์™€ ๋Œ€์กฐํ•˜๋Š” ๊ฒƒ์ด,
    # ์ œ3์ž๊ฐ€ ๋‚จ์˜ ๋กœ๊ทธ์ธ์„ ๊ฐ€๋กœ์ฑ„ ์™„๋ฃŒํ•˜๋Š” ๊ฒƒ์„ ๋ง‰๋Š” ์œ ์ผํ•œ ์ˆ˜๋‹จ์ด๋‹ค.
    r.set_cookie("finchal_state", state, max_age=600, httponly=True, **COOKIE_KW)
    return r


@app.get("/auth/callback")
def callback(request: Request, code: str = "", state: str = ""):
    lang = lang_of(request)
    saved = request.cookies.get("finchal_state")
    if not code:
        raise HTTPException(400, "No authorization code โ€” please sign in again")
    if not saved:
        # ์ฟ ํ‚ค๊ฐ€ ์ €์žฅ๋˜์ง€ ์•Š์€ ๊ฒƒ์ด๋‹ค. ์œ„์กฐ๊ฐ€ ์•„๋‹ˆ๋ผ ๋ธŒ๋ผ์šฐ์ € ์ •์ฑ… ๋ฌธ์ œ๋‹ค.
        raise HTTPException(400, (
            "๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์ฟ ํ‚ค๋ฅผ ์ €์žฅํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด ํŽ˜์ด์ง€๋ฅผ ์ƒˆ ํƒญ์—์„œ ์ง์ ‘ ์—ด๊ณ "
            "(.hf.space ์ฃผ์†Œ) ๋‹ค์‹œ ๋กœ๊ทธ์ธํ•ด ์ฃผ์„ธ์š”. 3์ž ์ฟ ํ‚ค ์ฐจ๋‹จ์ด ์›์ธ์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."
            if lang == "ko" else
            "Your browser did not store the cookie. Open this page directly in a new tab "
            "(the .hf.space address) and sign in again โ€” third-party cookie blocking is "
            "the usual cause."))
    if state != saved:
        raise HTTPException(400, "Sign-in state mismatch โ€” please try again")
    body = urllib.parse.urlencode({
        "client_id": OAUTH_ID, "client_secret": OAUTH_SECRET,
        "grant_type": "authorization_code", "code": code,
        "redirect_uri": _redirect_uri(request)}).encode()
    tr = urllib.request.Request(OAUTH_ISS.rstrip("/") + "/oauth/token", data=body,
                                headers={"Content-Type": "application/x-www-form-urlencoded"})
    with urllib.request.urlopen(tr, timeout=20) as r:
        tok = json.loads(r.read().decode())
    ur = urllib.request.Request(OAUTH_ISS.rstrip("/") + "/oauth/userinfo",
                                headers={"Authorization": "Bearer " + tok["access_token"]})
    with urllib.request.urlopen(ur, timeout=20) as r:
        ui = json.loads(r.read().decode())
    user = {"name": ui.get("preferred_username") or ui.get("name"),
            "picture": ui.get("picture"), "at": int(time.time())}
    resp = RedirectResponse("/")
    resp.set_cookie(COOKIE, _sign(user), max_age=60 * 60 * 24 * 14,
                    httponly=True, **COOKIE_KW)
    resp.delete_cookie("finchal_state")
    return resp


@app.get("/logout")
def logout():
    r = RedirectResponse("/")
    r.delete_cookie(COOKIE)
    return r


@app.get("/api/lang/{code}")
def set_lang(code: str):
    """์–ธ์–ด ์„ ํƒ์„ ๊ธฐ์–ตํ•œ๋‹ค. ์ž๋™ ์‹๋ณ„๋ณด๋‹ค ์‚ฌ์šฉ์ž์˜ ์„ ํƒ์ด ์šฐ์„ ํ•œ๋‹ค."""
    if code not in I.LANGS:
        return JSONResponse({"ok": False, "error": "unknown language"}, 400)
    r = JSONResponse({"ok": True, "lang": code})
    r.set_cookie("finchal_lang", code, max_age=60 * 60 * 24 * 365, **COOKIE_KW)
    return r


@app.get("/api/data")
def api_data(asset: str, bars: int = 500, interval: str = "1d"):
    if asset not in ASSETS:
        return JSONResponse({"ok": False, "error": "์•Œ ์ˆ˜ ์—†๋Š” ์ข…๋ชฉ"}, 400)
    if interval == "1h":
        h = hourly_px(asset)
        if h is None or not len(h):
            return JSONResponse({"ok": False,
                                 "error": "์‹œ๊ฐ„๋ด‰ ์—†์Œ / no hourly bars yet"}, 400)
        return {"ok": True, "asset": asset, "interval": "1h",
                "bars": [{"t": t.isoformat(), "c": float(v)}
                         for t, v in h.iloc[-min(max(bars, 10), 5000):].items()]}
    if interval != "1d":
        return JSONResponse({"ok": False,
                             "error": "1d ๋˜๋Š” 1h / 1d or 1h only"}, 400)
    s = prices(asset, interval, min(max(bars, 10), 5000))
    return {"ok": True, "asset": asset, "interval": interval,
            "bars": [{"t": t.isoformat(), "c": float(v)} for t, v in s.items()]}


# ๐Ÿ”ด ์ž์œจ ์—์ด์ „ํŠธ๋Š” ๋ธŒ๋ผ์šฐ์ € OAuth ๋ฅผ ํ†ต๊ณผํ•  ์ˆ˜ ์—†๋‹ค. ๊ทธ๋ ‡๋‹ค๊ณ  ์•„๋ฌด๋‚˜ ์ด๋ฆ„์„
#    ์ง€์–ด ๋“ฑ๋กํ•˜๊ฒŒ ๋‘๋ฉด ๋‚จ์˜ ์ด๋ฆ„์œผ๋กœ ์ œ์ถœํ•  ์ˆ˜ ์žˆ์–ด ์ˆœ์œ„ํ‘œ๊ฐ€ ๋ฌด์˜๋ฏธํ•ด์ง„๋‹ค.
#    ๊ทธ๋ž˜์„œ ๋ณ„๋„ ๊ด€๋ฆฌ ํ‚ค๋ฅผ ๊ฐ€์ง„ ์š”์ฒญ๋งŒ ์ง€์ • ์ด๋ฆ„์œผ๋กœ ๋“ฑ๋กํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค.
#    ์ด ํ‚ค๋Š” Space ์‹œํฌ๋ฆฟ์ด๊ณ , ๋ฐœ๊ธ‰ ๋Œ€์ƒ์€ ์šด์˜์ž๊ฐ€ ์ง์ ‘ ํ™•์ธํ•œ ๊ณ„์ •๋ฟ์ด๋‹ค.
ADMIN_KEY = os.environ.get("FINCHAL_ADMIN_KEY", "")


@app.post("/api/agent/enroll")
async def api_agent_enroll(req: Request, x_finchal_admin: str = Header(None)):
    """ํ—ค๋“œ๋ฆฌ์Šค ์—์ด์ „ํŠธ ๋“ฑ๋ก. ๊ด€๋ฆฌ ํ‚ค๊ฐ€ ์žˆ์–ด์•ผ ํ•œ๋‹ค."""
    if not ADMIN_KEY or (x_finchal_admin or "").strip() != ADMIN_KEY:
        return JSONResponse({"ok": False, "error": "not authorized"}, 403)
    b = await req.json()
    u = L.register(b["user"], b.get("strategy", "-"), b.get("type", "agent"),
                   b.get("assets", list(ASSETS)))
    return {"ok": True, **u}


@app.post("/api/register")
async def api_register(req: Request):
    b = await req.json()
    sess = current_user(req)
    if OAUTH_ID and OAUTH_SECRET:
        if not (sess and sess.get("name")):
            return JSONResponse({"ok": False, "error":
                ("Hugging Face ๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค" if lang_of(req) == "ko"
                 else "Please sign in with Hugging Face")}, 401)
        who = sess["name"]          # ์‹ ์›์€ ์ œ์ถœ์ž๊ฐ€ ์ •ํ•˜์ง€ ์•Š๋Š”๋‹ค
    else:
        who = b["user"]
    u = L.register(who, b.get("strategy", "-"),
                   b.get("type", "human" if sess else "agent"),
                   b.get("assets", list(ASSETS)))
    return {"ok": True, **u}


@app.post("/api/submit")
async def api_submit(req: Request, authorization: str = Header(None),

                     x_finchal_key: str = Header(None)):
    b = await req.json()
    lang = lang_of(req)
    # Authorization ์€ ์•ž๋‹จ ํ”„๋ก์‹œ๊ฐ€ ์ž๊ธฐ ์ธ์ฆ์— ์“ฐ๊ธฐ๋„ ํ•œ๋‹ค. ๊ทธ๋•Œ ์ฐธ๊ฐ€ํ‚ค๊ฐ€
    # ์•ฑ๊นŒ์ง€ ์˜ค์ง€ ์•Š๋Š”๋‹ค. ์ „์šฉ ํ—ค๋”๋ฅผ ํ•จ๊ป˜ ๋ฐ›์•„ ๊ทธ ์ถฉ๋Œ์„ ํ”ผํ•œ๋‹ค.
    key = ((x_finchal_key or "").strip()
           or (authorization or "").replace("Bearer ", "").strip()
           or b.get("key", ""))
    # ๐Ÿ”‘ ํ™”๋ฉด์—์„œ ์˜จ ์š”์ฒญ์€ Hugging Face ๋กœ๊ทธ์ธ ์ฟ ํ‚ค๊ฐ€ ๊ณง ์‹ ์›์ด๋‹ค.
    #    ์ž์œ  ์ž…๋ ฅ ID๋ฅผ ํ—ˆ์šฉํ•˜๋ฉด ๋‚จ์˜ ์ด๋ฆ„์œผ๋กœ ์ œ์ถœํ•  ์ˆ˜ ์žˆ๊ณ  ์ˆœ์œ„ํ‘œ๊ฐ€ ๋ฌด์˜๋ฏธํ•ด์ง„๋‹ค.
    sess = current_user(req)
    if sess and sess.get("name"):
        u = L.register(sess["name"], b.get("strategy", "-"),
                       b.get("type", "human"), list(ASSETS))
    else:
        if OAUTH_ID and OAUTH_SECRET and not key:
            return JSONResponse({"ok": False, "error":
                ("Hugging Face ๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค" if lang == "ko"
                 else "Please sign in with Hugging Face")}, 401)
        try:
            u = me_from(key, lang)
        except PermissionError as e:
            return JSONResponse({"ok": False, "error": str(e)}, 401)
    if b["asset"] not in ASSETS:
        return JSONResponse({"ok": False, "error": "์•Œ ์ˆ˜ ์—†๋Š” ์ข…๋ชฉ"}, 400)
    r = L.submit(u["user"], b["asset"], b["position"], b.get("source", "rest"))
    _SC.pop(b["asset"], None)      # ๋ฐฉ๊ธˆ ๋‚ธ ์‚ฌ๋žŒ์ด ํ‘œ์—์„œ ์ž๊ธฐ๋ฅผ ๋ชป ์ฐพ์œผ๋ฉด ์•ˆ ๋œ๋‹ค
    return {"ok": True, **r}


@app.get("/api/leaderboard")
def api_leaderboard(asset: str):
    if asset not in ASSETS:
        return JSONResponse({"ok": False, "error": "์•Œ ์ˆ˜ ์—†๋Š” ์ข…๋ชฉ"}, 400)
    return {"ok": True, "asset": asset, "rows": score_cached(asset)}


@app.get("/api/curves")
def api_curves(asset: str, top: int = 12):
    if asset not in ASSETS:
        return JSONResponse({"ok": False, "error": "์•Œ ์ˆ˜ ์—†๋Š” ์ข…๋ชฉ"}, 400)
    return {"ok": True, "asset": asset, **curves(asset, top)}


_BLC = {}


@app.get("/api/baselines")
def api_baselines(request: Request, asset: str, lang: str = None):
    """๊ต๊ณผ์„œ ๊ทœ์น™๋“ค์„ ์ตœ๊ทผ ๊ตฌ๊ฐ„์— ์ ์šฉํ•œ ๋˜๋Œ์•„๋ณด๊ธฐ. ์ฐธ๊ฐ€์ž ๊ณก์„ ์˜ ์ฒ™๋„๋กœ ์“ด๋‹ค."""
    if asset not in ASSETS:
        return JSONResponse({"ok": False, "error": "์•Œ ์ˆ˜ ์—†๋Š” ์ข…๋ชฉ"}, 400)
    g = lang_of(request, lang)
    k = "%s|%s" % (asset, g)
    e = _BLC.get(k)
    if not e or time.time() - e[0] > 1800:
        _BLC[k] = (time.time(), BL.curves(prices(asset, "1d", 400), asset, SC, g))
    return {"ok": True, "asset": asset, **_BLC[k][1]}


@app.get("/api/manifesto")
def api_manifesto(request: Request, lang: str = None):
    g = lang_of(request, lang)
    T = lambda d: I.t(d, g)
    M = I.MANIFESTO
    s2 = S.SEASONS.get(2, {})
    return {"ok": True, "lang": g,
            "title": T(M["title"]), "sub": T(M["sub"]),
            "acts": [[T(a), T(b)] for a, b in M["acts"]],
            "why": [[T(a), T(b)] for a, b in M["why"]],
            "how": [[T(a), T(b)] for a, b in M["how"]],
            "our_stake": T(M["our_stake"]),
            "anchors": {k: T(v) for k, v in I.ANCHOR.items()},
            "season2": {"name": ("์‹œ์ฆŒ 2 ยท ์˜ˆ๊ณ " if g == "ko" else "Season 2 ยท Coming"),
                        "teaser": ("์„ ๋ฌผ๊ณผ ์›์ž์žฌ, ๊ทธ๋ฆฌ๊ณ  ์™ธํ™˜" if g == "ko"
                                   else "Futures, commodities and currencies"),
                        "note": ("์ข…๋ชฉ์€ ์‹œ์ฆŒ 1 ์ข…๋ฃŒ ํ›„ ํ™•์ •ํ•ฉ๋‹ˆ๋‹ค." if g == "ko"
                                 else "Assets will be announced after Season 1 closes.")}}


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ MCP โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def _call(name, args, key=None, lang="ko"):
    T = lambda d: I.t(d, lang)
    if name == "get_rules":
        return rules_doc(lang)
    if name == "get_data":
        a = args["asset"]
        if a not in ASSETS:
            return {"error": T(I.HINT["unknown_asset"]) % list(ASSETS)}
        iv = args.get("interval", "1d")
        n = min(args.get("bars", 500), 5000)
        if iv == "1h":
            h = hourly_px(a)
            if h is None or not len(h):
                return {"error": ("์ด ์ข…๋ชฉ์€ ์•„์ง ์‹œ๊ฐ„๋ด‰์ด ์—†์Šต๋‹ˆ๋‹ค. '1d' ๋ฅผ ์“ฐ์‹ญ์‹œ์˜ค."
                                  if lang == "ko" else
                                  "No hourly bars for this asset yet. Use '1d'.")}
            return {"asset": a, "interval": "1h",
                    "bars": [{"t": t.isoformat(sep=" "), "c": round(float(v), 6)}
                             for t, v in h.iloc[-n:].items()]}
        if iv != "1d":
            # ์š”์ฒญ์„ ์กฐ์šฉํžˆ ๋ฌด์‹œํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋ชป ์ฃผ๋Š” ๊ฒƒ์€ ๋ชป ์ค€๋‹ค๊ณ  ๋งํ•œ๋‹ค.
            return {"error": ("interval ์€ '1d' ๋˜๋Š” '1h' ๋งŒ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."
                              if lang == "ko" else
                              "interval must be '1d' or '1h'.")}
        s = prices(a, iv, n)
        return {"asset": a, "interval": "1d",
                "bars": [{"t": t.date().isoformat(), "c": round(float(v), 6)}
                         for t, v in s.items()]}
    if name == "submit_position":
        u = me_from(key, lang)
        a = args["asset"]
        if a not in ASSETS:
            return {"error": T(I.HINT["unknown_asset"]) % list(ASSETS)}
        r = L.submit(u["user"], a, args["position"], "mcp")
        _SC.pop(a, None)
        return {"accepted": True, "asset": a, "position": r["p"], "at": r["t"],
                "note": T(I.HINT["kept"])}
    if name == "check_score":
        u = me_from(key, lang)
        want = [args["asset"]] if args.get("asset") else u.get("assets", list(ASSETS))
        out = []
        for a in want:
            if a not in ASSETS:
                continue
            rows = score_asset(a)
            mine = next((r for r in rows if r["user"] == u["user"]), None)
            if not mine:
                last = L.latest(a, u["user"])
                out.append({"asset": a, "status": T(I.HINT["pending"]),
                            "position": last["p"] if last else None,
                            "hint": T(I.HINT["have_pos"] if last
                                      else I.HINT["no_pos"])})
            elif mine.get("pending") or mine.get("ret") is None:
                # ๐Ÿ”ด ํ‘œ์—๋Š” ์˜ฌ๋ผ์™€ ์žˆ์ง€๋งŒ ์•„์ง ์žด ๊ตฌ๊ฐ„์ด ์—†๋‹ค. ์—ฌ๊ธฐ์„œ ์ˆ˜์น˜๋ฅผ
                #    ๋ฐ˜์˜ฌ๋ฆผํ•˜๋ ค ๋“ค๋ฉด None ์— ๊ฑธ๋ ค ๋„๊ตฌ ํ˜ธ์ถœ ์ž์ฒด๊ฐ€ ์‹คํŒจํ•œ๋‹ค.
                out.append({"asset": a, "status": T(I.HINT["pending"]),
                            "position": mine.get("position"),
                            "of": len(rows),
                            "hint": T(I.HINT["have_pos"])})
            else:
                out.append({"asset": a, "rank": mine["rank"], "of": len(rows),
                            "return": round(mine["ret"], 4),
                            "luck_ceiling": round(mine["luck_p95"], 4),
                            "score": round(mine["score"], 2),
                            "fee_paid": round(mine["fee_paid"], 4),
                            "hint": T(I.HINT["over"] if mine["ret"] > mine["luck_p95"]
                                      else I.HINT["under"])})
        return {"user": u["user"], "strategy": u.get("strategy"), "results": out}
    return {"error": "๋ฏธ๊ตฌํ˜„"}


@app.post("/mcp")
async def mcp_endpoint(req: Request, authorization: str = Header(None),

                       x_finchal_key: str = Header(None)):
    body = await req.json()
    lang = lang_of(req)
    key = ((x_finchal_key or "").strip()
           or (authorization or "").replace("Bearer ", "").strip())
    resp = MCP.handle(body, lambda n, a: _call(n, a, key, lang), lang)
    if resp is None:
        return JSONResponse({}, 202)
    return JSONResponse(resp)


@app.get("/llms.txt", response_class=PlainTextResponse)
def llms(request: Request, lang: str = None):
    """์—์ด์ „ํŠธ๊ฐ€ ๋จผ์ € ์ฝ๋Š” ์š”์•ฝ. ๋„๊ตฌ ์„ค๋ช…๊ณผ ๊ฐ™์€ ์–ธ์–ด์—ฌ์•ผ ํ•œ๋‹ค."""
    g = lang_of(request, lang)
    r = rules_doc(g)
    a = ", ".join("%s (%s)" % (k, v["label"]) for k, v in r["assets"].items())
    N = "\n"
    if g == "en":
        return (("# %s" + N + N) % r["manifesto"] +
                "You take real positions and compete on returns. "
                "This is trading, not calling direction." + N + N +
                ("Assets: %s" + N) % a +
                ("Season: %s to %s" + N) % (r["opens"], r["closes"]) +
                ("Prize: %s" + N) % r["prize"] +
                ("Position: %s" + N) % r["leverage"] +
                ("Updates: %s" + N) % r["update"] +
                "Fees: charged on position changes only. "
                "Flipping often loses money." + N +
                ("Scoring: %s" + N + N) % r["scoring"] +
                "Start: get_rules() -> get_data() -> build your own model "
                "-> submit_position()" + N)
    return (("# %s" + N + N) % r["manifesto"] +
            "๋‹น์‹ ์€ ์‹ค์ œ ํฌ์ง€์…˜์„ ์žก์•„ ์ˆ˜์ต๋ฅ ๋กœ ๊ฒจ๋ฃน๋‹ˆ๋‹ค. ๋ฐฉํ–ฅ ์˜ˆ์ธก์ด ์•„๋‹ˆ๋ผ ๋งค๋งค์ž…๋‹ˆ๋‹ค."
            + N + N +
            ("์ข…๋ชฉ: %s" + N) % a +
            ("๊ธฐ๊ฐ„: %s ~ %s" + N) % (r["opens"], r["closes"]) +
            ("์ƒ๊ธˆ: %s" + N) % r["prize"] +
            ("ํฌ์ง€์…˜: %s" + N) % r["leverage"] +
            ("๊ฐฑ์‹ : %s" + N) % r["update"] +
            "์ˆ˜์ˆ˜๋ฃŒ: ํฌ์ง€์…˜ ๋ณ€๊ฒฝ๋ถ„์—๋งŒ. ์ž์ฃผ ๋’ค์ง‘์œผ๋ฉด ์†ํ•ด์ž…๋‹ˆ๋‹ค" + N +
            ("์ฑ„์ : %s" + N + N) % r["scoring"] +
            "์‹œ์ž‘: get_rules() โ†’ get_data() โ†’ ์ง์ ‘ ๋ชจ๋ธ๋ง โ†’ submit_position()" + N)


STATIC = os.path.join(HERE, "static")
if os.path.isdir(STATIC):
    app.mount("/static", StaticFiles(directory=STATIC), name="static")


@app.get("/")
def index():
    f = os.path.join(STATIC, "index.html")
    if not os.path.exists(f):
        return JSONResponse({"ok": True, "note": "ํ™”๋ฉด ์ค€๋น„ ์ค‘", **rules_doc()})
    return FileResponse(f, headers={"Cache-Control": "no-cache"})


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ๊ธฐ์ค€์„  ์ž๋™ ์ œ์ถœ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def _anchor_loop():
    """ํ•˜๋ฃจ ํ•œ ๋ฒˆ ๊ธฐ์ค€์„  ์…‹์˜ ํฌ์ง€์…˜์„ ๋‚ธ๋‹ค.



    ๐Ÿ”‘ ์‹คํŒจํ•ด๋„ ์„œ๋ฒ„๋ฅผ ์ฃฝ์ด๋ฉด ์•ˆ ๋œ๋‹ค. ๊ธฐ์ค€์„ ์€ ์ฒ™๋„์ด์ง€ ์„œ๋น„์Šค๊ฐ€ ์•„๋‹ˆ๋‹ค.

       yfinance๊ฐ€ ์ž ๊น ๋ง‰ํ˜€๋„ ํ™”๋ฉด๊ณผ ์ฐธ๊ฐ€์ž ์ œ์ถœ์€ ๊ณ„์† ๋Œ์•„๊ฐ€์•ผ ํ•œ๋‹ค.

    """
    import traceback
    import anchors as A
    while True:
        try:
            A.run(list(ASSETS), lambda a: prices(a, "1d", 1500),
                  opens=S1["opens"] + "T00:00:00+00:00")
            _SC.clear()
        except Exception:
            traceback.print_exc()
        time.sleep(6 * 3600)


# ๐Ÿ”‘ ์›์žฅ ๋ณต์›์€ **๋‹ค๋ฅธ ๋ฌด์—‡๋ณด๋‹ค ๋จผ์ €**๋‹ค. ๋ณต์› ์ „์— ๋ถ€ํŒ… ํ‘œ์‹์„ ์“ฐ๋ฉด
#    ๊ทธ ํ‘œ์‹์ด ๋ฏธ๋Ÿฌ๋ฅผ ๋ฎ์–ด ์›์žฅ์„ ์ง€์šด๋‹ค.
_RESTORE = L.restore()
_DUR = L.boot_check()


def _flush_loop():
    """์›์žฅ์„ ์ฃผ๊ธฐ์ ์œผ๋กœ ๋ฏธ๋Ÿฌ์— ์˜ฌ๋ฆฐ๋‹ค. ์ œ์ถœ๋งˆ๋‹ค ์ปค๋ฐ‹ํ•˜๋ฉด ์ €์žฅ์†Œ๊ฐ€ ํ„ฐ์ง„๋‹ค."""
    import traceback
    while True:
        time.sleep(90)
        try:
            L.flush()
        except Exception:
            traceback.print_exc()


@app.on_event("startup")
def _startup():
    import threading
    print("[finchal] ์›์žฅ %s ยท ๋ฏธ๋Ÿฌ %s" % (L.ROOT, _RESTORE))
    if L.MIRROR:
        threading.Thread(target=_flush_loop, daemon=True).start()
    if os.environ.get("FINCHAL_NO_ANCHOR"):
        return
    threading.Thread(target=_anchor_loop, daemon=True).start()


@app.get("/api/diag")
def api_diag():
    """์–ด๋А ์†Œ์Šค์—์„œ ์‹œ์„ธ๊ฐ€ ์˜ค๋Š”์ง€ ์‹ค์ธกํ•œ๋‹ค.



    ๐Ÿ”‘ ๋กœ์ปฌ์—์„œ ๋˜๋Š”์ง€๋Š” ์•„๋ฌด ์˜๋ฏธ๊ฐ€ ์—†๋‹ค. ๋ง‰ํžˆ๋Š” ๊ณณ์€ ์„œ๋ฒ„๋‹ค.

    """
    out = {}
    for a in ASSETS:
        s = prices(a, "1d", 5)
        out[a] = {**_SRC.get(a, {}),
                  "last": None if not len(s) else round(float(s.iloc[-1]), 4),
                  "at": None if not len(s) else s.index[-1].date().isoformat()}
    return {"ok": all(v.get("bars") for v in out.values()), "assets": out}


@app.get("/health")
def health():
    return {"ok": True, "season": S1["name"], "assets": list(ASSETS),
            "ledger": L.ROOT, "durability": _DUR[0], "boots": _DUR[1],
            "mirror": L.mirror_status(), "restore": _RESTORE,
            "warn": None if (_DUR[0] == "ํ™•์ธ๋จ" or L.mirror_status()["restored"])
                    else "์›์žฅ์ด ์žฌ์‹œ์ž‘์„ ๊ฒฌ๋”˜๋‹ค๋Š” ์ฆ๊ฑฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. "
                         "๋ฏธ๋Ÿฌ(FINCHAL_MIRROR)๋‚˜ ์˜์† ์Šคํ† ๋ฆฌ์ง€๋ฅผ ๋ถ™์ด์‹ญ์‹œ์˜ค."}