AI 기반 바이낸스 코인 자동 트레이딩 봇 구조 프로젝트

이 포스트에서는 Python과 AI 모델(LLama 3.1)을 활용하여 바이낸스 선물 자동매매 시스템을 설계한 전체 구조를 소개합니다. 이 봇은 실시간 가격, 계정 정보, 기술적 지표, AI 분석, 그리고 포지션 전략까지 통합하여 트레이딩을 자동화하며, 데이터는 Mysql 을 통해 관리됩니다.


📌 목차

  1. 사용 기술 및 라이브러리 구성

  2. 환경변수 관리 (.env)

  3. 데이터베이스 구조 및 초기화

  4. 트레이드 기록 및 계정 히스토리 함수

  5. 성과 분석 및 통계 계산

  6. 기술적 지표 분석 로직

  7. AI 모델 연동 및 응답 파싱

  8. 메인 트레이딩 루프


1. 사용 기술 및 라이브러리 구성

  • ccxt: 바이낸스 선물 API 연동 (포지션/가격/잔고 관리)

  • mysql: 데이터 저장 (트레이드 및 계정 이력) 

  • pandas, numpy: 시계열 데이터 및 기술적 지표 계산

  • requests: 외부 AI 모델 및 뉴스 API 통신

  • dotenv: API 키 및 민감 정보 환경변수로 관리


2. 환경변수 관리 (.env)

.env 파일에 민감한 키 정보를 관리합니다:

  • BINANCE_API_KEY, BINANCE_SECRET_KEY

  • AI_API_URL, AI_API_KEY (예: 로컬 Llama3.1 WebUI 엔드포인트)


3. 데이터베이스 구조 및 초기화

초기 실행 시 아래 테이블을 생성합니다:

  • trades: 거래 상태 기록 (open/closed, 가격, 수량 등)

  • trade_results: 개별 거래의 성과 기록

  • account_history: 계정 잔액 히스토리


4. 트레이드 기록 및 계정 히스토리 함수

  • save_trade(): 포지션 진입 정보 기록

  • close_trade(): 포지션 종료 및 수익 계산

  • update_account_history(): 주기적 잔액 저장

  • get_active_trade_info(): 현재 오픈된 거래 정보 조회

  • get_last_open_trade_id(): 최근 트레이드 ID 반환


5. 성과 분석 및 통계 계산

  • get_recent_trade_history(n=20): 최근 N건 거래 내역

  • get_trading_performance_stats()

    • 전체 승률, 평균 손익, 누적 PnL, MDD 등

  • 추가 분석:

    • 시간대별 승률 (ex. 오전 vs 오후)

    • 변동성 별 승률 (low vs high volatility)


6. 기술적 지표 분석 로직

적용 지표:
  • MA / EMA: 이동 평균선

  • MACD: 모멘텀 및 추세

  • RSI: 과매수/과매도 판단

  • ATR: 평균 진폭

추세 판단 로직:

  • analyze_ma_crossovers(): MA 골든크로스, 데드크로스 감지

  • get_trend_status_string(): 결과를 자연어로 요약


7. AI 모델 연동 및 응답 파싱

  • LLaMA 3.1 WebUI 포맷으로 POST 요청

  • 응답 예측 로그 기록: inspect_api_response()

  • 파싱 로직:

    • parse_ai_response()를 통해 "long (75%)" 등 방향성과 확률 추출


8. 메인 트레이딩 루프

  • 현재 가격, 계정 잔고, 포지션 여부 확인

  • 보유 중일 경우:

    • 손절(SL) / 익절(TP) 조건 충족 시 → close_trade()

  • 포지션 없을 경우:

    • 미체결 주문 취소

    • 시장 요약 + 지표 분석 + 뉴스 → AI 요청

    • 응답 기반으로 매수/매도 결정 후 save_trade()

💡 추가:

  • 매 10분마다 update_account_history() 실행


8. 코드 공유

  • https://github.com/dslee1371/autotrade-binance


9. 대시보드 만들기 (코드공유)

  • https://github.com/dslee1371/autotrade-binance-dash/tree/main


11. 1일 경과

  • 손실이 계속 발생하고 있어서, 보완이 필요한 상황 입니다.








실행 결과 예시


=== 1시간봉 이동평균선 분석 ===
MA5: $115695.84 (falling), MA20: $117795.91 (falling), MA50: $118087.96, MA100: $118246.41
Price vs MAs: MA5=below, MA20=below, MA50=below, MA100=below
Trend Analysis: Short-term=bearish, Medium-term=bearish, Long-term=bearish

=== 4시간봉 이동평균선 분석 ===
MA5: $117384.96 (falling), MA20: $118289.12 (falling), MA50: $118269.06, MA100: $117202.77
Price vs MAs: MA5=below, MA20=below, MA50=below, MA100=below
Trend Analysis: Short-term=bearish, Medium-term=bearish, Long-term=bearish
Fetching latest breaking news from Investing.com API...
Retrieved 10 latest news headlines

===== 최신 암호화폐 뉴스 =====
1. Volkswagen lowers guidance after taking $1.5-billion tariff hit in H1
   출처: Investing.com (2025-07-25 06:50:50)
2. Remy Cointreau reports rise in first-quarter sales, raises guidance
   출처: Investing.com (2025-07-25 06:50:35)
3. Puma shares dive after warning of full year loss
   출처: Investing.com (2025-07-25 06:35:32)
4. Australia stocks lower at close of trade; S&P/ASX 200 down 0.49%
   출처: Investing.com (2025-07-25 06:35:03)
5. Asian stocks slip, dollar gains as markets brace for crucial week
   출처: Investing.com (2025-07-25 06:26:24)
6. Intel shares drop almost 6% on disappointing guidance, job cuts
   출처: Investing.com (2025-07-25 06:20:53)
