Інтеграція бота з API Coinbase
Coinbase Advanced Trade API (раніше Coinbase Pro) — професійний API для алгоритмічної торгівлі. Відрізняється від Coinbase Simple: підтримує limit/market/stop ордери, WebSocket feed, детальну історію. Ключова особливість — перехід на JWT аутентифікацію у 2024 році.
Аутентифікація через JWT
Coinbase Advanced Trade API використовує JWT (JSON Web Token) з алгоритмом ES256:
import jwt
import time
from cryptography.hazmat.primitives.asymmetric import ec
def generate_jwt(api_key: str, private_key_pem: str) -> str:
"""
api_key: рядок вигляду "organizations/{org_id}/apiKeys/{key_id}"
private_key_pem: EC приватний ключ у PEM форматі
"""
private_key = serialization.load_pem_private_key(
private_key_pem.encode(), password=None
)
payload = {
'sub': api_key,
'iss': 'coinbase-cloud',
'nbf': int(time.time()),
'exp': int(time.time()) + 120, # JWT дійсний 2 хвилини
}
return jwt.encode(payload, private_key, algorithm='ES256',
headers={'kid': api_key, 'nonce': secrets.token_hex(16)})
# Кожен запит вимагає свіжого JWT
async def api_request(method: str, path: str, body: dict = None):
token = generate_jwt(API_KEY, PRIVATE_KEY)
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
async with aiohttp.ClientSession() as session:
async with session.request(method, BASE_URL + path,
headers=headers, json=body) as resp:
return await resp.json()
Базові торговельні операції
# Розміщення ордера
async def place_order(product_id: str, side: str, order_type: str,
size: str, price: str = None) -> dict:
body = {
'client_order_id': str(uuid.uuid4()),
'product_id': product_id, # 'BTC-USD'
'side': side, # 'BUY' або 'SELL'
'order_configuration': {}
}
if order_type == 'market':
if side == 'BUY':
body['order_configuration']['market_market_ioc'] = {'quote_size': size}
else:
body['order_configuration']['market_market_ioc'] = {'base_size': size}
elif order_type == 'limit':
body['order_configuration']['limit_limit_gtc'] = {
'base_size': size,
'limit_price': price,
'post_only': False,
}
return await api_request('POST', '/api/v3/brokerage/orders', body)
# Скасування ордерів
async def cancel_orders(order_ids: list[str]) -> dict:
return await api_request('POST', '/api/v3/brokerage/orders/batch_cancel',
{'order_ids': order_ids})
WebSocket Feed
import websockets
async def subscribe_market_data():
async with websockets.connect('wss://advanced-trade-ws.coinbase.com') as ws:
# Підписка з JWT аутентифікацією
token = generate_jwt(API_KEY, PRIVATE_KEY)
await ws.send(json.dumps({
'type': 'subscribe',
'product_ids': ['BTC-USD', 'ETH-USD'],
'channel': 'ticker',
'jwt': token,
}))
async for message in ws:
data = json.loads(message)
if data['channel'] == 'ticker':
for event in data['events']:
process_ticker(event)
Coinbase також підтримує CCXT для уніфікованого доступу, але прямий API дає більше можливостей (batch cancel, вдосконалені типи ордерів).
Інтеграція з API Coinbase Advanced Trade: 1–2 тижні з урахуванням JWT аутентифікації та тестування на sandbox.







