Compare commits

...

16 Commits

Author SHA1 Message Date
21in7
7a1abc7b72 chore: update python-binance dependency and improve error handling in BinanceFuturesClient
- Changed python-binance version requirement from 1.0.19 to >=1.0.28 for better compatibility and features.
- Modified exception handling in the cancel_all_orders method to catch all exceptions instead of just BinanceAPIException, enhancing robustness.
2026-03-02 13:24:27 +09:00
21in7
de2a402bc1 feat: enhance cancel_all_orders method to include Algo order cancellation
- Updated the cancel_all_orders method to also cancel all Algo open orders in addition to regular open orders.
- Added error handling to log warnings if the cancellation of Algo orders fails.
2026-03-02 02:15:49 +09:00
21in7
684c8a32b9 feat: add Algo Order API support and update ML feature handling
- Introduced support for Algo Order API, allowing automatic sending of STOP_MARKET and TAKE_PROFIT_MARKET orders.
- Updated README.md to include new features related to Algo Order API and real-time handling of ML features.
- Enhanced ML feature processing to fill missing OI and funding rate values with zeros for consistency in training data.
- Added new training log entries for the lgbm model with updated metrics.
2026-03-02 02:03:50 +09:00
21in7
c89374410e feat: enhance trading bot functionality and documentation
- Updated README.md to reflect new features including dynamic margin ratio, model hot-reload, and multi-symbol streaming.
- Modified bot logic to ensure raw signals are passed to the `_close_and_reenter` method, even when the ML filter is loaded.
- Introduced a new script `run_tests.sh` for streamlined test execution.
- Improved test coverage for signal processing and re-entry logic, ensuring correct behavior under various conditions.
2026-03-02 01:51:53 +09:00
21in7
9ec78d76bd feat: implement immediate re-entry after closing position on reverse signal
- Added `_close_and_reenter` method to handle immediate re-entry after closing a position when a reverse signal is detected, contingent on passing the ML filter.
- Updated `process_candle` to call `_close_and_reenter` instead of `_close_position` for reverse signals.
- Enhanced test coverage for the new functionality, ensuring correct behavior under various conditions, including ML filter checks and position limits.
2026-03-02 01:34:36 +09:00
21in7
725a4349ee chore: Update MLXFilter model deployment and logging with new training results and ONNX file management
- Added new training log entries for lgbm backend with AUC, precision, and recall metrics.
- Enhanced deploy_model.sh to manage ONNX and lgbm model files based on the selected backend.
- Adjusted output shape in mlx_filter.py for ONNX export to support dynamic batch sizes.
2026-03-02 01:08:12 +09:00
21in7
5e6cdcc358 fix: _on_candle_closed async 콜백 구조 수정 — asyncio.create_task 제거
동기 콜백 내부에서 asyncio.create_task()를 호출하면 이벤트 루프
컨텍스트 밖에서 실패하여 캔들 처리가 전혀 이루어지지 않는 버그 수정.

- _on_candle_closed: 동기 → async, create_task → await
- handle_message (KlineStream/MultiSymbolStream): 동기 → async, on_candle await
- test_callback_called_on_closed_candle: AsyncMock + await handle_message로 수정

