refactor: 프로젝트명 bithumb으로 변경 및 futures 파이프라인 제거
deepcoin 패키지를 bithumb으로 rename하고, 3단계 live 운영·사이징 튜닝·텔레그램 알림을 통합한다. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -16,10 +16,10 @@ if str(SRC) not in sys.path:
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.data.candle_store import CandleStore
|
||||
from deepcoin.data.downloader import CandleDownloader
|
||||
from deepcoin.data.intervals import INTERVAL_1MIN, estimate_download_requests, interval_label
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.data.candle_store import CandleStore
|
||||
from bithumb.data.downloader import CandleDownloader
|
||||
from bithumb.data.intervals import INTERVAL_1MIN, estimate_download_requests, interval_label
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
|
||||
@@ -15,10 +15,10 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import Settings, load_settings
|
||||
from deepcoin.data.intervals import interval_label
|
||||
from deepcoin.ground_truth.chart import render_ground_truth_chart
|
||||
from deepcoin.ground_truth.ground_truth import GtParams, build_ground_truth, save_ground_truth
|
||||
from bithumb.config import Settings, load_settings
|
||||
from bithumb.data.intervals import interval_label
|
||||
from bithumb.ground_truth.chart import render_ground_truth_chart
|
||||
from bithumb.ground_truth.ground_truth import GtParams, build_ground_truth, save_ground_truth
|
||||
|
||||
TIER_DESCRIPTIONS = {
|
||||
"v1": "스윙만 (최소 매수·매도)",
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""0단계: 선물 GT 타점 차트 (현물 GT → 롱·숏 4색 마커)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import Settings, load_settings
|
||||
from deepcoin.ground_truth.futures import futures_events_from_gt_signals
|
||||
from deepcoin.ground_truth.futures_chart import render_futures_ground_truth_chart
|
||||
from deepcoin.ground_truth.ground_truth import save_ground_truth
|
||||
|
||||
TIER_DESCRIPTIONS = {
|
||||
"v1": "스윙만 (최소 매수·매도)",
|
||||
"v2": "스윙 + 눌림목",
|
||||
"v3": "스윙 + 눌림목 + 돌파 + 다이버전스",
|
||||
}
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
"""로깅 레벨을 설정한다."""
|
||||
level = logging.DEBUG if verbose else logging.INFO
|
||||
logging.basicConfig(
|
||||
level=level,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
|
||||
|
||||
def _tier_targets(
|
||||
settings: Settings,
|
||||
tier_arg: str,
|
||||
) -> list[tuple[str, Path, Path, Path]]:
|
||||
"""생성할 티어 목록 (tier, spot_json, futures_json, futures_chart)."""
|
||||
all_tiers: dict[str, tuple[Path, Path, Path]] = {
|
||||
"v1": (
|
||||
settings.ground_truth_v1_file,
|
||||
settings.ground_truth_futures_v1_file,
|
||||
settings.ground_truth_futures_chart_v1_file,
|
||||
),
|
||||
"v2": (
|
||||
settings.ground_truth_v2_file,
|
||||
settings.ground_truth_futures_v2_file,
|
||||
settings.ground_truth_futures_chart_v2_file,
|
||||
),
|
||||
"v3": (
|
||||
settings.ground_truth_file,
|
||||
settings.ground_truth_futures_file,
|
||||
settings.ground_truth_futures_chart_v3_file,
|
||||
),
|
||||
}
|
||||
if tier_arg == "all":
|
||||
return [(t, *paths) for t, paths in all_tiers.items()]
|
||||
return [(tier_arg, *all_tiers[tier_arg])]
|
||||
|
||||
|
||||
def _load_gt(json_path: Path) -> dict[str, Any]:
|
||||
"""GT JSON을 로드한다."""
|
||||
with json_path.open(encoding="utf-8") as fp:
|
||||
return json.load(fp)
|
||||
|
||||
|
||||
def _build_futures_gt(spot_gt: dict[str, Any]) -> dict[str, Any]:
|
||||
"""현물 GT JSON을 선물 GT JSON으로 변환한다."""
|
||||
signals = spot_gt.get("signals") or []
|
||||
futures_gt = deepcopy(spot_gt)
|
||||
futures_gt["meta"] = {
|
||||
**spot_gt.get("meta", {}),
|
||||
"market_type": "futures",
|
||||
"source": "spot_ground_truth",
|
||||
}
|
||||
futures_gt["futures_events"] = futures_events_from_gt_signals(signals)
|
||||
return futures_gt
|
||||
|
||||
|
||||
def _print_summary(
|
||||
tier: str,
|
||||
gt_result: dict[str, Any],
|
||||
json_path: Path,
|
||||
chart_path: Path,
|
||||
) -> None:
|
||||
"""티어별 선물 GT 요약을 출력한다."""
|
||||
meta = gt_result["meta"]
|
||||
summary = gt_result["summary"]
|
||||
print(f"\n=== 선물 GT {tier.upper()} ({TIER_DESCRIPTIONS[tier]}) ===")
|
||||
print(f"대상: {meta['symbol']} ({meta['interval_label']})")
|
||||
print(f"GT 기간: {meta['data_from']} ~ {meta['data_to']}")
|
||||
print(
|
||||
f"선물 GT 타점: 매수 {summary['buy_count']} / 매도 {summary['sell_count']} "
|
||||
f"→ 선물 상방·하방 각 {summary['buy_count']}/{summary['sell_count']} 마커"
|
||||
)
|
||||
print(f"JSON: {json_path}")
|
||||
print(f"차트: {chart_path}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""CLI 진입점."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="선물 GT JSON·차트 생성 (현물 GT → 롱·숏 4색)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--tier",
|
||||
choices=("v1", "v2", "v3", "all"),
|
||||
default="all",
|
||||
help="대상 GT 버전",
|
||||
)
|
||||
parser.add_argument("-v", "--verbose", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
_configure_logging(args.verbose)
|
||||
settings = load_settings()
|
||||
tiers = _tier_targets(settings, args.tier)
|
||||
|
||||
print("\n=== 선물 Ground Truth 생성 ===")
|
||||
print("현물 GT 타점 → L↑상방매수 L↓상방매도 S↓하방매수 S↑하방매도")
|
||||
|
||||
for tier, spot_json_path, futures_json_path, chart_path in tiers:
|
||||
if not spot_json_path.exists():
|
||||
logging.error(
|
||||
"현물 GT JSON 없음: %s — 먼저 0_ground_truth.py 실행",
|
||||
spot_json_path,
|
||||
)
|
||||
return 1
|
||||
|
||||
spot_gt = _load_gt(spot_json_path)
|
||||
futures_gt = _build_futures_gt(spot_gt)
|
||||
save_ground_truth(futures_gt, futures_json_path)
|
||||
|
||||
render_futures_ground_truth_chart(
|
||||
db_path=settings.db_path,
|
||||
symbol=settings.symbol,
|
||||
gt_result=spot_gt,
|
||||
output_path=chart_path,
|
||||
chart_lookback_days=settings.download_days,
|
||||
)
|
||||
_print_summary(tier, futures_gt, futures_json_path, chart_path)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -16,12 +16,12 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import Settings, load_settings
|
||||
from deepcoin.data.candle_loader import load_candles
|
||||
from deepcoin.data.intervals import interval_label
|
||||
from deepcoin.ground_truth.chart import render_ground_truth_sim_chart
|
||||
from deepcoin.ground_truth.ground_truth import GtParams, build_ground_truth, save_ground_truth
|
||||
from deepcoin.ground_truth.pnl import simulate_gt_signals_pnl
|
||||
from bithumb.config import Settings, load_settings
|
||||
from bithumb.data.candle_loader import load_candles
|
||||
from bithumb.data.intervals import interval_label
|
||||
from bithumb.ground_truth.chart import render_ground_truth_sim_chart
|
||||
from bithumb.ground_truth.ground_truth import GtParams, build_ground_truth, save_ground_truth
|
||||
from bithumb.ground_truth.pnl import simulate_gt_signals_pnl
|
||||
|
||||
TIER_DESCRIPTIONS = {
|
||||
"v1": "스윙만 (최소 매수·매도)",
|
||||
|
||||
96
scripts/1_tune_order_sizing.py
Normal file
96
scripts/1_tune_order_sizing.py
Normal file
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""1단계: 연속 매수·매도 클러스터별 매수·매도 비율 튜닝 (타점 고정)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.ground_truth.sizing_rules import save_sizing_rules
|
||||
from bithumb.ground_truth.sizing_tune import tune_sizing_rules
|
||||
from bithumb.operations.signal_pipeline import run_signal_pipeline
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
level = logging.DEBUG if verbose else logging.INFO
|
||||
logging.basicConfig(
|
||||
level=level,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""CLI 진입점."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="연속 매수·매도 클러스터 상태별 사이징 비율 학습",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--output",
|
||||
type=str,
|
||||
default=None,
|
||||
help="규칙 JSON 경로 (기본: OPS_SIZING_RULES_JSON)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--min-bucket-samples",
|
||||
type=int,
|
||||
default=5,
|
||||
help="클러스터 버킷별 최소 샘플 수",
|
||||
)
|
||||
parser.add_argument("-v", "--verbose", action="store_true")
|
||||
args = parser.parse_args()
|
||||
_configure_logging(args.verbose)
|
||||
|
||||
settings = load_settings()
|
||||
output_path = Path(args.output) if args.output else settings.ops_sizing_rules_json
|
||||
if not output_path.is_absolute():
|
||||
output_path = ROOT / output_path
|
||||
|
||||
print("\n=== 매수·매도 비율 튜닝 (타점 고정) ===", flush=True)
|
||||
print(
|
||||
f"기법: {settings.ops_technique_id} · sim {settings.gt_sim_lookback_days}일 · "
|
||||
f"기본 {settings.ops_buy_cash_pct:.0%}/{settings.ops_sell_coin_pct:.0%}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
pipeline = run_signal_pipeline(settings, use_cache=True)
|
||||
rules, final_sim = tune_sizing_rules(
|
||||
settings,
|
||||
pipeline["kept"],
|
||||
data_end=pipeline["data_end"],
|
||||
last_mark_price=pipeline["last_price"],
|
||||
technique_id=pipeline["technique_id"],
|
||||
min_bucket_samples=args.min_bucket_samples,
|
||||
)
|
||||
save_sizing_rules(rules, output_path)
|
||||
|
||||
tuning = rules.get("tuning") or {}
|
||||
print(f"\n기준(고정 10%): {tuning.get('baseline_return_pct'):+.2f}%")
|
||||
print(
|
||||
f"학습 후: {final_sim.get('total_return_pct'):+.2f}% · "
|
||||
f"매수/매도 {final_sim.get('buys_executed')}/{final_sim.get('sells_executed')}"
|
||||
)
|
||||
print(
|
||||
f"전역 비율: 매수 {rules.get('default_buy_cash_pct', 0):.0%} · "
|
||||
f"매도 {rules.get('default_sell_coin_pct', 0):.0%}"
|
||||
)
|
||||
by_cluster = rules.get("by_cluster") or {}
|
||||
if by_cluster.get("buy") or by_cluster.get("sell"):
|
||||
print("클러스터별:")
|
||||
print(json.dumps(by_cluster, ensure_ascii=False, indent=2))
|
||||
print(f"\n규칙 JSON: {output_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -14,15 +14,15 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.data.candle_loader import load_candles
|
||||
from deepcoin.evaluation.causal_sim import (
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.data.candle_loader import load_candles
|
||||
from bithumb.evaluation.causal_sim import (
|
||||
best_technique_chart_path,
|
||||
pick_best_technique_row,
|
||||
render_best_technique_comparison_chart,
|
||||
run_technique_causal_sim,
|
||||
)
|
||||
from deepcoin.techniques.runner import load_ground_truth, load_technique_result
|
||||
from bithumb.techniques.runner import load_ground_truth, load_technique_result
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
|
||||
@@ -14,10 +14,10 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.data.candle_loader import load_candles
|
||||
from deepcoin.data.intervals import interval_label
|
||||
from deepcoin.evaluation.causal_sim import (
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.data.candle_loader import load_candles
|
||||
from bithumb.data.intervals import interval_label
|
||||
from bithumb.evaluation.causal_sim import (
|
||||
best_technique_chart_path,
|
||||
build_causal_sim_report,
|
||||
pick_best_technique_row,
|
||||
@@ -28,7 +28,7 @@ from deepcoin.evaluation.causal_sim import (
|
||||
save_causal_sim_report,
|
||||
technique_sim_chart_path,
|
||||
)
|
||||
from deepcoin.techniques.runner import load_ground_truth, load_technique_results
|
||||
from bithumb.techniques.runner import load_ground_truth, load_technique_results
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
|
||||
@@ -13,16 +13,16 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.evaluation.mtf_report import (
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.evaluation.mtf_report import (
|
||||
build_mtf_correlation_report,
|
||||
render_mtf_html,
|
||||
save_mtf_report,
|
||||
)
|
||||
from deepcoin.mtf.extractor import MtfFeatureExtractor
|
||||
from deepcoin.mtf.rules import derive_rules_from_report, save_mtf_rules
|
||||
from deepcoin.mtf.store import MultiTimeframeStore
|
||||
from deepcoin.techniques.runner import load_ground_truth
|
||||
from bithumb.mtf.extractor import MtfFeatureExtractor
|
||||
from bithumb.mtf.rules import derive_rules_from_report, save_mtf_rules
|
||||
from bithumb.mtf.store import MultiTimeframeStore
|
||||
from bithumb.techniques.runner import load_ground_truth
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
|
||||
@@ -13,21 +13,21 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.data.intervals import interval_label
|
||||
from deepcoin.evaluation.report import (
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.data.intervals import interval_label
|
||||
from bithumb.evaluation.report import (
|
||||
build_comparison_report,
|
||||
render_comparison_html,
|
||||
save_comparison_report,
|
||||
)
|
||||
from deepcoin.evaluation.signal_type_report import (
|
||||
from bithumb.evaluation.signal_type_report import (
|
||||
build_signal_type_report,
|
||||
render_signal_type_html,
|
||||
save_signal_type_report,
|
||||
)
|
||||
from deepcoin.techniques.base import TechniqueParams
|
||||
from deepcoin.techniques.registry import list_technique_ids
|
||||
from deepcoin.techniques.runner import (
|
||||
from bithumb.techniques.base import TechniqueParams
|
||||
from bithumb.techniques.registry import list_technique_ids
|
||||
from bithumb.techniques.runner import (
|
||||
load_ground_truth,
|
||||
load_technique_results,
|
||||
run_all_techniques,
|
||||
|
||||
@@ -4,7 +4,7 @@ set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
export PYTHONPATH=src
|
||||
PY="${PY:-/opt/anaconda3/envs/ncue/bin/python}"
|
||||
LOG="${LOG:-/tmp/deepcoin_stage2.log}"
|
||||
LOG="${LOG:-/tmp/bithumb_stage2.log}"
|
||||
|
||||
echo "=== 현물 2단계 파이프라인 시작 $(date '+%Y-%m-%d %H:%M:%S') ===" | tee "$LOG"
|
||||
|
||||
|
||||
@@ -13,16 +13,16 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.data.intervals import interval_label
|
||||
from deepcoin.evaluation.report import (
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.data.intervals import interval_label
|
||||
from bithumb.evaluation.report import (
|
||||
build_comparison_report,
|
||||
render_comparison_html,
|
||||
save_comparison_report,
|
||||
)
|
||||
from deepcoin.techniques.base import TechniqueParams
|
||||
from deepcoin.techniques.registry import list_technique_ids
|
||||
from deepcoin.techniques.runner import (
|
||||
from bithumb.techniques.base import TechniqueParams
|
||||
from bithumb.techniques.registry import list_technique_ids
|
||||
from bithumb.techniques.runner import (
|
||||
load_ground_truth,
|
||||
run_all_techniques,
|
||||
save_technique_result,
|
||||
|
||||
90
scripts/3_init_live_state.py
Executable file
90
scripts/3_init_live_state.py
Executable file
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""paper → live 상태 전환 — 거래소 잔고 동기화."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.notifications.telegram import create_telegram_notifier
|
||||
from bithumb.operations.live_bootstrap import init_live_state
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""CLI 진입점."""
|
||||
parser = argparse.ArgumentParser(description="Bithumb live 상태 초기화")
|
||||
parser.add_argument(
|
||||
"--no-backup",
|
||||
action="store_true",
|
||||
help="기존 state JSON 백업 생략",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--reset-bar-cursor",
|
||||
action="store_true",
|
||||
help="last_processed_bar_index 를 -1 로 초기화",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--yes",
|
||||
action="store_true",
|
||||
help="확인 프롬프트 생략",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
settings = load_settings()
|
||||
if settings.ops_mode != "live":
|
||||
print(f"OPS_MODE={settings.ops_mode} — .env 에 OPS_MODE=live 설정 후 실행하세요.", file=sys.stderr)
|
||||
return 1
|
||||
if not settings.bithumb_access_key or not settings.bithumb_secret_key:
|
||||
print("BITHUMB API 키가 필요합니다.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if not args.yes:
|
||||
print("경고: live 상태 초기화 — 거래소 잔고가 state JSON에 반영됩니다.")
|
||||
print(f"state: {settings.ops_state_json}")
|
||||
answer = input("계속하시겠습니까? [y/N]: ").strip().lower()
|
||||
if answer not in ("y", "yes"):
|
||||
print("취소됨.")
|
||||
return 1
|
||||
|
||||
result = init_live_state(
|
||||
settings,
|
||||
backup=not args.no_backup,
|
||||
preserve_bar_cursor=not args.reset_bar_cursor,
|
||||
)
|
||||
bal = result["balances"]
|
||||
|
||||
print("=== live 상태 초기화 완료 ===")
|
||||
if result["backup_path"]:
|
||||
print(f"백업: {result['backup_path']}")
|
||||
print(f"state: {result['state_path']}")
|
||||
print(
|
||||
f"잔고: KRW {bal['cash_krw']:,.0f}원 · "
|
||||
f"{settings.symbol} {bal['coin_qty']:.8f}"
|
||||
)
|
||||
print(f"bar cursor: {result['last_processed_bar_index']}")
|
||||
|
||||
telegram = create_telegram_notifier(
|
||||
settings.telegram_bot_token,
|
||||
settings.telegram_chat_id,
|
||||
enabled=settings.ops_telegram_enabled,
|
||||
)
|
||||
if telegram.is_active:
|
||||
telegram.send_message(
|
||||
"[Bithumb] LIVE 세션 시작\n"
|
||||
f"{settings.coin_name} ({settings.symbol}) | {settings.ops_technique_id}\n"
|
||||
f"KRW {bal['cash_krw']:,.0f} · {settings.symbol} {bal['coin_qty']:.8f}\n"
|
||||
f"일 체결 상한 {settings.ops_daily_max_trades} · 슬리피지 {settings.ops_slippage_rate * 100:.2f}%"
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
70
scripts/3_preflight_live.py
Executable file
70
scripts/3_preflight_live.py
Executable file
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""live 운영 전 사전 점검 — API·잔고·캐시·텔레그램."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.operations.live_bootstrap import run_preflight, save_preflight_report
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""CLI 진입점."""
|
||||
parser = argparse.ArgumentParser(description="Bithumb live 사전 점검")
|
||||
parser.add_argument(
|
||||
"--report",
|
||||
default="docs/spot/3_operations/live_preflight_report.json",
|
||||
help="점검 결과 JSON 경로",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--require-live",
|
||||
action="store_true",
|
||||
help="OPS_MODE=live 가 아니면 실패",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
settings = load_settings()
|
||||
if args.require_live and settings.ops_mode != "live":
|
||||
print(f"OPS_MODE={settings.ops_mode} — live 전환 후 다시 실행하세요.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
report = run_preflight(settings)
|
||||
report_path = save_preflight_report(
|
||||
ROOT / args.report if not Path(args.report).is_absolute() else Path(args.report),
|
||||
report,
|
||||
)
|
||||
|
||||
print("=== Bithumb live 사전 점검 ===")
|
||||
print(f"기법: {report['technique_id']} · 마켓: {report['market']} · 모드: {report['mode']}")
|
||||
if report.get("balances"):
|
||||
bal = report["balances"]
|
||||
print(
|
||||
f"잔고: KRW {bal['cash_krw']:,.0f}원 · "
|
||||
f"{report['symbol']} {bal['coin_qty']:.8f}"
|
||||
)
|
||||
print()
|
||||
for row in report["checks"]:
|
||||
mark = "OK" if row["passed"] else "NG"
|
||||
req = "필수" if row["required"] else "선택"
|
||||
print(f"[{mark}] ({req}) {row['name']}: {row['detail']}")
|
||||
print(f"\n리포트: {report_path}")
|
||||
|
||||
if report["ok"]:
|
||||
print("\n사전 점검 통과 — live 운영을 시작할 수 있습니다.")
|
||||
return 0
|
||||
|
||||
print("\n사전 점검 실패 — live 시작 전 위 항목을 해결하세요.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -13,8 +13,8 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.operations.chart import render_ops_live_chart
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.operations.chart import render_ops_live_chart
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
@@ -34,12 +34,21 @@ def _write_index_html(
|
||||
"""docs/live 인덱스 HTML을 생성한다."""
|
||||
sim = report["filtered_sim"]
|
||||
ret = sim.get("total_return_pct", 0)
|
||||
sizing_line = ""
|
||||
if sim.get("sizing_rules_applied"):
|
||||
lb = sim.get("learned_default_buy_cash_pct")
|
||||
ls = sim.get("learned_default_sell_coin_pct")
|
||||
if lb is not None and ls is not None:
|
||||
sizing_line = (
|
||||
f"<br>학습 비율: 매수 {float(lb) * 100:.0f}% · 매도 {float(ls) * 100:.0f}%"
|
||||
f" (클러스터별 규칙 적용)"
|
||||
)
|
||||
index_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
html = f"""<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>DeepCoin Live — 운영 백테스트 차트</title>
|
||||
<title>Bithumb Live — 운영 백테스트 차트</title>
|
||||
<style>
|
||||
body {{ font-family: "Malgun Gothic", Arial, sans-serif; margin: 32px; color: #333; background: #f5f5f5; }}
|
||||
h1 {{ font-size: 22px; margin-bottom: 8px; }}
|
||||
@@ -52,13 +61,13 @@ def _write_index_html(
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>DeepCoin Live — 운영 백테스트</h1>
|
||||
<h1>Bithumb Live — 운영 백테스트</h1>
|
||||
<p class="meta">
|
||||
{report.get("symbol", "BTC")} · {report.get("technique_name", "")} ({report.get("technique_id", "")})<br>
|
||||
sim 기간: 최근 {report.get("sim_lookback_days", 1095)}일 ·
|
||||
슬리피지 {report.get("slippage_rate", 0) * 100:.2f}% ·
|
||||
일 체결 상한 {report.get("daily_max_trades", "-")} ·
|
||||
MTF {"on" if report.get("mtf_enabled") else "off"}
|
||||
MTF {"on" if report.get("mtf_enabled") else "off"}{sizing_line}
|
||||
</p>
|
||||
<div class="card">
|
||||
<div>3년 수익률 (운영 규칙 sim)</div>
|
||||
|
||||
@@ -13,8 +13,8 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.operations.backtest import run_filtered_backtest, save_backtest_report
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.operations.backtest import run_filtered_backtest, save_backtest_report
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
|
||||
26
scripts/3_run_fractal_live.sh
Executable file
26
scripts/3_run_fractal_live.sh
Executable file
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
# fractal_swing LIVE 운영 — 사전 점검 → 상태 초기화 → 180초 tick loop
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
export PYTHONPATH=src
|
||||
|
||||
if [[ "${OPS_MODE:-}" != "live" ]]; then
|
||||
if grep -q '^OPS_MODE=live' .env 2>/dev/null; then
|
||||
:
|
||||
else
|
||||
echo "오류: .env 에 OPS_MODE=live 가 필요합니다." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "=== 1/3 live 사전 점검 ==="
|
||||
python scripts/3_preflight_live.py --require-live
|
||||
|
||||
echo ""
|
||||
echo "=== 2/3 live 상태 초기화 (거래소 잔고 동기화) ==="
|
||||
python scripts/3_init_live_state.py --yes
|
||||
|
||||
echo ""
|
||||
echo "=== 3/3 LIVE 운영 (180초 loop) — Ctrl+C 종료 ==="
|
||||
echo "경고: 실제 빗썸 시장가 주문이 발생합니다."
|
||||
python scripts/3_run_operations.py --mode live --loop 180
|
||||
@@ -14,10 +14,10 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.evaluation.causal_sim import normalize_signals_for_sim
|
||||
from deepcoin.ground_truth.pnl import simulate_gt_signals_pnl
|
||||
from deepcoin.operations.signal_pipeline import (
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.evaluation.causal_sim import normalize_signals_for_sim
|
||||
from bithumb.ground_truth.pnl import simulate_gt_signals_pnl
|
||||
from bithumb.operations.signal_pipeline import (
|
||||
_signals_in_lookback,
|
||||
generate_raw_signals,
|
||||
load_ops_candles,
|
||||
@@ -64,6 +64,8 @@ def main() -> int:
|
||||
min_order_krw=settings.ops_min_order_krw,
|
||||
slippage_rate=sc["slippage_rate"],
|
||||
daily_max_trades=sc["daily_max_trades"],
|
||||
buy_cash_pct=settings.ops_buy_cash_pct,
|
||||
sell_coin_pct=settings.ops_sell_coin_pct,
|
||||
sim_lookback_days=settings.gt_sim_lookback_days,
|
||||
data_end=end,
|
||||
last_mark_price=price,
|
||||
|
||||
@@ -14,8 +14,8 @@ SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
||||
from deepcoin.config import load_settings
|
||||
from deepcoin.operations.runner import OperationsRunner
|
||||
from bithumb.config import load_settings
|
||||
from bithumb.operations.runner import OperationsRunner
|
||||
|
||||
|
||||
def _configure_logging(verbose: bool) -> None:
|
||||
@@ -29,7 +29,7 @@ def _configure_logging(verbose: bool) -> None:
|
||||
|
||||
def main() -> int:
|
||||
"""CLI 진입점."""
|
||||
parser = argparse.ArgumentParser(description="3단계: DeepCoin 운영 tick")
|
||||
parser = argparse.ArgumentParser(description="3단계: Bithumb 운영 tick")
|
||||
parser.add_argument(
|
||||
"--mode",
|
||||
choices=("paper", "live"),
|
||||
@@ -67,19 +67,37 @@ def main() -> int:
|
||||
sync = not args.no_sync
|
||||
|
||||
while True:
|
||||
report = runner.tick(sync_candles=sync)
|
||||
port = report["portfolio"]
|
||||
try:
|
||||
report = runner.tick(sync_candles=sync)
|
||||
except Exception as exc:
|
||||
logging.exception("운영 tick 예외 (복구 후 계속)")
|
||||
if runner.telegram.is_active:
|
||||
runner.telegram.notify_ops_error(
|
||||
mode=settings.ops_mode,
|
||||
symbol=settings.symbol,
|
||||
technique_id=settings.ops_technique_id,
|
||||
stage="main_loop",
|
||||
error=str(exc),
|
||||
)
|
||||
if args.loop <= 0:
|
||||
break
|
||||
time.sleep(args.loop)
|
||||
continue
|
||||
|
||||
port = report.get("portfolio") or {}
|
||||
print("\n=== 3단계 운영 tick ===")
|
||||
print(f"모드: {report['mode']}")
|
||||
if report.get("error"):
|
||||
print(f"오류: [{report.get('error_stage')}] {report.get('error_message')}")
|
||||
print(f"모드: {report.get('mode', settings.ops_mode)}")
|
||||
print(
|
||||
f"최신 봉 후보: {report.get('latest_bar_candidates', 0)} · "
|
||||
f"필터 통과: {report['filtered_signals']} · "
|
||||
f"필터 통과: {report.get('filtered_signals', 0)} · "
|
||||
f"처리 bar: {report.get('pending_bars', [])}"
|
||||
)
|
||||
print(f"이번 체결: {len(report['executions'])}건")
|
||||
print(f"이번 체결: {len(report.get('executions', []))}건")
|
||||
print(
|
||||
f"포트폴리오: 현금 {port['cash_krw']:,.0f}원 · "
|
||||
f"코인 {port['coin_qty']:.8f} {settings.symbol}"
|
||||
f"포트폴리오: 현금 {port.get('cash_krw', 0):,.0f}원 · "
|
||||
f"코인 {port.get('coin_qty', 0):.8f} {settings.symbol}"
|
||||
)
|
||||
print(f"리포트: {settings.ops_report_json}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user