Binance APIでPython仮想通貨自動売買ボットを作る【完全ガイド】
取引所APIPython自動売買Bitcoin
前提条件
- Python 3.10以上
- Binanceアカウント(APIキー発行済み)
- 基本的なPythonの知識
環境構築
pip install python-binance pandas ta
APIキーの設定
from binance.client import Client
api_key = "YOUR_API_KEY"
api_secret = "YOUR_API_SECRET"
client = Client(api_key, api_secret)
# 残高確認
balance = client.get_asset_balance(asset="BTC")
print(f"BTC残高: {balance['free']}")
基本的な売買注文
# 成行買い注文
order = client.order_market_buy(
symbol="BTCUSDT",
quoteOrderQty=100 # 100 USDT分のBTCを購入
)
# 指値売り注文
order = client.order_limit_sell(
symbol="BTCUSDT",
quantity=0.001,
price="70000"
)
簡単な移動平均クロス戦略
import pandas as pd
from ta.trend import SMAIndicator
def get_signal(symbol, short_window=20, long_window=50):
klines = client.get_klines(symbol=symbol, interval="1h", limit=100)
df = pd.DataFrame(klines, columns=["time", "open", "high", "low", "close", ...])
df["close"] = df["close"].astype(float)
sma_short = SMAIndicator(df["close"], window=short_window).sma_indicator()
sma_long = SMAIndicator(df["close"], window=long_window).sma_indicator()
if sma_short.iloc[-1] > sma_long.iloc[-1] and sma_short.iloc[-2] <= sma_long.iloc[-2]:
return "BUY"
elif sma_short.iloc[-1] < sma_long.iloc[-1] and sma_short.iloc[-2] >= sma_long.iloc[-2]:
return "SELL"
return "HOLD"
次のステップ
- WebSocketでリアルタイムデータを受信する
- リスク管理(ストップロス・ポジションサイジング)を追加
- バックテストフレームワーク(Backtrader)と組み合わせる