forked from ccxt/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoinbase.py
More file actions
343 lines (330 loc) · 14.5 KB
/
coinbase.py
File metadata and controls
343 lines (330 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
# -----------------------------------------------------------------------------
try:
basestring # Python 3
except NameError:
basestring = str # Python 2
import json
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import DDoSProtection
class coinbase (Exchange):
def describe(self):
return self.deep_extend(super(coinbase, self).describe(), {
'id': 'coinbase',
'name': 'coinbase',
'countries': ['US'],
'rateLimit': 400, # 10k calls per hour
'version': 'v2',
'userAgent': self.userAgents['chrome'],
'headers': {
'CB-VERSION': '2018-05-30',
},
'has': {
'CORS': True,
'cancelOrder': False,
'createDepositAddress': False,
'createOrder': False,
'deposit': False,
'fetchBalance': True,
'fetchClosedOrders': False,
'fetchCurrencies': True,
'fetchDepositAddress': False,
'fetchMarkets': False,
'fetchMyTrades': False,
'fetchOHLCV': False,
'fetchOpenOrders': False,
'fetchOrder': False,
'fetchOrderBook': False,
'fetchOrders': False,
'fetchTicker': True,
'fetchTickers': False,
'fetchBidsAsks': False,
'fetchTrades': False,
'withdraw': False,
'fetchTransactions': False,
'fetchDeposits': False,
'fetchWithdrawals': False,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/40811661-b6eceae2-653a-11e8-829e-10bfadb078cf.jpg',
'api': 'https://api.coinbase.com',
'www': 'https://www.coinbase.com',
'doc': 'https://developers.coinbase.com/api/v2',
'fees': 'https://support.coinbase.com/customer/portal/articles/2109597-buy-sell-bank-transfer-fees',
'referral': 'https://www.coinbase.com/join/58cbe25a355148797479dbd2',
},
'requiredCredentials': {
'apiKey': True,
'secret': True,
},
'api': {
'public': {
'get': [
'currencies',
'time',
'exchange-rates',
'users/{user_id}',
'prices/{symbol}/buy',
'prices/{symbol}/sell',
'prices/{symbol}/spot',
],
},
'private': {
'get': [
'accounts',
'accounts/{account_id}',
'accounts/{account_id}/addresses',
'accounts/{account_id}/addresses/{address_id}',
'accounts/{account_id}/addresses/{address_id}/transactions',
'accounts/{account_id}/transactions',
'accounts/{account_id}/transactions/{transaction_id}',
'accounts/{account_id}/buys',
'accounts/{account_id}/buys/{buy_id}',
'accounts/{account_id}/sells',
'accounts/{account_id}/sells/{sell_id}',
'accounts/{account_id}/deposits',
'accounts/{account_id}/deposits/{deposit_id}',
'accounts/{account_id}/withdrawals',
'accounts/{account_id}/withdrawals/{withdrawal_id}',
'payment-methods',
'payment-methods/{payment_method_id}',
'user',
'user/auth',
],
'post': [
'accounts',
'accounts/{account_id}/primary',
'accounts/{account_id}/addresses',
'accounts/{account_id}/transactions',
'accounts/{account_id}/transactions/{transaction_id}/complete',
'accounts/{account_id}/transactions/{transaction_id}/resend',
'accounts/{account_id}/buys',
'accounts/{account_id}/buys/{buy_id}/commit',
'accounts/{account_id}/sells',
'accounts/{account_id}/sells/{sell_id}/commit',
'accounts/{account_id}/deposists',
'accounts/{account_id}/deposists/{deposit_id}/commit',
'accounts/{account_id}/withdrawals',
'accounts/{account_id}/withdrawals/{withdrawal_id}/commit',
],
'put': [
'accounts/{account_id}',
'user',
],
'delete': [
'accounts/{id}',
'accounts/{account_id}/transactions/{transaction_id}',
],
},
},
'exceptions': {
'two_factor_required': AuthenticationError, # 402 When sending money over 2fa limit
'param_required': ExchangeError, # 400 Missing parameter
'validation_error': ExchangeError, # 400 Unable to validate POST/PUT
'invalid_request': ExchangeError, # 400 Invalid request
'personal_details_required': AuthenticationError, # 400 User’s personal detail required to complete self request
'identity_verification_required': AuthenticationError, # 400 Identity verification is required to complete self request
'jumio_verification_required': AuthenticationError, # 400 Document verification is required to complete self request
'jumio_face_match_verification_required': AuthenticationError, # 400 Document verification including face match is required to complete self request
'unverified_email': AuthenticationError, # 400 User has not verified their email
'authentication_error': AuthenticationError, # 401 Invalid auth(generic)
'invalid_token': AuthenticationError, # 401 Invalid Oauth token
'revoked_token': AuthenticationError, # 401 Revoked Oauth token
'expired_token': AuthenticationError, # 401 Expired Oauth token
'invalid_scope': AuthenticationError, # 403 User hasn’t authenticated necessary scope
'not_found': ExchangeError, # 404 Resource not found
'rate_limit_exceeded': DDoSProtection, # 429 Rate limit exceeded
'internal_server_error': ExchangeError, # 500 Internal server error
},
'markets': {
'BTC/USD': {'id': 'btc-usd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'LTC/USD': {'id': 'ltc-usd', 'symbol': 'LTC/USD', 'base': 'LTC', 'quote': 'USD'},
'ETH/USD': {'id': 'eth-usd', 'symbol': 'ETH/USD', 'base': 'ETH', 'quote': 'USD'},
'BCH/USD': {'id': 'bch-usd', 'symbol': 'BCH/USD', 'base': 'BCH', 'quote': 'USD'},
},
'options': {
'accounts': [
'wallet',
'fiat',
# 'vault',
],
},
})
async def fetch_time(self):
response = await self.publicGetTime()
data = response['data']
return self.parse8601(data['iso'])
async def fetch_currencies(self, params={}):
response = await self.publicGetCurrencies(params)
currencies = response['data']
result = {}
for c in range(0, len(currencies)):
currency = currencies[c]
id = currency['id']
name = currency['name']
code = self.common_currency_code(id)
minimum = self.safe_float(currency, 'min_size')
result[code] = {
'id': id,
'code': code,
'info': currency, # the original payload
'name': name,
'active': True,
'fee': None,
'precision': None,
'limits': {
'amount': {
'min': minimum,
'max': None,
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': None,
'max': None,
},
'withdraw': {
'min': None,
'max': None,
},
},
}
return result
async def fetch_ticker(self, symbol, params={}):
await self.load_markets()
timestamp = self.seconds()
market = self.market(symbol)
request = self.extend({
'symbol': market['id'],
}, params)
buy = await self.publicGetPricesSymbolBuy(request)
sell = await self.publicGetPricesSymbolSell(request)
spot = await self.publicGetPricesSymbolSpot(request)
ask = self.safe_float(buy['data'], 'amount')
bid = self.safe_float(sell['data'], 'amount')
last = self.safe_float(spot['data'], 'amount')
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'bid': bid,
'ask': ask,
'last': last,
'high': None,
'low': None,
'bidVolume': None,
'askVolume': None,
'vwap': None,
'open': None,
'close': None,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': None,
'info': {
'buy': buy,
'sell': sell,
'spot': spot,
},
}
async def fetch_balance(self, params={}):
response = await self.privateGetAccounts()
balances = response['data']
accounts = self.safe_value(params, 'type', self.options['accounts'])
result = {'info': response}
for b in range(0, len(balances)):
balance = balances[b]
if self.in_array(balance['type'], accounts):
currencyId = balance['balance']['currency']
code = currencyId
if currencyId in self.currencies_by_id:
code = self.currencies_by_id[currencyId]['code']
total = self.safe_float(balance['balance'], 'amount')
free = total
used = None
if code in result:
result[code]['free'] += total
result[code]['total'] += total
else:
account = {
'free': free,
'used': used,
'total': total,
}
result[code] = account
return self.parse_balance(result)
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
request = '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if method == 'GET':
if query:
request += '?' + self.urlencode(query)
url = self.urls['api'] + '/' + self.version + request
if api == 'private':
self.check_required_credentials()
nonce = str(self.nonce())
payload = ''
if method != 'GET':
if query:
body = self.json(query)
payload = body
what = nonce + method + '/' + self.version + request + payload
signature = self.hmac(self.encode(what), self.encode(self.secret))
headers = {
'CB-ACCESS-KEY': self.apiKey,
'CB-ACCESS-SIGN': signature,
'CB-ACCESS-TIMESTAMP': nonce,
'Content-Type': 'application/json',
}
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def handle_errors(self, code, reason, url, method, headers, body):
if not isinstance(body, basestring):
return # fallback to default error handler
if len(body) < 2:
return # fallback to default error handler
if (body[0] == '{') or (body[0] == '['):
response = json.loads(body)
feedback = self.id + ' ' + body
#
# {"error": "invalid_request", "error_description": "The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed."}
#
# or
#
# {
# "errors": [
# {
# "id": "not_found",
# "message": "Not found"
# }
# ]
# }
#
exceptions = self.exceptions
errorCode = self.safe_string(response, 'error')
if errorCode is not None:
if errorCode in exceptions:
raise exceptions[errorCode](feedback)
else:
raise ExchangeError(feedback)
errors = self.safe_value(response, 'errors')
if errors is not None:
if isinstance(errors, list):
numErrors = len(errors)
if numErrors > 0:
errorCode = self.safe_string(errors[0], 'id')
if errorCode is not None:
if errorCode in exceptions:
raise exceptions[errorCode](feedback)
else:
raise ExchangeError(feedback)
data = self.safe_value(response, 'data')
if data is None:
raise ExchangeError(self.id + ' failed due to a malformed response ' + self.json(response))