-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
bitso.py
493 lines (467 loc) · 19.1 KB
/
bitso.py
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# -*- 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.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 OrderNotFound
from ccxt.base.errors import InvalidNonce
class bitso (Exchange):
def describe(self):
return self.deep_extend(super(bitso, self).describe(), {
'id': 'bitso',
'name': 'Bitso',
'countries': 'MX', # Mexico
'rateLimit': 2000, # 30 requests per minute
'version': 'v3',
'has': {
'CORS': True,
'fetchMyTrades': True,
'fetchOpenOrders': True,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766335-715ce7aa-5ed5-11e7-88a8-173a27bb30fe.jpg',
'api': 'https://api.bitso.com',
'www': 'https://bitso.com',
'doc': 'https://bitso.com/api_info',
'fees': 'https://bitso.com/fees?l=es',
},
'api': {
'public': {
'get': [
'available_books',
'ticker',
'order_book',
'trades',
],
},
'private': {
'get': [
'account_status',
'balance',
'fees',
'fundings',
'fundings/{fid}',
'funding_destination',
'kyc_documents',
'ledger',
'ledger/trades',
'ledger/fees',
'ledger/fundings',
'ledger/withdrawals',
'mx_bank_codes',
'open_orders',
'order_trades/{oid}',
'orders/{oid}',
'user_trades',
'user_trades/{tid}',
'withdrawals/',
'withdrawals/{wid}',
],
'post': [
'bitcoin_withdrawal',
'debit_card_withdrawal',
'ether_withdrawal',
'ripple_withdrawal',
'bcash_withdrawal',
'litecoin_withdrawal',
'orders',
'phone_number',
'phone_verification',
'phone_withdrawal',
'spei_withdrawal',
'ripple_withdrawal',
'bcash_withdrawal',
'litecoin_withdrawal',
],
'delete': [
'orders/{oid}',
'orders/all',
],
},
},
'exceptions': {
'0201': AuthenticationError, # Invalid Nonce or Invalid Credentials
'104': InvalidNonce, # Cannot perform request - nonce must be higher than 1520307203724237
},
})
def fetch_markets(self):
markets = self.publicGetAvailableBooks()
result = []
for i in range(0, len(markets['payload'])):
market = markets['payload'][i]
id = market['book']
symbol = id.upper().replace('_', '/')
base, quote = symbol.split('/')
limits = {
'amount': {
'min': self.safe_float(market, 'minimum_amount'),
'max': self.safe_float(market, 'maximum_amount'),
},
'price': {
'min': self.safe_float(market, 'minimum_price'),
'max': self.safe_float(market, 'maximum_price'),
},
'cost': {
'min': self.safe_float(market, 'minimum_value'),
'max': self.safe_float(market, 'maximum_value'),
},
}
precision = {
'amount': self.precision_from_string(market['minimum_amount']),
'price': self.precision_from_string(market['minimum_price']),
}
lot = limits['amount']['min']
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
'lot': lot,
'limits': limits,
'precision': precision,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetBalance()
balances = response['payload']['balances']
result = {'info': response}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency'].upper()
account = {
'free': float(balance['available']),
'used': float(balance['locked']),
'total': float(balance['total']),
}
result[currency] = account
return self.parse_balance(result)
def fetch_order_book(self, symbol, limit=None, params={}):
self.load_markets()
response = self.publicGetOrderBook(self.extend({
'book': self.market_id(symbol),
}, params))
orderbook = response['payload']
timestamp = self.parse8601(orderbook['updated_at'])
return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'amount')
def fetch_ticker(self, symbol, params={}):
self.load_markets()
response = self.publicGetTicker(self.extend({
'book': self.market_id(symbol),
}, params))
ticker = response['payload']
timestamp = self.parse8601(ticker['created_at'])
vwap = self.safe_float(ticker, 'vwap')
baseVolume = self.safe_float(ticker, 'volume')
quoteVolume = baseVolume * vwap
last = self.safe_float(ticker, 'last')
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_float(ticker, 'high'),
'low': self.safe_float(ticker, 'low'),
'bid': self.safe_float(ticker, 'bid'),
'bidVolume': None,
'ask': self.safe_float(ticker, 'ask'),
'askVolume': None,
'vwap': vwap,
'open': None,
'close': last,
'last': last,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}
def parse_trade(self, trade, market=None):
timestamp = self.parse8601(trade['created_at'])
symbol = None
if market is None:
marketId = self.safe_string(trade, 'book')
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
if market is not None:
symbol = market['symbol']
side = self.safe_string(trade, 'side')
if side is None:
side = self.safe_string(trade, 'maker_side')
amount = self.safe_float(trade, 'amount')
if amount is None:
amount = self.safe_float(trade, 'major')
if amount is not None:
amount = abs(amount)
fee = None
feeCost = self.safe_float(trade, 'fees_amount')
if feeCost is not None:
feeCurrency = self.safe_string(trade, 'fees_currency')
if feeCurrency is not None:
if feeCurrency in self.currencies_by_id:
feeCurrency = self.currencies_by_id[feeCurrency]['code']
fee = {
'cost': feeCost,
'currency': feeCurrency,
}
cost = self.safe_float(trade, 'minor')
if cost is not None:
cost = abs(cost)
price = self.safe_float(trade, 'price')
orderId = self.safe_string(trade, 'oid')
return {
'id': str(trade['tid']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'order': orderId,
'type': None,
'side': side,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
}
def fetch_trades(self, symbol, since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTrades(self.extend({
'book': market['id'],
}, params))
return self.parse_trades(response['payload'], market, since, limit)
def fetch_my_trades(self, symbol=None, since=None, limit=25, params={}):
self.load_markets()
market = self.market(symbol)
# the don't support fetching trades starting from a date yet
# use the `marker` extra param for that
# self is not a typo, the variable name is 'marker'(don't confuse with 'market')
markerInParams = ('marker' in list(params.keys()))
# warn the user with an exception if the user wants to filter
# starting from since timestamp, but does not set the trade id with an extra 'marker' param
if (since is not None) and not markerInParams:
raise ExchangeError(self.id + ' fetchMyTrades does not support fetching trades starting from a timestamp with the `since` argument, use the `marker` extra param to filter starting from an integer trade id')
# convert it to an integer unconditionally
if markerInParams:
params = self.extend(params, {
'marker': int(params['marker']),
})
request = {
'book': market['id'],
'limit': limit, # default = 25, max = 100
# 'sort': 'desc', # default = desc
# 'marker': id, # integer id to start from
}
response = self.privateGetUserTrades(self.extend(request, params))
return self.parse_trades(response['payload'], market, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'book': self.market_id(symbol),
'side': side,
'type': type,
'major': self.amount_to_precision(symbol, amount),
}
if type == 'limit':
order['price'] = self.price_to_precision(symbol, price)
response = self.privatePostOrders(self.extend(order, params))
return {
'info': response,
'id': response['payload']['oid'],
}
def cancel_order(self, id, symbol=None, params={}):
self.load_markets()
return self.privateDeleteOrdersOid({'oid': id})
def parse_order_status(self, status):
statuses = {
'partial-fill': 'open', # self is a common substitution in ccxt
'completed': 'closed',
}
if status in statuses:
return statuses[status]
return status
def parse_order(self, order, market=None):
side = order['side']
status = self.parse_order_status(order['status'])
symbol = None
if market is None:
marketId = order['book']
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
if market:
symbol = market['symbol']
orderType = order['type']
timestamp = self.parse8601(order['created_at'])
amount = self.safe_float(order, 'original_amount')
remaining = self.safe_float(order, 'unfilled_amount')
filled = amount - remaining
result = {
'info': order,
'id': order['oid'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'symbol': symbol,
'type': orderType,
'side': side,
'price': self.safe_float(order, 'price'),
'amount': amount,
'cost': None,
'remaining': remaining,
'filled': filled,
'status': status,
'fee': None,
}
return result
def fetch_open_orders(self, symbol=None, since=None, limit=25, params={}):
self.load_markets()
market = self.market(symbol)
# the don't support fetching trades starting from a date yet
# use the `marker` extra param for that
# self is not a typo, the variable name is 'marker'(don't confuse with 'market')
markerInParams = ('marker' in list(params.keys()))
# warn the user with an exception if the user wants to filter
# starting from since timestamp, but does not set the trade id with an extra 'marker' param
if (since is not None) and not markerInParams:
raise ExchangeError(self.id + ' fetchOpenOrders does not support fetching orders starting from a timestamp with the `since` argument, use the `marker` extra param to filter starting from an integer trade id')
# convert it to an integer unconditionally
if markerInParams:
params = self.extend(params, {
'marker': int(params['marker']),
})
request = {
'book': market['id'],
'limit': limit, # default = 25, max = 100
# 'sort': 'desc', # default = desc
# 'marker': id, # integer id to start from
}
response = self.privateGetOpenOrders(self.extend(request, params))
orders = self.parse_orders(response['payload'], market, since, limit)
return orders
def fetch_order(self, id, symbol=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.privateGetOrdersOid({
'oid': id,
})
numOrders = len(response['payload'])
if not isinstance(response['payload'], list) or (numOrders != 1):
raise OrderNotFound(self.id + ': The order ' + id + ' not found.')
return self.parse_order(response['payload'][0], market)
def fetch_order_trades(self, id, symbol=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.privateGetOrderTradesOid({
'oid': id,
})
return self.parse_trades(response['payload'], market)
def fetch_deposit_address(self, code, params={}):
self.load_markets()
currency = self.currency(code)
request = {
'fund_currency': currency['id'],
}
response = self.privateGetFundingDestination(self.extend(request, params))
address = self.safe_string(response['payload'], 'account_identifier')
tag = None
if code == 'XRP':
parts = address.split('?dt=', 2)
address = parts[0]
tag = parts[1]
self.check_address(address)
return {
'currency': code,
'address': address,
'tag': tag,
'status': 'ok',
'info': response,
}
def withdraw(self, code, amount, address, tag=None, params={}):
self.check_address(address)
self.load_markets()
methods = {
'BTC': 'Bitcoin',
'ETH': 'Ether',
'XRP': 'Ripple',
'BCH': 'Bcash',
'LTC': 'Litecoin',
}
method = methods[code] if (code in list(methods.keys())) else None
if method is None:
raise ExchangeError(self.id + ' not valid withdraw coin: ' + code)
request = {
'amount': amount,
'address': address,
'destination_tag': tag,
}
classMethod = 'privatePost' + method + 'Withdrawal'
response = getattr(self, classMethod)(self.extend(request, params))
return {
'info': response,
'id': self.safe_string(response['payload'], 'wid'),
}
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
endpoint = '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if method == 'GET':
if query:
endpoint += '?' + self.urlencode(query)
url = self.urls['api'] + endpoint
if api == 'private':
self.check_required_credentials()
nonce = str(self.nonce())
request = ''.join([nonce, method, endpoint])
if method != 'GET':
if query:
body = self.json(query)
request += body
signature = self.hmac(self.encode(request), self.encode(self.secret))
auth = self.apiKey + ':' + nonce + ':' + signature
headers = {
'Authorization': 'Bitso ' + auth,
'Content-Type': 'application/json',
}
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def handle_errors(self, httpCode, 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)
if 'success' in response:
#
# {"success":false,"error":{"code":104,"message":"Cannot perform request - nonce must be higher than 1520307203724237"}}
#
success = self.safe_value(response, 'success', False)
if isinstance(success, basestring):
if (success == 'true') or (success == '1'):
success = True
else:
success = False
if not success:
feedback = self.id + ' ' + self.json(response)
error = self.safe_value(response, 'error')
if error is None:
raise ExchangeError(feedback)
code = self.safe_string(error, 'code')
exceptions = self.exceptions
if code in exceptions:
raise exceptions[code](feedback)
else:
raise ExchangeError(feedback)
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
response = self.fetch2(path, api, method, params, headers, body)
if 'success' in response:
if response['success']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))