Made-with: Cursor
2026-03-02 01:00:59 +09:00
21in7
361b0f4e00 fix: Update TradingBot signal processing to handle NaN values and improve MLFilter ONNX session configuration 2026-03-02 00:47:17 +09:00
21in7
031adac977 chore: .gitignore에 .DS_Store 추가 및 MLXFilter 훈련 로그 업데이트 2026-03-02 00:41:34 +09:00
21in7
747ab45bb0 fix: test_reload_model 단언을 실제 동작(파일 없으면 폴백 상태)에 맞게 수정
Made-with: Cursor
2026-03-02 00:38:08 +09:00
21in7
6fa6e854ca fix: test_reload_model _model → _lgbm_model 주입 방식으로 수정
Made-with: Cursor
2026-03-02 00:36:47 +09:00
21in7
518f1846b8 fix: 기존 테스트를 현재 코드 구조에 맞게 수정 — MLFilter API, FEATURE_COLS 수, 버퍼 최솟값 반영
Made-with: Cursor
2026-03-02 00:36:13 +09:00
21in7
3bfd1ca5a3 fix: test_mlx_filter _make_X를 FEATURE_COLS 기반으로 수정 — 피처 확장 후 input_dim 불일치 해소
Made-with: Cursor
2026-03-02 00:34:21 +09:00
21in7
7fdd8bff94 fix: MLXFilter self._mean/std 저장 전 nan_to_num 적용 — 전체-NaN 컬럼 predict_proba 오염 차단
Made-with: Cursor
2026-03-02 00:31:08 +09:00
21in7
bcc717776d fix: RS 계산을 np.divide(where=) 방식으로 교체 — epsilon 이상치 폭발 차단
Made-with: Cursor
2026-03-02 00:30:36 +09:00
9cac8a4afd Merge pull request 'feat: OI nan 마스킹 / epsilon 통일 / 정밀도 우선 임계값' (#1) from feature/oi-nan-epsilon-precision-threshold into main
Reviewed-on: http://10.1.10.28:3000/gihyeon/cointrader/pulls/1
2026-03-01 23:57:32 +09:00
27 changed files with 1223 additions and 128 deletions

1
.gitignore vendored
View File

@@ -9,3 +9,4 @@ venv/
models/*.pkl models/*.pkl
data/*.parquet data/*.parquet
.worktrees/ .worktrees/
.DS_Store

158
README.md
View File

@@ -1,18 +1,24 @@
# CoinTrader # CoinTrader
Binance Futures 자동매매 봇. 복합 기술 지표와 LightGBM ML 필터를 결합하여 XRPUSDT(기본) 선물 포지션을 자동으로 진입·청산하며, Discord로 실시간 알림을 전송합니다. Binance Futures 자동매매 봇. 복합 기술 지표와 ML 필터(LightGBM / MLX 신경망)를 결합하여 XRPUSDT(기본) 선물 포지션을 자동으로 진입·청산하며, Discord로 실시간 알림을 전송합니다.
--- ---
## 주요 기능 ## 주요 기능
- **복합 기술 지표 신호**: RSI, MACD 크로스, 볼린저 밴드, EMA 정/역배열, Stochastic RSI, 거래량 급증 — 3개 이상 일치 시 진입 - **복합 기술 지표 신호**: RSI, MACD 크로스, 볼린저 밴드, EMA 정/역배열, Stochastic RSI, 거래량 급증 — 가중치 합계 ≥ 3 시 진입
- **ML 필터 (LightGBM)**: 기술 지표 신호를 한 번 더 검증하여 오진입 차단 (모델 없으면 자동 폴백) - **ML 필터 (ONNX 우선 / LightGBM 폴백)**: 기술 지표 신호를 한 번 더 검증하여 오진입 차단. 우선순위: ONNX > LightGBM > 폴백(항상 허용)
- **모델 핫리로드**: 캔들마다 모델 파일 mtime을 감지해 변경 시 자동 리로드 (봇 재시작 불필요)
- **멀티심볼 스트림**: XRP/BTC/ETH 3개 심볼을 단일 Combined WebSocket으로 수신, BTC·ETH 상관관계 피처 활용
- **23개 ML 피처**: XRP 기술 지표 13개 + BTC/ETH 수익률·상대강도 8개 + OI 변화율·펀딩비 2개 (실시간 미수집 항목은 0으로 채움)
- **ATR 기반 손절/익절**: 변동성에 따라 동적으로 SL/TP 계산 (1.5× / 3.0× ATR) - **ATR 기반 손절/익절**: 변동성에 따라 동적으로 SL/TP 계산 (1.5× / 3.0× ATR)
- **리스크 관리**: 트레이드당 리스크 비율, 최대 포지션 수, 일일 손실 한도 제어 - **Algo Order API 지원**: 계정 설정에 따라 STOP_MARKET/TAKE_PROFIT_MARKET 주문을 `/fapi/v1/algoOrder` 엔드포인트로 자동 전송 (오류 코드 -4120 대응)
- **동적 증거금 비율**: 잔고 증가에 따라 선형 감소 (최대 50% → 최소 20%)
- **반대 시그널 재진입**: 보유 포지션과 반대 신호 발생 시 즉시 청산 후 ML 필터 통과 시 반대 방향 재진입
- **리스크 관리**: 트레이드당 리스크 비율, 최대 포지션 수, 일일 손실 한도(5%) 제어
- **포지션 복구**: 봇 재시작 시 기존 포지션 자동 감지 및 상태 복원 - **포지션 복구**: 봇 재시작 시 기존 포지션 자동 감지 및 상태 복원
- **Discord 알림**: 진입·청산·오류 이벤트 실시간 웹훅 알림 - **Discord 알림**: 진입·청산·오류 이벤트 실시간 웹훅 알림
- **CI/CD**: Jenkins + Gitea Container Registry 기반 Docker 이미지 자동 빌드·배포 - **CI/CD**: Jenkins + Gitea Container Registry 기반 Docker 이미지 자동 빌드·배포 (LXC 운영 서버 자동 적용)
--- ---
@@ -20,27 +26,33 @@ Binance Futures 자동매매 봇. 복합 기술 지표와 LightGBM ML 필터를
``` ```
cointrader/ cointrader/
├── main.py # 진입점 ├── main.py # 진입점
├── src/ ├── src/
│ ├── bot.py # 메인 트레이딩 루프 │ ├── bot.py # 메인 트레이딩 루프
│ ├── config.py # 환경변수 기반 설정 │ ├── config.py # 환경변수 기반 설정
│ ├── exchange.py # Binance Futures API 클라이언트 │ ├── exchange.py # Binance Futures API 클라이언트
│ ├── data_stream.py # WebSocket 1분봉 스트림 │ ├── data_stream.py # WebSocket 15분봉 멀티심볼 스트림 (XRP/BTC/ETH)
│ ├── indicators.py # 기술 지표 계산 및 신호 생성 │ ├── indicators.py # 기술 지표 계산 및 신호 생성
│ ├── ml_filter.py # LightGBM 진입 필터 │ ├── ml_filter.py # ML 필터 (ONNX 우선 / LightGBM 폴백 / 핫리로드)
│ ├── ml_features.py # ML 피처 빌더 │ ├── ml_features.py # ML 피처 빌더 (23개 피처)
│ ├── label_builder.py # 학습 레이블 생성 │ ├── mlx_filter.py # MLX 신경망 필터 (Apple Silicon GPU 학습 + ONNX export)
│ ├── dataset_builder.py # 벡터화 데이터셋 빌더 (학습용) │ ├── label_builder.py # 학습 레이블 생성
│ ├── risk_manager.py # 리스크 관리 │ ├── dataset_builder.py # 벡터화 데이터셋 빌더 (학습용)
│ ├── notifier.py # Discord 웹훅 알림 │ ├── risk_manager.py # 리스크 관리 (일일 손실 한도, 동적 증거금 비율)
── logger_setup.py # Loguru 로거 설정 ── notifier.py # Discord 웹훅 알림
│ └── logger_setup.py # Loguru 로거 설정
├── scripts/ ├── scripts/
│ ├── fetch_history.py # 과거 데이터 수집 │ ├── fetch_history.py # 과거 데이터 수집 (XRP/BTC/ETH + OI/펀딩비)
── train_model.py # ML 모델 수동 학습 ── train_model.py # LightGBM 모델 학습 (CPU)
├── models/ # 학습된 모델 저장 (.pkl) │ ├── train_mlx_model.py # MLX 신경망 학습 (Apple Silicon GPU)
├── data/ # 과거 데이터 캐시 │ ├── train_and_deploy.sh # 전체 파이프라인 (수집 → 학습 → LXC 배포)
├── logs/ # 로그 파일 │ ├── deploy_model.sh # 모델 파일 LXC 서버 전송
├── tests/ # 테스트 코드 │ └── run_tests.sh # 전체 테스트 실행
├── models/ # 학습된 모델 저장 (.pkl / .onnx)
├── data/ # 과거 데이터 캐시 (.parquet)
├── logs/ # 로그 파일
├── docs/plans/ # 설계 문서 및 구현 플랜
├── tests/ # 테스트 코드
├── Dockerfile ├── Dockerfile
├── docker-compose.yml ├── docker-compose.yml
├── Jenkinsfile ├── Jenkinsfile
@@ -64,7 +76,6 @@ BINANCE_API_KEY=your_api_key
BINANCE_API_SECRET=your_api_secret BINANCE_API_SECRET=your_api_secret
SYMBOL=XRPUSDT SYMBOL=XRPUSDT
LEVERAGE=10 LEVERAGE=10
RISK_PER_TRADE=0.02
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/... DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
``` ```
@@ -91,17 +102,50 @@ docker compose logs -f cointrader
## ML 모델 학습 ## ML 모델 학습
봇은 모델 파일(`models/lgbm_filter.pkl`)이 없으면 ML 필터 없이 동작합니다. 최초 실행 전 또는 수동 재학습 시 아래 순서로 진행합니다. 봇은 모델 파일이 없으면 ML 필터 없이 동작합니다. 최초 실행 전 또는 수동 재학습 시 아래 순서로 진행합니다.
### 전체 파이프라인 (권장)
맥미니에서 데이터 수집 → 학습 → LXC 배포까지 한 번에 실행합니다.
```bash ```bash
# 1. 과거 데이터 수집 # LightGBM + Walk-Forward 5폴드 (기본값)
python scripts/fetch_history.py bash scripts/train_and_deploy.sh
# 2. 모델 학습 (LightGBM, CPU) # MLX GPU 학습 + Walk-Forward 5폴드
python scripts/train_model.py bash scripts/train_and_deploy.sh mlx
# LightGBM + Walk-Forward 3폴드
bash scripts/train_and_deploy.sh lgbm 3
# 학습만 (배포 없이)
bash scripts/train_and_deploy.sh lgbm 0
``` ```
학습된 모델은 `models/lgbm_filter.pkl`에 저장됩니다. 재학습이 필요하면 맥미니에서 위 스크립트를 다시 실행하고 모델 파일을 컨테이너에 배포합니다. ### 단계별 수동 실행
```bash
# 1. 과거 데이터 수집 (XRP/BTC/ETH 3심볼, 15분봉, 1년치 + OI/펀딩비)
python scripts/fetch_history.py \
--symbols XRPUSDT BTCUSDT ETHUSDT \
--interval 15m \
--days 365 \
--output data/combined_15m.parquet
# 2-A. LightGBM 모델 학습 (CPU)
python scripts/train_model.py --data data/combined_15m.parquet
# 2-B. MLX 신경망 학습 (Apple Silicon GPU)
python scripts/train_mlx_model.py --data data/combined_15m.parquet
# 3. LXC 서버에 모델 배포
bash scripts/deploy_model.sh # LightGBM
bash scripts/deploy_model.sh mlx # MLX (ONNX)
```
학습된 모델은 `models/lgbm_filter.pkl` (LightGBM) 또는 `models/mlx_filter.weights.onnx` (MLX) 에 저장됩니다.
> **모델 핫리로드**: 봇이 실행 중일 때 모델 파일을 교체하면, 다음 캔들 마감 시 자동으로 감지해 리로드합니다. 봇 재시작이 필요 없습니다.
### Apple Silicon GPU 가속 학습 (M1/M2/M3/M4) ### Apple Silicon GPU 가속 학습 (M1/M2/M3/M4)
@@ -110,23 +154,16 @@ M 시리즈 맥에서는 MLX를 사용해 통합 GPU(Metal)로 학습할 수 있
> **설치**: `mlx`는 Apple Silicon 전용이며 `requirements.txt`에 포함되지 않습니다. > **설치**: `mlx`는 Apple Silicon 전용이며 `requirements.txt`에 포함되지 않습니다.
> 맥미니에서 별도 설치: `pip install mlx` > 맥미니에서 별도 설치: `pip install mlx`
```bash MLX로 학습한 모델은 ONNX 포맷으로 export되어 Linux 서버에서 `onnxruntime`으로 추론합니다.
# MLX 별도 설치 (맥미니 전용)
pip install mlx
# MLX 신경망 필터 학습 (GPU 자동 사용) > **참고**: LightGBM은 Apple Silicon GPU를 공식 지원하지 않습니다. MLX는 Apple이 만든 ML 프레임워크로 통합 GPU 자동으로 활용합니다.
python scripts/train_mlx_model.py
# train_and_deploy.sh에서 MLX 백엔드 사용
TRAIN_BACKEND=mlx bash scripts/train_and_deploy.sh
```
> **참고**: LightGBM은 Apple Silicon GPU를 공식 지원하지 않습니다. MLX는 Apple이 만든 ML 프레임워크로 통합 GPU를 자동으로 활용합니다. Neural Engine(NPU)은 Apple 내부 전용으로 Python에서 직접 제어할 수 없습니다.
--- ---
## 매매 전략 ## 매매 전략
### 기술 지표 신호 (15분봉)
| 지표 | 롱 조건 | 숏 조건 | 가중치 | | 지표 | 롱 조건 | 숏 조건 | 가중치 |
|------|---------|---------|--------| |------|---------|---------|--------|
| RSI (14) | < 35 | > 65 | 1 | | RSI (14) | < 35 | > 65 | 1 |
@@ -138,7 +175,13 @@ TRAIN_BACKEND=mlx bash scripts/train_and_deploy.sh
**진입 조건**: 가중치 합계 ≥ 3 + (거래량 급증 또는 가중치 합계 ≥ 4) **진입 조건**: 가중치 합계 ≥ 3 + (거래량 급증 또는 가중치 합계 ≥ 4)
**손절/익절**: ATR × 1.5 / ATR × 3.0 (리스크:리워드 = 1:2) **손절/익절**: ATR × 1.5 / ATR × 3.0 (리스크:리워드 = 1:2)
**ML 필터**: LightGBM 예측 확률 ≥ 0.60 이어야 최종 진입 **ML 필터**: 예측 확률 ≥ 0.60 이어야 최종 진입
### 반대 시그널 재진입
보유 포지션과 반대 방향 신호가 발생하면:
1. 기존 포지션 즉시 청산 (미체결 SL/TP 주문 취소 포함)
2. ML 필터 통과 시 반대 방향으로 즉시 재진입
--- ---
@@ -146,22 +189,27 @@ TRAIN_BACKEND=mlx bash scripts/train_and_deploy.sh
`main` 브랜치에 푸시하면 Jenkins 파이프라인이 자동으로 실행됩니다. `main` 브랜치에 푸시하면 Jenkins 파이프라인이 자동으로 실행됩니다.
1. **Checkout** — 소스 체크아웃 1. **Notify Build Start** — Discord 빌드 시작 알림
2. **Build Image** — Docker 이미지 빌드 (`:{BUILD_NUMBER}` + `:latest` 태그) 2. **Git Clone from Gitea** — 소스 체크아웃
3. **Push** — Gitea Container Registry(`10.1.10.28:3000`)에 푸시 3. **Build Docker Image** — Docker 이미지 빌드 (`:{BUILD_NUMBER}` + `:latest` 태그)
4. **Cleanup** — 로컬 이미지 정리 4. **Push to Gitea Registry** — Gitea Container Registry(`10.1.10.28:3000`)에 푸시
5. **Deploy to Prod LXC** — 운영 LXC 서버(`10.1.10.24`)에 자동 배포 (`docker compose pull && up -d`)
6. **Cleanup** — 빌드 서버 로컬 이미지 정리
배포 서버에서 최신 이미지를 반영하려면: 빌드 성공/실패 결과는 Discord로 자동 알림됩니다.
```bash
docker compose pull && docker compose up -d
```
--- ---
## 테스트 ## 테스트
```bash ```bash
# 전체 테스트
bash scripts/run_tests.sh
# 특정 키워드 필터
bash scripts/run_tests.sh -k bot
# pytest 직접 실행
pytest tests/ -v pytest tests/ -v
``` ```
@@ -175,13 +223,15 @@ pytest tests/ -v
| `BINANCE_API_SECRET` | — | Binance API 시크릿 | | `BINANCE_API_SECRET` | — | Binance API 시크릿 |
| `SYMBOL` | `XRPUSDT` | 거래 심볼 | | `SYMBOL` | `XRPUSDT` | 거래 심볼 |
| `LEVERAGE` | `10` | 레버리지 배수 | | `LEVERAGE` | `10` | 레버리지 배수 |
| `RISK_PER_TRADE` | `0.02` | 트레이드당 리스크 비율 (2%) |
| `DISCORD_WEBHOOK_URL` | — | Discord 웹훅 URL | | `DISCORD_WEBHOOK_URL` | — | Discord 웹훅 URL |
| `MARGIN_MAX_RATIO` | `0.50` | 최대 증거금 비율 (잔고 대비 50%) |
| `MARGIN_MIN_RATIO` | `0.20` | 최소 증거금 비율 (잔고 대비 20%) |
| `MARGIN_DECAY_RATE` | `0.0006` | 잔고 증가 시 증거금 비율 감소 속도 |
--- ---
## 주의사항 ## 주의사항
> **이 봇은 실제 자산을 거래합니다.** 운영 전 반드시 Binance Testnet에서 충분히 검증하세요. > **이 봇은 실제 자산을 거래합니다.** 운영 전 반드시 Binance Testnet에서 충분히 검증하세요.
> 과거 수익이 미래 수익을 보장하지 않습니다. 투자 손실에 대한 책임은 사용자 본인에게 있습니다. > 과거 수익이 미래 수익을 보장하지 않습니다. 투자 손실에 대한 책임은 사용자 본인에게 있습니다.
> 성투기원합니다. > 성투기원합니다.

View File

@@ -0,0 +1,125 @@
# 반대 시그널 시 청산 후 즉시 재진입 설계
- **날짜**: 2026-03-02
- **파일**: `src/bot.py`
- **상태**: 설계 완료, 구현 대기
---
## 배경
현재 `TradingBot.process_candle`은 반대 방향 시그널이 오면 기존 포지션을 청산만 하고 종료한다.
새 포지션은 다음 캔들에서 시그널이 다시 나와야 잡힌다.
```
현재: 반대 시그널 → 청산 → 다음 캔들 대기
목표: 반대 시그널 → 청산 → (ML 필터 통과 시) 즉시 반대 방향 재진입
```
같은 방향 시그널이 오거나 HOLD이면 기존 포지션을 그대로 유지한다.
---
## 요구사항
| 항목 | 결정 |
|------|------|
| 포지션 크기 | 재진입 시점 잔고 + 동적 증거금 비율로 새로 계산 |
| SL/TP | 청산 시 기존 주문 전부 취소, 재진입 시 새로 설정 |
| ML 필터 | 재진입에도 동일하게 적용 (차단 시 청산만 하고 대기) |
| 같은 방향 시그널 | 포지션 유지 (변경 없음) |
| HOLD 시그널 | 포지션 유지 (변경 없음) |
---
## 설계
### 변경 범위
`src/bot.py` 한 파일만 수정한다.
1. `_close_and_reenter` 메서드 신규 추가
2. `process_candle` 내 반대 시그널 분기에서 `_close_position` 대신 `_close_and_reenter` 호출
### 데이터 흐름
```
process_candle()
└─ 반대 시그널 감지
└─ _close_and_reenter(position, signal, df, btc_df, eth_df)
├─ _close_position(position) # 청산 + cancel_all_orders
├─ risk.can_open_new_position() 체크
│ └─ 불가 → 로그 + 종료
├─ ML 필터 체크 (ml_filter.is_model_loaded())
│ ├─ 차단 → 로그 + 종료 (포지션 없는 상태로 대기)
│ └─ 통과 → 계속
└─ _open_position(signal, df) # 재진입 + 새 SL/TP 설정
```
### `process_candle` 수정
```python
# 변경 전
elif position is not None:
pos_side = "LONG" if float(position["positionAmt"]) > 0 else "SHORT"
if (pos_side == "LONG" and signal == "SHORT") or \
(pos_side == "SHORT" and signal == "LONG"):
await self._close_position(position)
# 변경 후
elif position is not None:
pos_side = "LONG" if float(position["positionAmt"]) > 0 else "SHORT"
if (pos_side == "LONG" and signal == "SHORT") or \
(pos_side == "SHORT" and signal == "LONG"):
await self._close_and_reenter(position, signal, df_with_indicators, btc_df, eth_df)
```
### 신규 메서드 `_close_and_reenter`
```python
async def _close_and_reenter(
self,
position: dict,
signal: str,
df,
btc_df=None,
eth_df=None,
) -> None:
"""기존 포지션을 청산하고, ML 필터 통과 시 반대 방향으로 즉시 재진입한다."""
await self._close_position(position)
if not self.risk.can_open_new_position():
logger.info("최대 포지션 수 도달 — 재진입 건너뜀")
return
if self.ml_filter.is_model_loaded():
features = build_features(df, signal, btc_df=btc_df, eth_df=eth_df)
if not self.ml_filter.should_enter(features):
logger.info(f"ML 필터 차단: {signal} 재진입 무시")
return
await self._open_position(signal, df)
```
---
## 엣지 케이스
| 상황 | 처리 |
|------|------|
| 청산 후 ML 필터 차단 | 청산만 하고 포지션 없는 상태로 대기 |
| 청산 후 잔고 부족 (명목금액 미달) | `_open_position` 내부 경고 후 건너뜀 (기존 로직) |
| 청산 후 최대 포지션 수 초과 | 재진입 건너뜀 |
| 같은 방향 시그널 | 포지션 유지 (변경 없음) |
| HOLD 시그널 | 포지션 유지 (변경 없음) |
| 봇 재시작 후 포지션 복구 | `_recover_position` 로직 변경 없음 |
---
## 영향 없는 코드
- `_close_position` — 변경 없음
- `_open_position` — 변경 없음
- `_recover_position` — 변경 없음
- `RiskManager` — 변경 없음
- `MLFilter` — 변경 없음

View File

@@ -0,0 +1,269 @@
# 반대 시그널 시 청산 후 즉시 재진입 구현 플랜
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** 반대 방향 시그널이 오면 기존 포지션을 청산하고 ML 필터 통과 시 즉시 반대 방향으로 재진입한다.
**Architecture:** `src/bot.py``_close_and_reenter` 메서드를 추가하고, `process_candle`의 반대 시그널 분기에서 이를 호출한다. 기존 `_close_position``_open_position`을 그대로 재사용하므로 중복 없음.
**Tech Stack:** Python 3.12, pytest, unittest.mock
---
## 테스트 스크립트
각 태스크 단계마다 아래 스크립트로 테스트를 실행한다.
```bash
# Task 1 — 신규 테스트 실행 (구현 전, FAIL 확인용)
bash scripts/test_reverse_reenter.sh 1
# Task 2 — _close_and_reenter 메서드 테스트 (구현 후, PASS 확인)
bash scripts/test_reverse_reenter.sh 2
# Task 3 — process_candle 분기 테스트 (수정 후, PASS 확인)
bash scripts/test_reverse_reenter.sh 3
# test_bot.py 전체
bash scripts/test_reverse_reenter.sh bot
# 전체 테스트 스위트
bash scripts/test_reverse_reenter.sh all
```
---
## 참고 파일
- 설계 문서: `docs/plans/2026-03-02-reverse-signal-reenter-design.md`
- 구현 대상: `src/bot.py`
- 기존 테스트: `tests/test_bot.py`
---
## Task 1: `_close_and_reenter` 테스트 작성
**Files:**
- Modify: `tests/test_bot.py`
### Step 1: 테스트 3개 추가
`tests/test_bot.py` 맨 아래에 다음 테스트를 추가한다.
```python
@pytest.mark.asyncio
async def test_close_and_reenter_calls_open_when_ml_passes(config, sample_df):
"""반대 시그널 + ML 필터 통과 시 청산 후 재진입해야 한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot._close_position = AsyncMock()
bot._open_position = AsyncMock()
bot.ml_filter = MagicMock()
bot.ml_filter.is_model_loaded.return_value = True
bot.ml_filter.should_enter.return_value = True
position = {"positionAmt": "100", "entryPrice": "0.5", "markPrice": "0.52"}
await bot._close_and_reenter(position, "SHORT", sample_df)
bot._close_position.assert_awaited_once_with(position)
bot._open_position.assert_awaited_once_with("SHORT", sample_df)
@pytest.mark.asyncio
async def test_close_and_reenter_skips_open_when_ml_blocks(config, sample_df):
"""ML 필터 차단 시 청산만 하고 재진입하지 않아야 한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot._close_position = AsyncMock()
bot._open_position = AsyncMock()
bot.ml_filter = MagicMock()
bot.ml_filter.is_model_loaded.return_value = True
bot.ml_filter.should_enter.return_value = False
position = {"positionAmt": "100", "entryPrice": "0.5", "markPrice": "0.52"}
await bot._close_and_reenter(position, "SHORT", sample_df)
bot._close_position.assert_awaited_once_with(position)
bot._open_position.assert_not_called()
@pytest.mark.asyncio
async def test_close_and_reenter_skips_open_when_max_positions_reached(config, sample_df):
"""최대 포지션 수 도달 시 청산만 하고 재진입하지 않아야 한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot._close_position = AsyncMock()
bot._open_position = AsyncMock()
bot.risk = MagicMock()
bot.risk.can_open_new_position.return_value = False
position = {"positionAmt": "100", "entryPrice": "0.5", "markPrice": "0.52"}
await bot._close_and_reenter(position, "SHORT", sample_df)
bot._close_position.assert_awaited_once_with(position)
bot._open_position.assert_not_called()
```
### Step 2: 테스트 실행 — 실패 확인
```bash
bash scripts/test_reverse_reenter.sh 1
```
예상 결과: `AttributeError: 'TradingBot' object has no attribute '_close_and_reenter'` 로 3개 FAIL
---
## Task 2: `_close_and_reenter` 메서드 구현
**Files:**
- Modify: `src/bot.py:148` (`_close_position` 메서드 바로 아래에 추가)
### Step 1: `_close_position` 다음에 메서드 추가
`src/bot.py`에서 `_close_position` 메서드(148~167번째 줄) 바로 뒤에 다음을 추가한다.
```python
async def _close_and_reenter(
self,
position: dict,
signal: str,
df,
btc_df=None,
eth_df=None,
) -> None:
"""기존 포지션을 청산하고, ML 필터 통과 시 반대 방향으로 즉시 재진입한다."""
await self._close_position(position)
if not self.risk.can_open_new_position():
logger.info("최대 포지션 수 도달 — 재진입 건너뜀")
return
if self.ml_filter.is_model_loaded():
features = build_features(df, signal, btc_df=btc_df, eth_df=eth_df)
if not self.ml_filter.should_enter(features):
logger.info(f"ML 필터 차단: {signal} 재진입 무시")
return
await self._open_position(signal, df)
```
### Step 2: 테스트 실행 — 통과 확인
```bash
bash scripts/test_reverse_reenter.sh 2
```
예상 결과: 3개 PASS
### Step 3: 커밋
```bash
git add src/bot.py tests/test_bot.py
git commit -m "feat: add _close_and_reenter method for reverse signal handling"
```
---
## Task 3: `process_candle` 분기 수정
**Files:**
- Modify: `src/bot.py:83-85`
### Step 1: 기존 분기 테스트 추가
`tests/test_bot.py`에 다음 테스트를 추가한다.
```python
@pytest.mark.asyncio
async def test_process_candle_calls_close_and_reenter_on_reverse_signal(config, sample_df):
"""반대 시그널 시 process_candle이 _close_and_reenter를 호출해야 한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot.exchange = AsyncMock()
bot.exchange.get_position = AsyncMock(return_value={
"positionAmt": "100",
"entryPrice": "0.5",
"markPrice": "0.52",
})
bot._close_and_reenter = AsyncMock()
bot.ml_filter = MagicMock()
bot.ml_filter.is_model_loaded.return_value = False
bot.ml_filter.should_enter.return_value = True
with patch("src.bot.Indicators") as MockInd:
mock_ind = MagicMock()
mock_ind.calculate_all.return_value = sample_df
mock_ind.get_signal.return_value = "SHORT" # 현재 LONG 포지션에 반대 시그널
MockInd.return_value = mock_ind
await bot.process_candle(sample_df)
bot._close_and_reenter.assert_awaited_once()
call_args = bot._close_and_reenter.call_args
assert call_args.args[1] == "SHORT"
```
### Step 2: 테스트 실행 — 실패 확인
```bash
bash scripts/test_reverse_reenter.sh 3
```
예상 결과: FAIL (`_close_and_reenter`가 아직 호출되지 않음)
### Step 3: `process_candle` 수정
`src/bot.py`에서 아래 부분을 찾아 수정한다.
```python
# 변경 전 (81~85번째 줄 근처)
elif position is not None:
pos_side = "LONG" if float(position["positionAmt"]) > 0 else "SHORT"
if (pos_side == "LONG" and signal == "SHORT") or \
(pos_side == "SHORT" and signal == "LONG"):
await self._close_position(position)
# 변경 후
elif position is not None:
pos_side = "LONG" if float(position["positionAmt"]) > 0 else "SHORT"
if (pos_side == "LONG" and signal == "SHORT") or \
(pos_side == "SHORT" and signal == "LONG"):
await self._close_and_reenter(
position, signal, df_with_indicators, btc_df=btc_df, eth_df=eth_df
)
```
### Step 4: 전체 테스트 실행 — 통과 확인
```bash
bash scripts/test_reverse_reenter.sh bot
```
예상 결과: 전체 PASS (기존 테스트 포함)
### Step 5: 커밋
```bash
git add src/bot.py tests/test_bot.py
git commit -m "feat: call _close_and_reenter on reverse signal in process_candle"
```
---
## Task 4: 전체 테스트 스위트 확인
### Step 1: 전체 테스트 실행
```bash
bash scripts/test_reverse_reenter.sh all
```
예상 결과: 모든 테스트 PASS
### Step 2: 실패 테스트 있으면 수정 후 재실행
실패가 있으면 원인을 파악하고 수정한다. 기존 테스트를 깨뜨리지 않도록 주의.

View File

@@ -0,0 +1,203 @@
# RS np.divide 복구 / MLX NaN-Safe 통계 저장 구현 계획
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** RS(상대강도) 계산의 epsilon 폭발 이상치를 `np.divide` 방식으로 제거하고, MLXFilter의 `self._mean`/`self._std`에 NaN이 잔류하는 근본 허점을 차단한다.
**Architecture:**
- `src/dataset_builder.py`: `xrp_btc_rs_raw` / `xrp_eth_rs_raw` 계산을 `np.divide(..., where=...)` 방식으로 교체. 분모(btc_r1, eth_r1)가 0이면 결과를 0.0으로 채워 rolling zscore 윈도우 오염을 방지한다.
- `src/mlx_filter.py`: `fit()` 내부에서 `self._mean`/`self._std`를 저장하기 전에 `nan_to_num`을 적용해 전체-NaN 컬럼(OI 초반 구간 등)이 `predict_proba` 시점까지 NaN을 전파하지 않도록 한다.
**Tech Stack:** numpy, pandas, pytest, mlx(Apple Silicon 전용 — MLX 테스트는 Mac에서만 실행)
---
### Task 1: `dataset_builder.py` — RS 계산을 `np.divide` 방식으로 교체
**Files:**
- Modify: `src/dataset_builder.py:245-246`
- Test: `tests/test_dataset_builder.py`
**배경:**
`btc_r1 = 0.0`(15분 동안 BTC 가격 변동 없음)일 때 `xrp_r1 / (btc_r1 + 1e-8)`는 최대 수백만의 이상치를 만든다. 이 이상치가 288캔들 rolling zscore 윈도우에 들어가면 나머지 287개 값이 전부 0에 가깝게 압사된다.
**Step 1: 기존 테스트 실행 (기준선 확인)**
```bash
python -m pytest tests/test_dataset_builder.py -v
```
Expected: 모든 테스트 PASS (변경 전 기준선)
**Step 2: RS 제로-분모 테스트 작성**
`tests/test_dataset_builder.py` 파일 끝에 추가:
```python
def test_rs_zero_denominator():
"""btc_r1=0일 때 RS가 inf/nan이 아닌 0.0이어야 한다 (np.divide 방식 검증)."""
import numpy as np
import pandas as pd
from src.dataset_builder import _calc_features_vectorized, _calc_signals, _calc_indicators
n = 500
np.random.seed(7)
# XRP close: 약간의 변동
xrp_close = np.cumprod(1 + np.random.randn(n) * 0.001) * 1.0
xrp_df = pd.DataFrame({
"open": xrp_close * 0.999,
"high": xrp_close * 1.005,
"low": xrp_close * 0.995,
"close": xrp_close,
"volume": np.random.rand(n) * 1000 + 500,
})
# BTC close: 완전히 고정 → btc_r1 = 0.0
btc_close = np.ones(n) * 50000.0
btc_df = pd.DataFrame({
"open": btc_close,
"high": btc_close,
"low": btc_close,
"close": btc_close,
"volume": np.random.rand(n) * 1000 + 500,
})
from src.dataset_builder import generate_dataset_vectorized
result = generate_dataset_vectorized(xrp_df, btc_df=btc_df)
if result.empty:
pytest.skip("신호 없음")
assert "xrp_btc_rs" in result.columns, "xrp_btc_rs 컬럼이 있어야 함"
assert not result["xrp_btc_rs"].isin([np.inf, -np.inf]).any(), \
"xrp_btc_rs에 inf가 있으면 안 됨"
assert not result["xrp_btc_rs"].isna().all(), \
"xrp_btc_rs가 전부 nan이면 안 됨"
```
**Step 3: 테스트 실행 (FAIL 확인)**
```bash
python -m pytest tests/test_dataset_builder.py::test_rs_zero_denominator -v
```
Expected: FAIL — `xrp_btc_rs에 inf가 있으면 안 됨` (현재 epsilon 방식은 inf 대신 수백만 이상치를 만들어 rolling zscore 후 nan이 될 수 있음)
> 참고: 현재 코드는 inf를 직접 만들지 않을 수도 있다. 하지만 rolling zscore 후 nan이 생기거나 이상치가 남아있는지 확인하는 것이 목적이다. PASS가 나오더라도 Step 4를 진행한다.
**Step 4: `dataset_builder.py` 245~246줄 수정**
`src/dataset_builder.py`의 아래 두 줄을:
```python
xrp_btc_rs_raw = (xrp_r1 / (btc_r1 + 1e-8)).astype(np.float32)
xrp_eth_rs_raw = (xrp_r1 / (eth_r1 + 1e-8)).astype(np.float32)
```
다음으로 교체:
```python
xrp_btc_rs_raw = np.divide(
xrp_r1, btc_r1,
out=np.zeros_like(xrp_r1),
where=(btc_r1 != 0),
).astype(np.float32)
xrp_eth_rs_raw = np.divide(
xrp_r1, eth_r1,
out=np.zeros_like(xrp_r1),
where=(eth_r1 != 0),
).astype(np.float32)
```
**Step 5: 전체 테스트 실행 (PASS 확인)**
```bash
python -m pytest tests/test_dataset_builder.py -v
```
Expected: 모든 테스트 PASS
**Step 6: 커밋**
```bash
git add src/dataset_builder.py tests/test_dataset_builder.py
git commit -m "fix: RS 계산을 np.divide(where=) 방식으로 교체 — epsilon 이상치 폭발 차단"
```
---
### Task 2: `mlx_filter.py` — `self._mean`/`self._std` 저장 전 `nan_to_num` 적용
**Files:**
- Modify: `src/mlx_filter.py:145-146`
- Test: `tests/test_mlx_filter.py` (기존 `test_fit_with_nan_features` 활용)
**배경:**
현재 코드는 `self._mean = np.nanmean(X_np, axis=0)`으로 저장한다. 전체가 NaN인 컬럼(Walk-Forward 초반 11개월의 OI 데이터)이 있으면 `np.nanmean`은 해당 컬럼의 평균으로 NaN을 반환한다. 이 NaN이 `self._mean`에 저장되면 `predict_proba` 시점에 `(X_np - self._mean)`이 NaN이 되어 OI 데이터를 영원히 활용하지 못한다.
**Step 1: 기존 테스트 실행 (기준선 확인)**
```bash
python -m pytest tests/test_mlx_filter.py -v
```
Expected: 모든 테스트 PASS (MLX 없는 환경에서는 전체 SKIP)
**Step 2: `mlx_filter.py` 145~146줄 수정**
`src/mlx_filter.py`의 아래 두 줄을:
```python
self._mean = np.nanmean(X_np, axis=0)
self._std = np.nanstd(X_np, axis=0) + 1e-8
```
다음으로 교체:
```python
mean_vals = np.nanmean(X_np, axis=0)
self._mean = np.nan_to_num(mean_vals, nan=0.0) # 전체-NaN 컬럼 → 평균 0.0
std_vals = np.nanstd(X_np, axis=0)
self._std = np.nan_to_num(std_vals, nan=1.0) + 1e-8 # 전체-NaN 컬럼 → std 1.0
```
**Step 3: 테스트 실행 (PASS 확인)**
```bash
python -m pytest tests/test_mlx_filter.py::test_fit_with_nan_features -v
```
Expected: PASS (MLX 없는 환경에서는 SKIP)
**Step 4: 전체 테스트 실행**
```bash
python -m pytest tests/test_mlx_filter.py -v
```
Expected: 모든 테스트 PASS (또는 SKIP)
**Step 5: 커밋**
```bash
git add src/mlx_filter.py
git commit -m "fix: MLXFilter self._mean/std 저장 전 nan_to_num 적용 — 전체-NaN 컬럼 predict_proba 오염 차단"
```
---
### Task 3: 전체 테스트 통과 확인
**Step 1: 전체 테스트 실행**
```bash
python -m pytest tests/ -v --tb=short 2>&1 | tail -40
```
Expected: 모든 테스트 PASS (MLX 관련은 SKIP 허용)
**Step 2: 최종 커밋 (필요 시)**
```bash
git add -A
git commit -m "chore: RS epsilon 폭발 차단 + MLX NaN-Safe 통계 저장 통합"
```

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -216,5 +216,65 @@
"train_sec": 0.1, "train_sec": 0.1,
"time_weight_decay": 2.0, "time_weight_decay": 2.0,
"model_path": "models/mlx_filter.weights" "model_path": "models/mlx_filter.weights"
},
{
"date": "2026-03-01T23:59:27.956019",
"backend": "mlx",
"auc": 0.5595,
"best_threshold": 0.9538,
"best_precision": 0.462,
"best_recall": 0.171,
"samples": 533,
"train_sec": 0.2,
"time_weight_decay": 2.0,
"model_path": "models/mlx_filter.weights"
},
{
"date": "2026-03-02T00:40:15.931055",
"backend": "mlx",
"auc": 0.5829,
"best_threshold": 0.9609,
"best_precision": 0.6,
"best_recall": 0.171,
"samples": 534,
"train_sec": 0.2,
"time_weight_decay": 2.0,
"model_path": "models/mlx_filter.weights"
},
{
"date": "2026-03-02T00:54:32.264425",
"backend": "lgbm",
"auc": 0.5607,
"best_threshold": 0.6532,
"best_precision": 0.467,
"best_recall": 0.2,
"samples": 533,
"features": 23,
"time_weight_decay": 2.0,
"model_path": "models/lgbm_filter.pkl"
},
{
"date": "2026-03-02T01:07:30.690959",
"backend": "lgbm",
"auc": 0.5579,
"best_threshold": 0.6511,
"best_precision": 0.4,
"best_recall": 0.171,
"samples": 533,
"features": 23,
"time_weight_decay": 2.0,
"model_path": "models/lgbm_filter.pkl"
},
{
"date": "2026-03-02T02:00:45.931227",
"backend": "lgbm",
"auc": 0.5752,
"best_threshold": 0.6307,
"best_precision": 0.471,
"best_recall": 0.229,
"samples": 533,
"features": 23,
"time_weight_decay": 2.0,
"model_path": "models/lgbm_filter.pkl"
} }
] ]

View File

@@ -1,4 +1,4 @@
python-binance==1.0.19 python-binance>=1.0.28
pandas>=2.3.2 pandas>=2.3.2
pandas-ta==0.4.71b0 pandas-ta==0.4.71b0
python-dotenv==1.0.0 python-dotenv==1.0.0

View File

@@ -33,12 +33,25 @@ done
echo "=== 모델 전송 시작 (백엔드: ${BACKEND}) ===" echo "=== 모델 전송 시작 (백엔드: ${BACKEND}) ==="
echo " 대상: ${LXC_HOST}:${LXC_MODELS_PATH}" echo " 대상: ${LXC_HOST}:${LXC_MODELS_PATH}"
# ── 원격 디렉터리 생성 + lgbm 기존 모델 백업 ───────────────────────────────── # ── 원격 디렉터리 생성 + 백업 + 상대 백엔드 파일 제거 ───────────────────────
# lgbm 배포 시: 기존 lgbm 백업 후 ONNX 파일 삭제 (ONNX 우선순위 때문에 lgbm이 무시되는 것 방지)
# mlx 배포 시: lgbm 파일 삭제 (명시적으로 mlx만 사용)
ssh "${LXC_HOST}" " ssh "${LXC_HOST}" "
mkdir -p '${LXC_MODELS_PATH}' mkdir -p '${LXC_MODELS_PATH}'
if [ '$BACKEND' = 'lgbm' ] && [ -f '${LXC_MODELS_PATH}/lgbm_filter.pkl' ]; then if [ '$BACKEND' = 'lgbm' ]; then
cp '${LXC_MODELS_PATH}/lgbm_filter.pkl' '${LXC_MODELS_PATH}/lgbm_filter_prev.pkl' if [ -f '${LXC_MODELS_PATH}/lgbm_filter.pkl' ]; then
echo ' 기존 lgbm 모델 백업 완료' cp '${LXC_MODELS_PATH}/lgbm_filter.pkl' '${LXC_MODELS_PATH}/lgbm_filter_prev.pkl'
echo ' 기존 lgbm 모델 백업 완료'
fi
if [ -f '${LXC_MODELS_PATH}/mlx_filter.weights.onnx' ]; then
rm '${LXC_MODELS_PATH}/mlx_filter.weights.onnx'
echo ' ONNX 파일 제거 완료 (lgbm 우선 적용)'
fi
else
if [ -f '${LXC_MODELS_PATH}/lgbm_filter.pkl' ]; then
rm '${LXC_MODELS_PATH}/lgbm_filter.pkl'
echo ' lgbm 파일 제거 완료 (mlx 우선 적용)'
fi
fi fi
" "

26
scripts/run_tests.sh Executable file
View File

@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# 전체 테스트 실행 스크립트
#
# 사용법:
# bash scripts/run_tests.sh # 전체 실행
# bash scripts/run_tests.sh -k bot # 특정 키워드 필터
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
VENV_PATH="${VENV_PATH:-$PROJECT_ROOT/.venv}"
if [ -f "$VENV_PATH/bin/activate" ]; then
# shellcheck source=/dev/null
source "$VENV_PATH/bin/activate"
else
echo "경고: 가상환경을 찾을 수 없습니다 ($VENV_PATH). 시스템 Python을 사용합니다." >&2
fi
cd "$PROJECT_ROOT"
python -m pytest tests/ \
--ignore=tests/test_database.py \
-v \
"$@"

83
scripts/test_reverse_reenter.sh Executable file
View File

@@ -0,0 +1,83 @@
#!/usr/bin/env bash
# 반대 시그널 재진입 기능 테스트 스크립트
# 사용법: bash scripts/test_reverse_reenter.sh [task]
#
# 예시:
# bash scripts/test_reverse_reenter.sh # 전체 태스크 순서대로 실행
# bash scripts/test_reverse_reenter.sh 1 # Task 1: 신규 테스트만 (실패 확인)
# bash scripts/test_reverse_reenter.sh 2 # Task 2: _close_and_reenter 메서드 테스트
# bash scripts/test_reverse_reenter.sh 3 # Task 3: process_candle 분기 테스트
# bash scripts/test_reverse_reenter.sh bot # test_bot.py 전체
# bash scripts/test_reverse_reenter.sh all # tests/ 전체
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
VENV_PATH="${VENV_PATH:-$PROJECT_ROOT/.venv}"
if [ -f "$VENV_PATH/bin/activate" ]; then
# shellcheck source=/dev/null
source "$VENV_PATH/bin/activate"
else
echo "경고: 가상환경을 찾을 수 없습니다 ($VENV_PATH). 시스템 Python을 사용합니다." >&2
fi
cd "$PROJECT_ROOT"
TASK="${1:-all}"
# ── 태스크별 테스트 이름 ──────────────────────────────────────────────────────
TASK1_TESTS=(
"tests/test_bot.py::test_close_and_reenter_calls_open_when_ml_passes"
"tests/test_bot.py::test_close_and_reenter_skips_open_when_ml_blocks"
"tests/test_bot.py::test_close_and_reenter_skips_open_when_max_positions_reached"
)
TASK2_TESTS=(
"tests/test_bot.py::test_close_and_reenter_calls_open_when_ml_passes"
"tests/test_bot.py::test_close_and_reenter_skips_open_when_ml_blocks"
"tests/test_bot.py::test_close_and_reenter_skips_open_when_max_positions_reached"
)
TASK3_TESTS=(
"tests/test_bot.py::test_process_candle_calls_close_and_reenter_on_reverse_signal"
)
run_pytest() {
echo ""
echo "▶ pytest $*"
echo "────────────────────────────────────────"
python -m pytest "$@" -v
}
case "$TASK" in
1)
echo "=== Task 1: 신규 테스트 실행 (구현 전 → FAIL 예상) ==="
run_pytest "${TASK1_TESTS[@]}"
;;
2)
echo "=== Task 2: _close_and_reenter 메서드 테스트 (구현 후 → PASS 예상) ==="
run_pytest "${TASK2_TESTS[@]}"
;;
3)
echo "=== Task 3: process_candle 분기 테스트 (수정 후 → PASS 예상) ==="
run_pytest "${TASK3_TESTS[@]}"
;;
bot)
echo "=== test_bot.py 전체 ==="
run_pytest tests/test_bot.py
;;
all)
echo "=== 전체 테스트 스위트 ==="
run_pytest tests/
;;
*)
echo "알 수 없는 태스크: $TASK"
echo "사용법: bash scripts/test_reverse_reenter.sh [1|2|3|bot|all]"
exit 1
;;
esac
echo ""
echo "=== 완료 ==="

View File

@@ -1,4 +1,4 @@
import asyncio import pandas as pd
from loguru import logger from loguru import logger
from src.config import Config from src.config import Config
from src.exchange import BinanceFuturesClient from src.exchange import BinanceFuturesClient
@@ -24,12 +24,12 @@ class TradingBot:
on_candle=self._on_candle_closed, on_candle=self._on_candle_closed,
) )
def _on_candle_closed(self, candle: dict): async def _on_candle_closed(self, candle: dict):
xrp_df = self.stream.get_dataframe(self.config.symbol) xrp_df = self.stream.get_dataframe(self.config.symbol)
btc_df = self.stream.get_dataframe("BTCUSDT") btc_df = self.stream.get_dataframe("BTCUSDT")
eth_df = self.stream.get_dataframe("ETHUSDT") eth_df = self.stream.get_dataframe("ETHUSDT")
if xrp_df is not None: if xrp_df is not None:
asyncio.create_task(self.process_candle(xrp_df, btc_df=btc_df, eth_df=eth_df)) await self.process_candle(xrp_df, btc_df=btc_df, eth_df=eth_df)
async def _recover_position(self) -> None: async def _recover_position(self) -> None:
"""재시작 시 바이낸스에서 현재 포지션을 조회하여 상태 복구.""" """재시작 시 바이낸스에서 현재 포지션을 조회하여 상태 복구."""
@@ -58,31 +58,33 @@ class TradingBot:
ind = Indicators(df) ind = Indicators(df)
df_with_indicators = ind.calculate_all() df_with_indicators = ind.calculate_all()
signal = ind.get_signal(df_with_indicators) raw_signal = ind.get_signal(df_with_indicators)
if signal != "HOLD" and self.ml_filter.is_model_loaded():
features = build_features(df_with_indicators, signal, btc_df=btc_df, eth_df=eth_df)
if not self.ml_filter.should_enter(features):
logger.info(f"ML 필터 차단: {signal} 신호 무시")
signal = "HOLD"
current_price = df_with_indicators["close"].iloc[-1] current_price = df_with_indicators["close"].iloc[-1]
logger.info(f"신호: {signal} | 현재가: {current_price:.4f} USDT") logger.info(f"신호: {raw_signal} | 현재가: {current_price:.4f} USDT")
position = await self.exchange.get_position() position = await self.exchange.get_position()
if position is None and signal != "HOLD": if position is None and raw_signal != "HOLD":
self.current_trade_side = None self.current_trade_side = None
if not self.risk.can_open_new_position(): if not self.risk.can_open_new_position():
logger.info("최대 포지션 수 도달") logger.info("최대 포지션 수 도달")
return return
signal = raw_signal
if self.ml_filter.is_model_loaded():
features = build_features(df_with_indicators, signal, btc_df=btc_df, eth_df=eth_df)
if not self.ml_filter.should_enter(features):
logger.info(f"ML 필터 차단: {signal} 신호 무시")
return
await self._open_position(signal, df_with_indicators) await self._open_position(signal, df_with_indicators)
elif position is not None: elif position is not None:
pos_side = "LONG" if float(position["positionAmt"]) > 0 else "SHORT" pos_side = "LONG" if float(position["positionAmt"]) > 0 else "SHORT"
if (pos_side == "LONG" and signal == "SHORT") or \ if (pos_side == "LONG" and raw_signal == "SHORT") or \
(pos_side == "SHORT" and signal == "LONG"): (pos_side == "SHORT" and raw_signal == "LONG"):
await self._close_position(position) await self._close_and_reenter(
position, raw_signal, df_with_indicators, btc_df=btc_df, eth_df=eth_df
)
async def _open_position(self, signal: str, df): async def _open_position(self, signal: str, df):
balance = await self.exchange.get_balance() balance = await self.exchange.get_balance()
@@ -108,9 +110,9 @@ class TradingBot:
last_row = df.iloc[-1] last_row = df.iloc[-1]
signal_snapshot = { signal_snapshot = {
"rsi": float(last_row.get("rsi", 0)), "rsi": float(last_row["rsi"]) if "rsi" in last_row.index and pd.notna(last_row["rsi"]) else 0.0,
"macd_hist": float(last_row.get("macd_hist", 0)), "macd_hist": float(last_row["macd_hist"]) if "macd_hist" in last_row.index and pd.notna(last_row["macd_hist"]) else 0.0,
"atr": float(last_row.get("atr", 0)), "atr": float(last_row["atr"]) if "atr" in last_row.index and pd.notna(last_row["atr"]) else 0.0,
} }
self.current_trade_side = signal self.current_trade_side = signal
@@ -166,6 +168,29 @@ class TradingBot:
self.current_trade_side = None self.current_trade_side = None
logger.success(f"포지션 청산: PnL={pnl:.4f} USDT") logger.success(f"포지션 청산: PnL={pnl:.4f} USDT")
async def _close_and_reenter(
self,
position: dict,
signal: str,
df,
btc_df=None,
eth_df=None,
) -> None:
"""기존 포지션을 청산하고, ML 필터 통과 시 반대 방향으로 즉시 재진입한다."""
await self._close_position(position)
if not self.risk.can_open_new_position():
logger.info("최대 포지션 수 도달 — 재진입 건너뜀")
return
if self.ml_filter.is_model_loaded():
features = build_features(df, signal, btc_df=btc_df, eth_df=eth_df)
if not self.ml_filter.should_enter(features):
logger.info(f"ML 필터 차단: {signal} 재진입 무시")
return
await self._open_position(signal, df)
async def run(self): async def run(self):
logger.info(f"봇 시작: {self.config.symbol}, 레버리지 {self.config.leverage}x") logger.info(f"봇 시작: {self.config.symbol}, 레버리지 {self.config.leverage}x")
await self._recover_position() await self._recover_position()

View File

@@ -40,12 +40,12 @@ class KlineStream:
"is_closed": k["x"], "is_closed": k["x"],
} }
def handle_message(self, msg: dict): async def handle_message(self, msg: dict):
candle = self.parse_kline(msg) candle = self.parse_kline(msg)
if candle["is_closed"]: if candle["is_closed"]:
self.buffer.append(candle) self.buffer.append(candle)
if self.on_candle: if self.on_candle:
self.on_candle(candle) await self.on_candle(candle)
def get_dataframe(self) -> pd.DataFrame | None: def get_dataframe(self) -> pd.DataFrame | None:
if len(self.buffer) < _MIN_CANDLES_FOR_SIGNAL: if len(self.buffer) < _MIN_CANDLES_FOR_SIGNAL:
@@ -90,7 +90,7 @@ class KlineStream:
) as stream: ) as stream:
while True: while True:
msg = await stream.recv() msg = await stream.recv()
self.handle_message(msg) await self.handle_message(msg)
finally: finally:
await client.close_connection() await client.close_connection()
@@ -129,7 +129,7 @@ class MultiSymbolStream:
"is_closed": k["x"], "is_closed": k["x"],
} }
def handle_message(self, msg: dict): async def handle_message(self, msg: dict):
# Combined stream 메시지는 {"stream": "...", "data": {...}} 형태 # Combined stream 메시지는 {"stream": "...", "data": {...}} 형태
if "stream" in msg: if "stream" in msg:
data = msg["data"] data = msg["data"]
@@ -145,7 +145,7 @@ class MultiSymbolStream:
if candle["is_closed"] and symbol in self.buffers: if candle["is_closed"] and symbol in self.buffers:
self.buffers[symbol].append(candle) self.buffers[symbol].append(candle)
if symbol == self.primary_symbol and self.on_candle: if symbol == self.primary_symbol and self.on_candle:
self.on_candle(candle) await self.on_candle(candle)
def get_dataframe(self, symbol: str) -> pd.DataFrame | None: def get_dataframe(self, symbol: str) -> pd.DataFrame | None:
key = symbol.lower() key = symbol.lower()
@@ -192,6 +192,6 @@ class MultiSymbolStream:
async with bm.futures_multiplex_socket(streams) as stream: async with bm.futures_multiplex_socket(streams) as stream:
while True: while True:
msg = await stream.recv() msg = await stream.recv()
self.handle_message(msg) await self.handle_message(msg)
finally: finally:
await client.close_connection() await client.close_connection()

View File

@@ -242,8 +242,16 @@ def _calc_features_vectorized(
eth_r5 = _align(eth_ret_5, n).astype(np.float32) eth_r5 = _align(eth_ret_5, n).astype(np.float32)
xrp_r1 = ret_1.astype(np.float32) xrp_r1 = ret_1.astype(np.float32)
xrp_btc_rs_raw = (xrp_r1 / (btc_r1 + 1e-8)).astype(np.float32) xrp_btc_rs_raw = np.divide(
xrp_eth_rs_raw = (xrp_r1 / (eth_r1 + 1e-8)).astype(np.float32) xrp_r1, btc_r1,
out=np.zeros_like(xrp_r1),
where=(btc_r1 != 0),
).astype(np.float32)
xrp_eth_rs_raw = np.divide(
xrp_r1, eth_r1,
out=np.zeros_like(xrp_r1),
where=(eth_r1 != 0),
).astype(np.float32)
extra = pd.DataFrame({ extra = pd.DataFrame({
"btc_ret_1": _rolling_zscore(btc_r1), "btc_ret_1": _rolling_zscore(btc_r1),

View File

@@ -45,6 +45,8 @@ class BinanceFuturesClient:
return float(b["balance"]) return float(b["balance"])
return 0.0 return 0.0
_ALGO_ORDER_TYPES = {"STOP_MARKET", "TAKE_PROFIT_MARKET", "STOP", "TAKE_PROFIT", "TRAILING_STOP_MARKET"}
async def place_order( async def place_order(
self, self,
side: str, side: str,
@@ -55,6 +57,16 @@ class BinanceFuturesClient:
reduce_only: bool = False, reduce_only: bool = False,
) -> dict: ) -> dict:
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
if order_type in self._ALGO_ORDER_TYPES:
return await self._place_algo_order(
side=side,
quantity=quantity,
order_type=order_type,
stop_price=stop_price,
reduce_only=reduce_only,
)
params = dict( params = dict(
symbol=self.config.symbol, symbol=self.config.symbol,
side=side, side=side,
@@ -75,6 +87,34 @@ class BinanceFuturesClient:
logger.error(f"주문 실패: {e}") logger.error(f"주문 실패: {e}")
raise raise
async def _place_algo_order(
self,
side: str,
quantity: float,
order_type: str,
stop_price: float = None,
reduce_only: bool = False,
) -> dict:
"""STOP_MARKET / TAKE_PROFIT_MARKET 등 Algo Order API(/fapi/v1/algoOrder)로 전송."""
loop = asyncio.get_event_loop()
params = dict(
symbol=self.config.symbol,
side=side,
algoType="CONDITIONAL",
type=order_type,
quantity=quantity,
reduceOnly="true" if reduce_only else "false",
)
if stop_price:
params["triggerPrice"] = stop_price
try:
return await loop.run_in_executor(
None, lambda: self.client.futures_create_algo_order(**params)
)
except BinanceAPIException as e:
logger.error(f"Algo 주문 실패: {e}")
raise
async def get_position(self) -> dict | None: async def get_position(self) -> dict | None:
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
positions = await loop.run_in_executor( positions = await loop.run_in_executor(
@@ -89,10 +129,20 @@ class BinanceFuturesClient:
return None return None
async def cancel_all_orders(self): async def cancel_all_orders(self):
"""일반 오픈 주문과 Algo 오픈 주문을 모두 취소한다."""
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
return await loop.run_in_executor( await loop.run_in_executor(
None, None,
lambda: self.client.futures_cancel_all_open_orders( lambda: self.client.futures_cancel_all_open_orders(
symbol=self.config.symbol symbol=self.config.symbol
), ),
) )
try:
await loop.run_in_executor(
None,
lambda: self.client.futures_cancel_all_algo_open_orders(
symbol=self.config.symbol
),
)
except Exception as e:
logger.warning(f"Algo 주문 전체 취소 실패 (무시): {e}")

View File

@@ -127,4 +127,8 @@ def build_features(
"xrp_eth_rs": float(_calc_rs(ret_1, eth_ret_1)), "xrp_eth_rs": float(_calc_rs(ret_1, eth_ret_1)),
}) })
# 실시간에서는 OI/펀딩비를 수집하지 않으므로 0으로 채워 학습 피처(23개)와 일치시킨다
base.setdefault("oi_change", 0.0)
base.setdefault("funding_rate", 0.0)
return pd.Series(base) return pd.Series(base)

View File

@@ -53,8 +53,12 @@ class MLFilter:
if self._onnx_path.exists(): if self._onnx_path.exists():
try: try:
import onnxruntime as ort import onnxruntime as ort
sess_opts = ort.SessionOptions()
sess_opts.intra_op_num_threads = 1
sess_opts.inter_op_num_threads = 1
self._onnx_session = ort.InferenceSession( self._onnx_session = ort.InferenceSession(
str(self._onnx_path), str(self._onnx_path),
sess_options=sess_opts,
providers=["CPUExecutionProvider"], providers=["CPUExecutionProvider"],
) )
self._lgbm_model = None self._lgbm_model = None

View File

@@ -71,15 +71,20 @@ def _export_onnx(
transB=1), transB=1),
# sigmoid → (N, 1) # sigmoid → (N, 1)
helper.make_node("Sigmoid", ["logits"], ["proba_2d"]), helper.make_node("Sigmoid", ["logits"], ["proba_2d"]),
# squeeze: (N, 1) → (N,) # squeeze: (N, 1) → (N,) — axis=-1 로 마지막 차원만 제거
helper.make_node("Flatten", ["proba_2d"], ["proba"], axis=0), helper.make_node("Squeeze", ["proba_2d", "squeeze_axes"], ["proba"]),
] ]
squeeze_axes = numpy_helper.from_array(
np.array([-1], dtype=np.int64), name="squeeze_axes"
)
initializers.append(squeeze_axes)
graph = helper.make_graph( graph = helper.make_graph(
nodes, nodes,
"mlx_filter", "mlx_filter",
inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, [None, input_dim])], inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, [None, input_dim])],
outputs=[helper.make_tensor_value_info("proba", TensorProto.FLOAT, [None])], outputs=[helper.make_tensor_value_info("proba", TensorProto.FLOAT, [-1])],
initializer=initializers, initializer=initializers,
) )
model_proto = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)]) model_proto = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)])
@@ -142,8 +147,10 @@ class MLXFilter:
# nan-safe 정규화: nanmean/nanstd로 통계 계산 후 nan → 0.0 대치 # nan-safe 정규화: nanmean/nanstd로 통계 계산 후 nan → 0.0 대치
# (z-score 후 0.0 = 평균값, 신경망에 줄 수 있는 가장 무난한 결측 대치값) # (z-score 후 0.0 = 평균값, 신경망에 줄 수 있는 가장 무난한 결측 대치값)
self._mean = np.nanmean(X_np, axis=0) mean_vals = np.nanmean(X_np, axis=0)
self._std = np.nanstd(X_np, axis=0) + 1e-8 self._mean = np.nan_to_num(mean_vals, nan=0.0) # 전체-NaN 컬럼 → 평균 0.0
std_vals = np.nanstd(X_np, axis=0)
self._std = np.nan_to_num(std_vals, nan=1.0) + 1e-8 # 전체-NaN 컬럼 → std 1.0
X_np = (X_np - self._mean) / self._std X_np = (X_np - self._mean) / self._std
X_np = np.nan_to_num(X_np, nan=0.0) X_np = np.nan_to_num(X_np, nan=0.0)

View File

@@ -69,3 +69,122 @@ async def test_bot_processes_signal(config, sample_df):
mock_ind.get_atr_stop.return_value = (0.48, 0.56) mock_ind.get_atr_stop.return_value = (0.48, 0.56)
MockInd.return_value = mock_ind MockInd.return_value = mock_ind
await bot.process_candle(sample_df) await bot.process_candle(sample_df)
@pytest.mark.asyncio
async def test_close_and_reenter_calls_open_when_ml_passes(config, sample_df):
"""반대 시그널 + ML 필터 통과 시 청산 후 재진입해야 한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot._close_position = AsyncMock()
bot._open_position = AsyncMock()
bot.risk = MagicMock()
bot.risk.can_open_new_position.return_value = True
bot.ml_filter = MagicMock()
bot.ml_filter.is_model_loaded.return_value = True
bot.ml_filter.should_enter.return_value = True
position = {"positionAmt": "100", "entryPrice": "0.5", "markPrice": "0.52"}
await bot._close_and_reenter(position, "SHORT", sample_df)
bot._close_position.assert_awaited_once_with(position)
bot._open_position.assert_awaited_once_with("SHORT", sample_df)
@pytest.mark.asyncio
async def test_close_and_reenter_skips_open_when_ml_blocks(config, sample_df):
"""ML 필터 차단 시 청산만 하고 재진입하지 않아야 한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot._close_position = AsyncMock()
bot._open_position = AsyncMock()
bot.ml_filter = MagicMock()
bot.ml_filter.is_model_loaded.return_value = True
bot.ml_filter.should_enter.return_value = False
position = {"positionAmt": "100", "entryPrice": "0.5", "markPrice": "0.52"}
await bot._close_and_reenter(position, "SHORT", sample_df)
bot._close_position.assert_awaited_once_with(position)
bot._open_position.assert_not_called()
@pytest.mark.asyncio
async def test_close_and_reenter_skips_open_when_max_positions_reached(config, sample_df):
"""최대 포지션 수 도달 시 청산만 하고 재진입하지 않아야 한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot._close_position = AsyncMock()
bot._open_position = AsyncMock()
bot.risk = MagicMock()
bot.risk.can_open_new_position.return_value = False
position = {"positionAmt": "100", "entryPrice": "0.5", "markPrice": "0.52"}
await bot._close_and_reenter(position, "SHORT", sample_df)
bot._close_position.assert_awaited_once_with(position)
bot._open_position.assert_not_called()
@pytest.mark.asyncio
async def test_process_candle_calls_close_and_reenter_on_reverse_signal(config, sample_df):
"""반대 시그널 시 process_candle이 _close_and_reenter를 호출해야 한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot.exchange = AsyncMock()
bot.exchange.get_position = AsyncMock(return_value={
"positionAmt": "100",
"entryPrice": "0.5",
"markPrice": "0.52",
})
bot._close_and_reenter = AsyncMock()
bot.ml_filter = MagicMock()
bot.ml_filter.is_model_loaded.return_value = False
bot.ml_filter.should_enter.return_value = True
with patch("src.bot.Indicators") as MockInd:
mock_ind = MagicMock()
mock_ind.calculate_all.return_value = sample_df
mock_ind.get_signal.return_value = "SHORT" # 현재 LONG 포지션에 반대 시그널
MockInd.return_value = mock_ind
await bot.process_candle(sample_df)
bot._close_and_reenter.assert_awaited_once()
call_args = bot._close_and_reenter.call_args
assert call_args.args[1] == "SHORT"
@pytest.mark.asyncio
async def test_process_candle_passes_raw_signal_to_close_and_reenter_even_if_ml_loaded(config, sample_df):
"""포지션 보유 시 ML 필터가 로드되어 있어도 process_candle은 raw signal을 _close_and_reenter에 전달한다."""
with patch("src.bot.BinanceFuturesClient"):
bot = TradingBot(config)
bot.exchange = AsyncMock()
bot.exchange.get_position = AsyncMock(return_value={
"positionAmt": "100",
"entryPrice": "0.5",
"markPrice": "0.52",
})
bot._close_and_reenter = AsyncMock()
bot.ml_filter = MagicMock()
bot.ml_filter.is_model_loaded.return_value = True # 모델 로드됨
bot.ml_filter.should_enter.return_value = False # ML이 차단하더라도
with patch("src.bot.Indicators") as MockInd:
mock_ind = MagicMock()
mock_ind.calculate_all.return_value = sample_df
mock_ind.get_signal.return_value = "SHORT"
MockInd.return_value = mock_ind
await bot.process_candle(sample_df)
# ML 필터가 차단해도 _close_and_reenter는 호출되어야 한다 (ML 재평가는 내부에서)
bot._close_and_reenter.assert_awaited_once()
call_args = bot._close_and_reenter.call_args
assert call_args.args[1] == "SHORT"
# process_candle에서 ml_filter.should_enter가 호출되지 않아야 한다
bot.ml_filter.should_enter.assert_not_called()

View File

@@ -23,6 +23,7 @@ def test_multi_symbol_stream_get_dataframe_returns_none_when_empty():
def test_multi_symbol_stream_get_dataframe_returns_df_when_full(): def test_multi_symbol_stream_get_dataframe_returns_df_when_full():
import pandas as pd import pandas as pd
from src.data_stream import _MIN_CANDLES_FOR_SIGNAL
stream = MultiSymbolStream( stream = MultiSymbolStream(
symbols=["XRPUSDT", "BTCUSDT", "ETHUSDT"], symbols=["XRPUSDT", "BTCUSDT", "ETHUSDT"],
interval="1m", interval="1m",
@@ -32,13 +33,13 @@ def test_multi_symbol_stream_get_dataframe_returns_df_when_full():
"timestamp": 1000, "open": 1.0, "high": 1.1, "timestamp": 1000, "open": 1.0, "high": 1.1,
"low": 0.9, "close": 1.05, "volume": 100.0, "is_closed": True, "low": 0.9, "close": 1.05, "volume": 100.0, "is_closed": True,
} }
for i in range(50): for i in range(_MIN_CANDLES_FOR_SIGNAL):
c = candle.copy() c = candle.copy()
c["timestamp"] = 1000 + i c["timestamp"] = 1000 + i
stream.buffers["xrpusdt"].append(c) stream.buffers["xrpusdt"].append(c)
df = stream.get_dataframe("XRPUSDT") df = stream.get_dataframe("XRPUSDT")
assert df is not None assert df is not None
assert len(df) == 50 assert len(df) == _MIN_CANDLES_FOR_SIGNAL
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -62,11 +63,11 @@ async def test_kline_stream_parses_message():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_callback_called_on_closed_candle(): async def test_callback_called_on_closed_candle():
received = [] callback = AsyncMock()
stream = KlineStream( stream = KlineStream(
symbol="XRPUSDT", symbol="XRPUSDT",
interval="1m", interval="1m",
on_candle=lambda c: received.append(c), on_candle=callback,
) )
raw_msg = { raw_msg = {
"k": { "k": {
@@ -79,8 +80,8 @@ async def test_callback_called_on_closed_candle():
"x": True, "x": True,
} }
} }
stream.handle_message(raw_msg) await stream.handle_message(raw_msg)
assert len(received) == 1 assert callback.call_count == 1
@pytest.mark.asyncio @pytest.mark.asyncio

View File

@@ -160,3 +160,51 @@ def test_oi_nan_masking_with_zeros():
feat = _calc_features_vectorized(d, sig) feat = _calc_features_vectorized(d, sig)
assert feat["oi_change"].iloc[50:].notna().any(), "실제 OI 값 구간에 유한값이 있어야 함" assert feat["oi_change"].iloc[50:].notna().any(), "실제 OI 값 구간에 유한값이 있어야 함"
def test_rs_zero_denominator():
"""btc_r1=0일 때 RS가 inf/nan이 아닌 0.0이어야 한다 (np.divide 방식 검증)."""
import numpy as np
import pandas as pd
from src.dataset_builder import _calc_features_vectorized, _calc_signals, _calc_indicators
n = 500
np.random.seed(7)
# XRP close: 약간의 변동
xrp_close = np.cumprod(1 + np.random.randn(n) * 0.001) * 1.0
xrp_df = pd.DataFrame({
"open": xrp_close * 0.999,
"high": xrp_close * 1.005,
"low": xrp_close * 0.995,
"close": xrp_close,
"volume": np.random.rand(n) * 1000 + 500,
})
# BTC close: 완전히 고정 → btc_r1 = 0.0
btc_close = np.ones(n) * 50000.0
btc_df = pd.DataFrame({
"open": btc_close,
"high": btc_close,
"low": btc_close,
"close": btc_close,
"volume": np.random.rand(n) * 1000 + 500,
})
# ETH close: 약간의 변동 (eth_df 없으면 BTC 피처 자체가 계산 안 됨)
eth_close = np.cumprod(1 + np.random.randn(n) * 0.001) * 3000.0
eth_df = pd.DataFrame({
"open": eth_close * 0.999,
"high": eth_close * 1.005,
"low": eth_close * 0.995,
"close": eth_close,
"volume": np.random.rand(n) * 1000 + 500,
})
# _calc_features_vectorized를 직접 호출해 BTC/ETH 피처를 포함한 전체 피처를 검증
d = _calc_indicators(xrp_df)
signal_arr = _calc_signals(d)
feat = _calc_features_vectorized(d, signal_arr, btc_df=btc_df, eth_df=eth_df)
assert "xrp_btc_rs" in feat.columns, "xrp_btc_rs 컬럼이 있어야 함"
assert not feat["xrp_btc_rs"].isin([np.inf, -np.inf]).any(), \
"xrp_btc_rs에 inf가 있으면 안 됨"
assert not feat["xrp_btc_rs"].isna().all(), \
"xrp_btc_rs가 전부 nan이면 안 됨"

View File

@@ -49,9 +49,9 @@ def test_build_features_rs_zero_when_btc_ret_zero():
features = build_features(xrp_df, "LONG", btc_df=btc_df, eth_df=eth_df) features = build_features(xrp_df, "LONG", btc_df=btc_df, eth_df=eth_df)
assert features["xrp_btc_rs"] == 0.0 assert features["xrp_btc_rs"] == 0.0
def test_feature_cols_has_21_items(): def test_feature_cols_has_23_items():
from src.ml_features import FEATURE_COLS from src.ml_features import FEATURE_COLS
assert len(FEATURE_COLS) == 21 assert len(FEATURE_COLS) == 23
def make_df(n=100): def make_df(n=100):

View File

@@ -12,13 +12,19 @@ def make_features(side="LONG") -> pd.Series:
def test_no_model_file_is_not_loaded(tmp_path): def test_no_model_file_is_not_loaded(tmp_path):
f = MLFilter(model_path=str(tmp_path / "nonexistent.pkl")) f = MLFilter(
onnx_path=str(tmp_path / "nonexistent.onnx"),
lgbm_path=str(tmp_path / "nonexistent.pkl"),
)
assert not f.is_model_loaded() assert not f.is_model_loaded()
def test_no_model_should_enter_returns_true(tmp_path): def test_no_model_should_enter_returns_true(tmp_path):
"""모델 없으면 항상 진입 허용 (폴백)""" """모델 없으면 항상 진입 허용 (폴백)"""
f = MLFilter(model_path=str(tmp_path / "nonexistent.pkl")) f = MLFilter(
onnx_path=str(tmp_path / "nonexistent.onnx"),
lgbm_path=str(tmp_path / "nonexistent.pkl"),
)
features = make_features() features = make_features()
assert f.should_enter(features) is True assert f.should_enter(features) is True
@@ -28,7 +34,7 @@ def test_should_enter_above_threshold():
f = MLFilter(threshold=0.60) f = MLFilter(threshold=0.60)
mock_model = MagicMock() mock_model = MagicMock()
mock_model.predict_proba.return_value = np.array([[0.35, 0.65]]) mock_model.predict_proba.return_value = np.array([[0.35, 0.65]])
f._model = mock_model f._lgbm_model = mock_model
features = make_features() features = make_features()
assert f.should_enter(features) is True assert f.should_enter(features) is True
@@ -38,7 +44,7 @@ def test_should_enter_below_threshold():
f = MLFilter(threshold=0.60) f = MLFilter(threshold=0.60)
mock_model = MagicMock() mock_model = MagicMock()
mock_model.predict_proba.return_value = np.array([[0.55, 0.45]]) mock_model.predict_proba.return_value = np.array([[0.55, 0.45]])
f._model = mock_model f._lgbm_model = mock_model
features = make_features() features = make_features()
assert f.should_enter(features) is False assert f.should_enter(features) is False
@@ -48,16 +54,18 @@ def test_reload_model(tmp_path):
import joblib import joblib
# 모델 파일이 없는 상태에서 시작 # 모델 파일이 없는 상태에서 시작
model_path = tmp_path / "lgbm_filter.pkl" f = MLFilter(
f = MLFilter(model_path=str(model_path)) onnx_path=str(tmp_path / "nonexistent.onnx"),
lgbm_path=str(tmp_path / "lgbm_filter.pkl"),
)
assert not f.is_model_loaded() assert not f.is_model_loaded()
# _model을 직접 주입해서 is_model_loaded가 True인지 확인 # _lgbm_model을 직접 주입해서 is_model_loaded가 True인지 확인
mock_model = MagicMock() mock_model = MagicMock()
f._model = mock_model f._lgbm_model = mock_model
assert f.is_model_loaded() assert f.is_model_loaded()
# reload_model 호출 시 파일이 없으면 _try_load가 _model을 변경하지 않음 # reload_model은 항상 _lgbm_model/_onnx_session을 초기화 후 재로드한다.
# (기존 동작 유지 - 파일 없으면 None으로 초기화하지 않음) # 파일 없으면 None으로 리셋되어 폴백 상태가 된다.
f.reload_model() f.reload_model()
assert f.is_model_loaded() # mock_model이 유지됨 assert not f.is_model_loaded() # 파일 없으므로 폴백 상태

View File

@@ -10,23 +10,11 @@ mlx = pytest.importorskip("mlx.core", reason="MLX 미설치")
def _make_X(n: int = 4) -> pd.DataFrame: def _make_X(n: int = 4) -> pd.DataFrame:
from src.ml_features import FEATURE_COLS
rng = np.random.default_rng(0) rng = np.random.default_rng(0)
return pd.DataFrame( return pd.DataFrame(
{ rng.uniform(-1.0, 1.0, (n, len(FEATURE_COLS))).astype(np.float32),
"rsi": rng.uniform(20, 80, n), columns=FEATURE_COLS,
"macd_hist": rng.uniform(-0.1, 0.1, n),
"bb_pct": rng.uniform(0, 1, n),
"ema_align": rng.choice([-1.0, 0.0, 1.0], n),
"stoch_k": rng.uniform(0, 100, n),
"stoch_d": rng.uniform(0, 100, n),
"atr_pct": rng.uniform(0.001, 0.05, n),
"vol_ratio": rng.uniform(0.5, 3.0, n),
"ret_1": rng.uniform(-0.01, 0.01, n),
"ret_3": rng.uniform(-0.02, 0.02, n),
"ret_5": rng.uniform(-0.03, 0.03, n),
"signal_strength": rng.integers(0, 6, n).astype(float),
"side": rng.choice([0.0, 1.0], n),
}
) )
@@ -41,9 +29,10 @@ def test_mlx_gpu_device():
def test_mlx_filter_predict_shape_untrained(): def test_mlx_filter_predict_shape_untrained():
"""학습 전에도 predict_proba가 (N,) 형태를 반환해야 한다.""" """학습 전에도 predict_proba가 (N,) 형태를 반환해야 한다."""
from src.mlx_filter import MLXFilter from src.mlx_filter import MLXFilter
from src.ml_features import FEATURE_COLS
X = _make_X(4) X = _make_X(4)
model = MLXFilter(input_dim=13, hidden_dim=32) model = MLXFilter(input_dim=len(FEATURE_COLS), hidden_dim=32)
proba = model.predict_proba(X) proba = model.predict_proba(X)
assert proba.shape == (4,) assert proba.shape == (4,)
assert np.all((proba >= 0.0) & (proba <= 1.0)) assert np.all((proba >= 0.0) & (proba <= 1.0))
@@ -52,12 +41,13 @@ def test_mlx_filter_predict_shape_untrained():
def test_mlx_filter_fit_and_predict(): def test_mlx_filter_fit_and_predict():
"""학습 후 predict_proba가 유효한 확률값을 반환해야 한다.""" """학습 후 predict_proba가 유효한 확률값을 반환해야 한다."""
from src.mlx_filter import MLXFilter from src.mlx_filter import MLXFilter
from src.ml_features import FEATURE_COLS
n = 100 n = 100
X = _make_X(n) X = _make_X(n)
y = pd.Series(np.random.randint(0, 2, n)) y = pd.Series(np.random.randint(0, 2, n))
model = MLXFilter(input_dim=13, hidden_dim=32, epochs=5, batch_size=32) model = MLXFilter(input_dim=len(FEATURE_COLS), hidden_dim=32, epochs=5, batch_size=32)
model.fit(X, y) model.fit(X, y)
proba = model.predict_proba(X) proba = model.predict_proba(X)
@@ -93,12 +83,13 @@ def test_fit_with_nan_features():
def test_mlx_filter_save_load(tmp_path): def test_mlx_filter_save_load(tmp_path):
"""저장 후 로드한 모델이 동일한 예측값을 반환해야 한다.""" """저장 후 로드한 모델이 동일한 예측값을 반환해야 한다."""
from src.mlx_filter import MLXFilter from src.mlx_filter import MLXFilter
from src.ml_features import FEATURE_COLS
n = 50 n = 50
X = _make_X(n) X = _make_X(n)
y = pd.Series(np.random.randint(0, 2, n)) y = pd.Series(np.random.randint(0, 2, n))
model = MLXFilter(input_dim=13, hidden_dim=32, epochs=3, batch_size=32) model = MLXFilter(input_dim=len(FEATURE_COLS), hidden_dim=32, epochs=3, batch_size=32)
model.fit(X, y) model.fit(X, y)
proba_before = model.predict_proba(X) proba_before = model.predict_proba(X)