비트코인 자동매매 시스템 개발 가이드

비트코인 자동매매 시스템 개발 가이드

KissCuseMe
2025-03-03
91

1. 개발 환경 구성

# Install required libraries
pip install ccxt pandas numpy talib TA-Lib python-dotenv schedule websockets flask
  • 주요 도구:
    • CCXT: 100+ 거래소 통합 API
    • Pandas: 데이터 분석
    • TA-Lib: 기술적 지표 계산
    • Websockets: 실시간 데이터 수신
    • Flask: 대시보드 구축

2. 거래소 선택 및 API 설정

# Save API key in .env file
API_KEY = "your_api_key" # API key issued by exchange
API_SECRET = "your_api_secret" # API secret issued by exchange
  • 추천 거래소:
    • Binance: 높은 유동성, REST/Websocket 지원
    • Bybit: 선물 거래 특화
    • 업비트: 국내 법인 안정성

3. 차트 데이터 수집

import ccxt

# Initialize Binance API
binance = ccxt.binance({
    'apiKey': API_KEY,  # Set API key
    'secret': API_SECRET,  # Set API secret
    'enableRateLimit': True  # Enable API request limit
})

# Receive real-time OHLCV data (Websocket)
async def fetch_btc_data():
    async with websockets.connect('wss://fstream.binance.com/ws/btcusdt@kline_1m') as ws:
        while True:
            data = await ws.recv()  # Receive real-time data
            print(json.loads(data))  # Print data

4. 트레이딩 전략 개발

4-1. 기술적 지표 구현

import talib

# Function to calculate technical indicators
def calculate_indicators(df):
    # Calculate 20-day Simple Moving Average (SMA)
    df['MA20'] = talib.SMA(df['close'], timeperiod=20)
    # Calculate 14-day Relative Strength Index (RSI)
    df['RSI'] = talib.RSI(df['close'], timeperiod=14)
    # Calculate MACD (Moving Average Convergence Divergence)
    df['MACD'], _, _ = talib.MACD(df['close'])
    return df

4-2. 매매 신호 생성 로직

# Function to generate trading signals
def generate_signal(df):
    latest = df.iloc[-1]  # Get the latest data
    
    # Dual SMA Strategy
    if latest['MA20'] > latest['MA50'] and df['MA20'].iloc[-2] <= df['MA50'].iloc[-2]:
        return 'BUY'  # Buy signal
    elif latest['MA20'] < latest['MA50'] and df['MA20'].iloc[-2] >= df['MA50'].iloc[-2]:
        return 'SELL'  # Sell signal
    else:
        return 'HOLD'  # Hold signal

5. 리스크 관리 시스템

# Function to calculate position size
def calculate_position_size(balance, risk_per_trade=0.02):
    # Calculate position size based on total capital and risk percentage per trade
    return balance * risk_per_trade

# Function to set stop loss
def set_stop_loss(entry_price, atr, multiplier=1.5):
    # Calculate stop loss based on ATR (Average True Range)
    return entry_price - (atr * multiplier)

6. 주문 실행 모듈

# Function to execute an order
def execute_order(side, amount, symbol='BTC/USDT'):
    try:
        if side == 'BUY':
            # Execute a market buy order
            order = binance.create_market_buy_order(symbol, amount)
        elif side == 'SELL':
            # Execute a market sell order
            order = binance.create_market_sell_order(symbol, amount)
        print(f"Order Executed: {order}")  # Print order execution log
        return order
    except Exception as e:
        print(f"Order Failed: {e}")  # Print error message if the order fails
        return None

7. 백테스팅 시스템

# Backtesting function
def backtest_strategy(df, initial_balance=10000):
    balance = initial_balance  # Set initial capital
    position = 0  # Initialize position
    
    for i in range(1, len(df)):
        signal = df['signal'].iloc[i]  # Get trading signal
        price = df['close'].iloc[i]  # Get closing price
        
        if signal == 'BUY' and position == 0:
            # Set position when a buy signal is received
            position = balance / price
            balance = 0
        elif signal == 'SELL' and position > 0:
            # Liquidate position when a sell signal is received
            balance = position * price
            position = 0
            
    return balance  # Return final balance

8. 모니터링 & 로깅 시스템

import logging

# Logging settings
logging.basicConfig(filename='trading.log', level=logging.INFO)

# Transaction logging function
def log_transaction(order):
    logging.info(f"""
    [Transaction Details]
    Time: {datetime.now()}
    Type: {order['side']}
    Amount: {order['amount']}
    Price: {order['price']}
    Status: {order['status']}
    """)

9. 메인 함수

# Main execution loop
def main():
    while True:
        try:
            df = fetch_realtime_data()  # Fetch real-time data
            df = calculate_indicators(df)  # Calculate technical indicators
            signal = generate_signal(df)  # Generate trading signal
            
            if signal != 'HOLD':
                # Execute an order if there is a trading signal
                amount = calculate_position_size(get_balance())
                execute_order(signal, amount)
                
            time.sleep(60)  # Run at 1-minute intervals
        except KeyboardInterrupt:
            break  # Exit the loop when interrupted by the user

10. 보안 강화 조치

10-1. API 키 관리

  • 버전 관리 시스템에 절대 커밋하지 마세요
  • AWS Secrets Manager 또는 Hashicorp Vault를 사용하세요.

10-2.트래픽 암호화

binance = ccxt.binance({
    'options': {'adjustForTimeDifference': True},  # Time difference correction
    'proxies': {'https': 'http://10.10.1.10:3128'}  # Proxy settings
})

11. 배포 예시

# System service registration (Linux)
[Unit]
Description=Crypto Trading Bot
After=network.target

[Service]
ExecStart=/usr/bin/python3 /path/to/bot.py
Restart=always

[Install]
WantedBy=multi-user.target

📌 핵심 주의사항

  • 초기 자본의 1% 미만으로 리스크 제한
  • 거래소 API Rate Limit 반드시 준수
  • 주말/공휴일 시장 변동성 대비
  • 주기적으로 전략 성능 재평가
  • 실제 자금 투입 전 반드시 가상 환경에서 2주 이상 테스트
  • 실제 API 주소를 발급 받아 적용해야 실행 가능
비트코인
자동매매
파이썬
가이드

0

목차

  • 1. 개발 환경 구성
  • 2. 거래소 선택 및 API 설정
  • 3. 차트 데이터 수집
  • 4. 트레이딩 전략 개발
  • 4-1. 기술적 지표 구현
  • 4-2. 매매 신호 생성 로직
  • 5. 리스크 관리 시스템
  • 6. 주문 실행 모듈
  • 7. 백테스팅 시스템
  • 8. 모니터링 & 로깅 시스템
  • 9. 메인 함수
  • 10. 보안 강화 조치
  • 10-1. API 키 관리
  • 10-2.트래픽 암호화
  • 11. 배포 예시
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

이용약관개인정보 처리방침문의
© 2025
미리 알았다면 좋았을 텐데
All rights reserved.