7. Close Brothers to sell Winterflood Securities to Marex for £103.9 million
   출처: Investing.com (2025-07-25 06:20:31)
8. Taiwan stocks higher at close of trade; Taiwan Weighted up 1.44%
   출처: Investing.com (2025-07-25 06:00:03)
9. Sanofi's Sarclisa receives EU approval for newly diagnosed multiple myeloma
   출처: Investing.com (2025-07-25 05:54:47)
10. Meko reports Q2 revenue drop, launches cost reduction program
   출처: Investing.com (2025-07-25 05:47:10)
=======================

API Response structure: ['id', 'created', 'model', 'choices', 'object', 'usage']
AI Analysis: after analyzing the provided market data, i have identified some key insights that will inform my trading decision.

**short-term trends:**

* the 15m ma lines are all below the current price, indicating a downward trend.
* the rsi (38.91) is slightly above the oversold region (30), suggesting some buying pressure.
* macd and signal lines are both negative, with a significant gap between them, indicating a strong bearish momentum.

**medium-term trends:**

* 1h ma lines are also below the current price, reinforcing the downward trend observed in the short term.
* the rsi is still above the oversold region (30), but not as high as in the short term.

**latest news and market volatility:**

* there are no specific news headlines that would suggest a significant bullish or bearish sentiment shift in bitcoin prices.
* market volatility remains relatively low at 0.40%.

**past trading performance:**

* the recent 10 trades have shown an equal split between wins and losses, with a win percentage of 50.00%.
* long trades have performed slightly better than short trades.

**timeframe-specific performance:**

* in the 4-8 hour timeframe, trades were successful 50% of the time.
* there is no significant difference in performance across different volatility ranges.

considering these insights, i conclude that the current trend is bearish, with a slight leaning towards selling. however, given the relatively low market volatility and the recent trading performance showing equal success rates for both long and short trades, my confidence level is moderate.

**direction: short**
**probability: 0.67**

please note that this is not investment advice, but rather a professional analysis based on historical data and technical indicators.
AI Analysis: after analyzing the provided market data, i have identified some key insights that will inform my trading decision.

**short-term trends:**

* the 15m ma lines are all below the current price, indicating a downward trend.
* the rsi (38.91) is slightly above the oversold region (30), suggesting some buying pressure.
* macd and signal lines are both negative, with a significant gap between them, indicating a strong bearish momentum.

**medium-term trends:**

* 1h ma lines are also below the current price, reinforcing the downward trend observed in the short term.
* the rsi is still above the oversold region (30), but not as high as in the short term.

**latest news and market volatility:**

* there are no specific news headlines that would suggest a significant bullish or bearish sentiment shift in bitcoin prices.
* market volatility remains relatively low at 0.40%.

**past trading performance:**

* the recent 10 trades have shown an equal split between wins and losses, with a win percentage of 50.00%.
* long trades have performed slightly better than short trades.

**timeframe-specific performance:**

* in the 4-8 hour timeframe, trades were successful 50% of the time.
* there is no significant difference in performance across different volatility ranges.

considering these insights, i conclude that the current trend is bearish, with a slight leaning towards selling. however, given the relatively low market volatility and the recent trading performance showing equal success rates for both long and short trades, my confidence level is moderate.

**direction: short**
**probability: 0.67**

please note that this is not investment advice, but rather a professional analysis based on historical data and technical indicators.
Raw AI response to parse: after analyzing the provided market data, i have identified some key insights that will inform my trading decision.

**short-term trends:**

* the 15m ma lines are all below the current price, indicating a downward trend.
* the rsi (38.91) is slightly above the oversold region (30), suggesting some buying pressure.
* macd and signal lines are both negative, with a significant gap between them, indicating a strong bearish momentum.

**medium-term trends:**

* 1h ma lines are also below the current price, reinforcing the downward trend observed in the short term.
* the rsi is still above the oversold region (30), but not as high as in the short term.

**latest news and market volatility:**

* there are no specific news headlines that would suggest a significant bullish or bearish sentiment shift in bitcoin prices.
* market volatility remains relatively low at 0.40%.

**past trading performance:**

* the recent 10 trades have shown an equal split between wins and losses, with a win percentage of 50.00%.
* long trades have performed slightly better than short trades.

**timeframe-specific performance:**

* in the 4-8 hour timeframe, trades were successful 50% of the time.
* there is no significant difference in performance across different volatility ranges.

considering these insights, i conclude that the current trend is bearish, with a slight leaning towards selling. however, given the relatively low market volatility and the recent trading performance showing equal success rates for both long and short trades, my confidence level is moderate.

**direction: short**
**probability: 0.67**

please note that this is not investment advice, but rather a professional analysis based on historical data and technical indicators.
Parsed decision: SHORT with 67.00% confidence
Trading Signal: SHORT with 67.00% confidence
Kelly Criterion Fraction: 0.1000 (10.00%)
Setting leverage to 4x
Order Amount: 0.002 BTC ($200.00 USDT)
Trade saved with ID: 15

=== SHORT Position Opened ===
Entry: $115,269.70
Stop Loss: $115,846.05 (+0.5%)
Take Profit: $114,693.35 (-0.5%)
Position Size: 0.002 BTC ($200.00 USDT)
Leverage: 4x
Kelly Fraction: 10.00%
Win Probability: 67.00%
Trade ID: 15
============================


댓글

이 블로그의 인기 게시물

10.15 부동산 대책, 오피스텔도 LTV 40%인가요? 혼선 정리

Kubernetes Pod Pending 해결법: FailedScheduling 원인별 실전 점검 가이드

애플 비전 프로 새 밴드 착용감 어떨까? Dual Knit Band 착용 경험 리뷰