Python + Deriv API: Cara Membuat Trading Bot Pertama Anda
📌 Yang akan Anda pelajari
- Python + Deriv API memungkinkan trading bot powerful tanpa Blockly
- Library python-deriv-api (open source, official)
- WebSocket connection untuk real-time ticks
- Buy contracts programmatically (Rise/Fall, Higher/Lower, Digits)
- Build bot RSI lengkap dengan stop loss dalam ~50 lines kode
Daftar Isi
Mengapa Python > DBot?
Python memberikan flexibilitas yang DBot tidak bisa:
Deriv DBot (Blockly)
- ✓ Visual, mudah pemula
- ✓ Tidak butuh coding skill
- ✗ Limited logic complexity
- ✗ Tidak ada multi-asset
- ✗ Browser-dependent
- ✗ Sulit version control
Python + Deriv API
- ✓ Unlimited complexity
- ✓ Multi-asset, multi-strategy
- ✓ Server-side execution (24/7)
- ✓ Integrate dengan ML libraries
- ✓ Proper logging dan monitoring
- ✗ Butuh Python basics
Untuk strategi yang melibatkan multiple indicators, machine learning, atau external data, Python adalah satu-satunya pilihan.
Setup environment Python
Requirements:
- Python 3.8+ (recommended 3.10 atau 3.11)
- pip (package manager)
- Code editor (VSCode recommended)
Install library:
pip install python-deriv-api websocketsLibrary yang di-install:
- python-deriv-api: Wrapper official Deriv WebSocket API
- websockets: Dependency untuk async WebSocket
Optional (untuk RSI dan technical analysis):
pip install numpy pandas ta-lib- numpy: Math operations
- pandas: Data manipulation
- ta-lib: Technical indicators (RSI, MACD, dll)
Get API token Deriv
Login ke Deriv.com
Pastikan akun Anda already verified.
Buka API Token settings
Account Settings → Security and Safety → API Token. Atau langsung ke app.deriv.com/account/api-token
Create new token
Nama: “Trading Bot” (atau apapun).
Permissions yang dibutuhkan:
- Read – view account info
- Trade – buy/sell contracts
- Payments – jika perlu deposit/withdraw via API
Save token
Copy token (32 karakter). Simpan secure! Jangan share dengan siapapun, jangan commit ke Git.
⚠️ Security warning
API token = full access ke akun trading. Jika leaked, attacker dapat menjual semua position dan withdraw funds. Best practices:
- Gunakan
.envfile untuk store token - Tambahkan
.envke.gitignore - Rotate token setiap 6 bulan
- Buat token terpisah untuk demo vs real account
Connect ke Deriv API
Code dasar untuk connection:
import asyncio
from deriv_api import DerivAPI
APP_ID = 1089 # Replace dengan App ID Anda
API_TOKEN = "your_api_token" # Dari Deriv API settings
async def connect_to_deriv():
"""Connect ke Deriv API."""
api = DerivAPI(app_id=APP_ID)
# Authorize dengan token
authorize = await api.authorize(API_TOKEN)
print(f"✓ Authorized: {authorize['authorize']['loginid']}")
# Get balance
balance = await api.balance()
print(f"Balance: {balance['balance']['balance']} {balance['balance']['currency']}")
return api
# Run
loop = asyncio.get_event_loop()
api = loop.run_until_complete(connect_to_deriv())Yang terjadi:
- DerivAPI(): Create instance dengan App ID (1089 = generic)
- authorize(): Auth dengan API token
- balance(): Get current balance
Jika berhasil, output:
✓ Authorized: CR1234567 Balance: 10000.00 USD
Stream tick data real-time
Untuk strategi yang react ke price changes, butuh tick stream:
async def stream_ticks(api, symbol="R_75"):
"""Stream ticks real-time untuk symbol."""
print(f"Streaming ticks untuk {symbol}...")
# Subscribe ke ticks
source = await api.subscribe({
'ticks': symbol,
'subscribe': 1
})
async for tick in source:
if 'tick' in tick:
print(f"Tick: {tick['tick']['quote']} at {tick['tick']['epoch']}")
# Run
await stream_ticks(api, "R_75") # Volatility 75 IndexSymbol yang available di Deriv:
- R_10, R_25, R_50, R_75, R_100: Volatility Indices
- BOOM300N, BOOM500, BOOM1000: Boom Indices
- CRASH300N, CRASH500, CRASH1000: Crash Indices
- frxEURUSD, frxGBPUSD: Forex pairs (real)
- 1HZ10V, 1HZ25V: 1-second Volatility Indices
Buy contract programmatically
Workflow buy contract: Proposal → Buy → Result:
async def buy_rise_fall(api, symbol="R_75", duration=5, stake=1.0, direction="CALL"):
"""Buy Rise (CALL) atau Fall (PUT) contract."""
# Get price proposal first
proposal = await api.proposal({
'amount': stake,
'basis': 'stake',
'contract_type': direction, # CALL = Rise, PUT = Fall
'currency': 'USD',
'duration': duration,
'duration_unit': 't', # ticks
'symbol': symbol
})
if 'proposal' not in proposal:
print(f"Error: {proposal}")
return None
# Buy contract
buy = await api.buy({
'buy': proposal['proposal']['id'],
'price': stake
})
contract_id = buy['buy']['contract_id']
print(f"✓ Contract bought: {contract_id}, Buy price: ${stake}")
return contract_id
# Buy Rise dengan $1, 5 ticks
contract_id = await buy_rise_fall(api, "R_75", 5, 1.0, "CALL")Contract types:
- CALL: Rise – price ends higher
- PUT: Fall – price ends lower
- HIGHER: Higher than specific barrier
- LOWER: Lower than specific barrier
- DIGITDIFF: Last digit different from prediction
- DIGITMATCH: Last digit matches prediction
Duration units:
- t: ticks (1-10)
- s: seconds (15-86400)
- m: minutes
- h: hours
- d: days
Build RSI bot lengkap
Implementasi RSI bot lengkap dengan stop loss:
import numpy as np
from deriv_api import DerivAPI
import asyncio
class RSIBot:
def __init__(self, api, symbol="R_75", rsi_period=14, rsi_oversold=30):
self.api = api
self.symbol = symbol
self.rsi_period = rsi_period
self.rsi_oversold = rsi_oversold
self.prices = []
self.stake = 1.0
self.max_loss = 20.0 # Stop at $20 loss
self.total_pnl = 0.0
def calculate_rsi(self, prices, period=14):
"""Calculate RSI dari list of prices."""
if len(prices) < period + 1:
return None
deltas = np.diff(prices)
gains = np.where(deltas > 0, deltas, 0)
losses = np.where(deltas < 0, -deltas, 0)
avg_gain = np.mean(gains[-period:])
avg_loss = np.mean(losses[-period:])
if avg_loss == 0:
return 100
rs = avg_gain / avg_loss
return 100 - (100 / (1 + rs))
async def run(self):
"""Main bot loop."""
# Subscribe ke ticks
source = await self.api.subscribe({
'ticks': self.symbol,
'subscribe': 1
})
async for tick_data in source:
if 'tick' not in tick_data:
continue
price = float(tick_data['tick']['quote'])
self.prices.append(price)
# Keep only last 100 prices (memory management)
if len(self.prices) > 100:
self.prices = self.prices[-100:]
rsi = self.calculate_rsi(self.prices, self.rsi_period)
if rsi is None:
continue
print(f"Price: {price:.5f}, RSI: {rsi:.2f}")
# Trade jika RSI oversold
if rsi < self.rsi_oversold:
print(f"🟢 RSI oversold ({rsi:.2f}) - Buy Rise!")
contract_id = await self.buy_rise()
# Wait untuk contract selesai
result = await self.check_result(contract_id)
self.total_pnl += result
print(f"P/L: ${result:.2f}, Total: ${self.total_pnl:.2f}")
# Stop jika loss limit hit
if self.total_pnl <= -self.max_loss:
print("⛔ Max loss reached. Stopping bot.")
break
async def buy_rise(self):
"""Buy CALL (Rise) contract."""
proposal = await self.api.proposal({
'amount': self.stake,
'basis': 'stake',
'contract_type': 'CALL',
'currency': 'USD',
'duration': 5,
'duration_unit': 't',
'symbol': self.symbol
})
buy = await self.api.buy({
'buy': proposal['proposal']['id'],
'price': self.stake
})
return buy['buy']['contract_id']
async def check_result(self, contract_id):
"""Wait dan get hasil contract."""
result = await self.api.proposal_open_contract({
'contract_id': contract_id,
'subscribe': 1
})
# Logic untuk wait sampai selesai...
# Simplified - dalam production butuh proper async handling
return result.get('profit', 0)
# Run bot
async def main():
api = await connect_to_deriv()
bot = RSIBot(api)
await bot.run()
asyncio.run(main())Logic bot:
- Subscribe ke ticks Volatility 75
- Collect prices, calculate RSI(14)
- Jika RSI < 30, buy Rise contract
- Track total P/L
- Stop jika max loss ($20) tercapai
💡 Improvements untuk production
- Add proper error handling (network disconnects)
- Implement reconnection logic
- Save trade history ke database
- Add multiple entry conditions (RSI + MACD)
- Implement adaptive position sizing
- Add telegram notification untuk signals
Deployment ke VPS
Bot harus run 24/7 untuk meaningful results. Pilihan deployment:
Option 1: VPS (Recommended)
- DigitalOcean: $4-6/bulan untuk basic droplet
- AWS Lightsail: $3.50/bulan untuk smallest instance
- Contabo: $4-5/bulan dengan specs lebih baik
Setup:
# Update system
sudo apt update && sudo apt upgrade -y
# Install Python
sudo apt install python3 python3-pip -y
# Clone your bot repo
git clone https://github.com/yourusername/deriv-bot.git
cd deriv-bot
# Install dependencies
pip3 install -r requirements.txt
# Run dengan nohup (background)
nohup python3 bot.py > bot.log 2>&1 &
# Atau gunakan systemd untuk auto-restart
sudo systemctl enable deriv-bot.serviceOption 2: GitHub Actions (untuk light bots)
Gratis untuk repo public. Scheduled workflows dapat run setiap 5 menit, tetapi tidak untuk real-time trading.
Option 3: Local computer + uptime
OK untuk testing, tetapi tidak reliable untuk live trading (internet outage, power failure).
FAQ
$5 minimum deposit Deriv. Untuk meaningful testing, $50-$100 recommended. Bot dengan stake $1 dapat run dengan $10 modal.
Ya, gratis. Hanya butuh akun Deriv dan API token. Tidak ada subscription fee untuk API access.
Ya, untuk forex MT5 yang ditawarkan Deriv. Tetapi akses langsung lebih limited daripada synthetic indices. Untuk forex serius, gunakan MetaTrader EA atau cTrader Python.
Mulai dengan basics Python (1-2 minggu). FreeCodeCamp atau Codecademy gratis. Setelah comfortable, balik ke tutorial Deriv API ini.
