10.2 - API Kullanımı ve Bot Geliştirme
🤖 API Kullanımı ve Bot Geliştirme
Bu Modülde Neler Öğreneceksiniz?
Exchange API kullanımı, trading bot geliştirme, Python ile otomasyon, risk yönetimi ve deployment stratejilerini öğreneceksiniz.
Trading botları, 24/7 piyasayı izler ve önceden tanımlanmış kurallara göre otomatik işlem yapar. Duygusuz, hızlı ve tutarlıdır.
🔑 Exchange API Temelleri
API Key Oluşturma
- Binance/Bybit → API Management
- Create API Key
- Permissions: Read + Trade (NO Withdraw!)
- IP Whitelist: Güvenlik için ekle
- API Key + Secret Key kaydet
⚠️ Güvenlik
- Asla Paylaşma: API key gizli
- Withdraw Kapalı: Sadece trade yetkisi
- IP Whitelist: Sadece senin IP
- 2FA: Mutlaka aktif
- Test Net: Önce test ortamında dene
🐍 Python ile Trading Bot Geliştirme
import time
import pandas as pd
# Binance bağlantısı
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET_KEY',
'enableRateLimit': True
})
def get_ma(symbol, timeframe, period):
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=period)
closes = [x[4] for x in ohlcv]
return sum(closes) / len(closes)
def check_position(symbol):
balance = exchange.fetch_balance()
return balance['total'].get(symbol.split('/')[0], 0)
symbol = 'BTC/USDT'
amount = 0.001 # 0.001 BTC
while True:
try:
fast_ma = get_ma(symbol, '1h', 9)
slow_ma = get_ma(symbol, '1h', 21)
position = check_position(symbol)
if fast_ma > slow_ma and position == 0:
print("BUY Signal")
exchange.create_market_buy_order(symbol, amount)
elif fast_ma < slow_ma and position > 0:
print("SELL Signal")
exchange.create_market_sell_order(symbol, amount)
time.sleep(3600) # 1 saat bekle
except Exception as e:
print(f"Error: {e}")
time.sleep(60)
def __init__(self, symbol, grid_size, grid_levels):
self.symbol = symbol
self.grid_size = grid_size # $100
self.grid_levels = grid_levels # 10
self.orders = []
def create_grid(self, base_price):
# Alış emirleri (aşağı)
for i in range(1, self.grid_levels + 1):
buy_price = base_price - (i * self.grid_size)
order = exchange.create_limit_buy_order(
self.symbol, 0.01, buy_price
)
self.orders.append(order)
# Satış emirleri (yukarı)
for i in range(1, self.grid_levels + 1):
sell_price = base_price + (i * self.grid_size)
order = exchange.create_limit_sell_order(
self.symbol, 0.01, sell_price
)
self.orders.append(order)
# Kullanım
bot = GridBot('BTC/USDT', 100, 10)
current_price = exchange.fetch_ticker('BTC/USDT')['last']
bot.create_grid(current_price)
"""
Position sizing hesaplama
"""
risk_amount = balance * (risk_percent / 100)
price_diff = abs(entry - stop_loss)
position_size = risk_amount / price_diff
return position_size
def place_order_with_sl(symbol, side, entry, stop_loss, risk=2):
"""
Stop loss ile emir
"""
balance = exchange.fetch_balance()['USDT']['free']
size = calculate_position_size(balance, risk, entry, stop_loss)
# Ana emir
if side == 'buy':
order = exchange.create_market_buy_order(symbol, size)
else:
order = exchange.create_market_sell_order(symbol, size)
# Stop loss
sl_order = exchange.create_stop_loss_order(
symbol, 'sell', size, stop_loss
)
return order, sl_order
# Örnek kullanım
entry = 50000
stop_loss = 49000 # 2% altı
place_order_with_sl('BTC/USDT', 'buy', entry, stop_loss, risk=2)
🤖 Bot Türleri
1️⃣ Grid Trading Bot
Fiyat aralığında otomatik al-sat
2️⃣ DCA Bot
Düzenli aralıklarla al (Dollar Cost Average)
3️⃣ Arbitrage Bot
Borsalar arası fiyat farkı
4️⃣ Market Making Bot
Likidite sağla, spread kazan
⚙️ Bot Deployment & Monitoring
Cloud Hosting Seçenekleri
- AWS EC2: Scalable, güvenilir ($5-50/ay)
- DigitalOcean: Basit, ucuz ($5/ay)
- Heroku: Kolay deployment (Free tier)
- VPS (Contabo): Tam kontrol ($4/ay)
- Raspberry Pi: Evde hosting (tek seferlik $50)
Deployment Adımları
- VPS satın al (DigitalOcean öneriyoruz)
- SSH ile bağlan
- Python + dependencies kur
- Bot kodunu yükle (git clone)
- Screen/tmux ile arka planda çalıştır
- Cron job ile otomatik restart
Monitoring & Logging
# Log ayarları
logging.basicConfig(
filename='bot.log',
level=logging.INFO,
format='%(asctime)s - %(message)s'
)
# Her işlemi logla
logging.info(f"BUY: {symbol} @ {price}")
logging.error(f"Error: {e}")
# Telegram bildirim
import requests
def send_telegram(msg):
bot_token = 'YOUR_BOT_TOKEN'
chat_id = 'YOUR_CHAT_ID'
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
requests.post(url, data={'chat_id': chat_id, 'text': msg})
Performance Tracking
- Günlük P/L raporu
- Win rate hesaplama
- Drawdown takibi
- Telegram/Discord alerts
📚 Popüler Bot Kütüphaneleri
CCXT
100+ exchange desteği
Unified API
En popüler kütüphane
Freqtrade
Hazır bot framework
Backtesting dahil
Open source
Jesse
Modern framework
Live + backtest
Python 3.9+
🎓 Bilgi Testi (5 Soru)
Soru 1/5
API Key oluştururken hangi yetki VERİLMEMELİ?
Önemli Hatırlatmalar
- Güvenlik: API key gizli, withdraw kapalı
- Test: Önce test net, sonra küçük sermaye
- Monitoring: 24/7 izle, log tut
- Risk: Bot da hata yapar, stop loss şart
- Bakım: Düzenli güncelleme ve optimizasyon