ビットコインオートマチックトレーディングシステム開発ガイド

ビットコインオートマチックトレーディングシステム開発ガイド

KissCuseMe
2025-03-03
2

1。開発環境の構成

# Install required libraries
pip install ccxt pandas numpy talib TA-Lib python-dotenv schedule websockets flask
  • メインツール
    • CCXT:100+ Exchange Integration API
    • パンダ:データ分析
    • TA-LIB:技術指標の計算
    • WebSockets:実際のデータの受信
    • フラスコ:ダッシュボードの構築

2. Exchangeを選択して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
  • 推奨される交換
    • バイナンス:高流動性、休憩/WebSocketサポート
    • バイビット:ギフト取引の専門化
    • 明るい:国内補助的な安定性

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レートの交換制限を遵守する必要があります
  • 週末/休日の市場のボラティリティの準備
  • 定期的に戦略的パフォーマンスの評価
  • 実際の資金の前に仮想環境で2週間以上テストしてください
  • 発行および適用される実際のAPIアドレスのみを実行することができます
ビットコイン
自動取引
Python
ガイド

0

目次

  • 1。開発環境の構成
  • 2. Exchangeを選択してAPIを設定します
  • 3。チャートデータの収集
  • 4。取引戦略開発
  • 4-1。 技術指標の実装
  • 4-2。 販売信号の作成ロジック
  • 5。リスク管理システム
  • 6。実行モジュールを注文します
  • 7。バックテストシステム
  • 8。監視およびロギングシステム
  • 9。メイン関数
  • 10。セキュリティ強化措置
  • 10-1。 APIキー管理
  • 10-2
  • 11。配布の例
この投稿は、クパンパートナーズの活動の一環として、一定額の手数料を受け取ります。

利用規約個人情報取扱方針サポート
© 2025
あらかじめ知っていたら良かったでしょう
All rights reserved.