-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy path__init__.py
More file actions
475 lines (373 loc) · 16.3 KB
/
__init__.py
File metadata and controls
475 lines (373 loc) · 16.3 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
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
"""
Coinbase Python Client Library
AUTHOR
George Sibble
Github: sibblegp
LICENSE (The MIT License)
Copyright (c) 2013 George Sibble "gsibble@gmail.com"
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
__author__ = 'gsibble'
from oauth2client.client import AccessTokenRefreshError, OAuth2Credentials, AccessTokenCredentialsError
import requests
import httplib2
import json
import os
import inspect
#TODO: Switch to decimals from floats
#from decimal import Decimal
from coinbase.config import COINBASE_ENDPOINT
from coinbase.models import CoinbaseAmount, CoinbaseTransaction, CoinbaseUser, CoinbaseTransfer, CoinbaseError
class CoinbaseAccount(object):
"""
Primary object for interacting with a Coinbase account
You may either use oauth credentials or a classic API key
"""
def __init__(self,
oauth2_credentials=None,
api_key=None,
oauth_access_token=None):
"""
:param oauth2_credentials: JSON representation of Coinbase oauth2 credentials
:param api_key: Coinbase API key
"""
#Set up our requests session
self.session = requests.session()
#Set our Content-Type
self.session.headers.update({'content-type': 'application/json'})
if oauth2_credentials:
#CA Cert Path
ca_directory = os.path.abspath(__file__).split('/')[0:-1]
ca_path = '/'.join(ca_directory) + '/ca_certs.txt'
#Set CA certificates (breaks without them)
self.http = httplib2.Http(ca_certs=ca_path)
#Create our credentials from the JSON sent
self.oauth2_credentials = OAuth2Credentials.from_json(oauth2_credentials)
#Check our token
self.token_expired = False
try:
self._check_oauth_expired()
except AccessTokenCredentialsError:
self.token_expired = True
#Apply our oAuth credentials to the session
self.oauth2_credentials.apply(headers=self.session.headers)
#Set our request parameters to be empty
self.global_request_params = {}
elif api_key:
if isinstance(api_key, basestring):
#Set our API Key
self.api_key = api_key
#Set our global_request_params
self.global_request_params = {'api_key':api_key}
else:
print "Your api_key must be a string"
elif oauth_access_token:
if isinstance(oauth_access_token, basestring):
self.oauth_access_token = oauth_access_token
self.global_request_params = {'access_token': oauth_access_token}
else:
print "Oauth access token must be a string"
else:
print "You must pass either an api_key, oauth_credentials, or oauth_access_token."
def _check_oauth_expired(self):
"""
Internal function to check if the oauth2 credentials are expired
"""
#Check if they are expired
if self.oauth2_credentials.access_token_expired == True:
#Print an notification message if they are
print 'oAuth2 Token Expired'
#Raise the appropriate error
raise AccessTokenCredentialsError
def refresh_oauth(self):
"""
Refresh our oauth2 token
:return: JSON representation of oauth token
:raise: AccessTokenRefreshError if there was an error refreshing the token
"""
#See if we can refresh the token
try:
#Ask to refresh the token
self.oauth2_credentials.refresh(http=self.http)
#We were successful
#print 'Your token was refreshed with the following response...'
#Return the token for storage
return self.oauth2_credentials
#If the refresh token was invalid
except AccessTokenRefreshError:
#Print a warning
print 'Your refresh token is invalid'
#Raise the appropriate error
raise AccessTokenRefreshError
def _prepare_request(self):
"""
Prepare our request in various ways
"""
#Check if the oauth token is expired and refresh it if necessary
self._check_oauth_expired()
@property
def balance(self):
"""
Retrieve coinbase's account balance
:return: CoinbaseAmount (float) with currency attribute
"""
url = COINBASE_ENDPOINT + '/account/balance'
response = self.session.get(url, params=self.global_request_params)
results = response.json()
return CoinbaseAmount(results['amount'], results['currency'])
@property
def receive_address(self):
"""
Get the account's current receive address
:return: String address of account
"""
url = COINBASE_ENDPOINT + '/account/receive_address'
response = self.session.get(url, params=self.global_request_params)
return response.json()['address']
@property
def contacts(self):
"""
Get the account's contacts
:return: List of contacts in the account
"""
url = COINBASE_ENDPOINT + '/contacts'
response = self.session.get(url, params=self.global_request_params)
return [contact['contact'] for contact in response.json()['contacts']]
def buy_price(self, qty=1):
"""
Return the buy price of BitCoin in USD
:param qty: Quantity of BitCoin to price
:return: CoinbaseAmount (float) with currency attribute
"""
url = COINBASE_ENDPOINT + '/prices/buy'
params = {'qty': qty}
params.update(self.global_request_params)
response = self.session.get(url, params=params)
results = response.json()
return CoinbaseAmount(results['amount'], results['currency'])
def sell_price(self, qty=1):
"""
Return the sell price of BitCoin in USD
:param qty: Quantity of BitCoin to price
:return: CoinbaseAmount (float) with currency attribute
"""
url = COINBASE_ENDPOINT + '/prices/sell'
params = {'qty': qty}
params.update(self.global_request_params)
response = self.session.get(url, params=params)
results = response.json()
return CoinbaseAmount(results['amount'], results['currency'])
# @property
# def user(self):
# url = COINBASE_ENDPOINT + '/account/receive_address'
# response = self.session.get(url)
# return response.json()
def buy_btc(self, qty, pricevaries=False):
"""
Buy BitCoin from Coinbase for USD
:param qty: BitCoin quantity to be bought
:param pricevaries: Boolean value that indicates whether or not the transaction should
be processed if Coinbase cannot gaurentee the current price.
:return: CoinbaseTransfer with all transfer details on success or
CoinbaseError with the error list received from Coinbase on failure
"""
url = COINBASE_ENDPOINT + '/buys'
request_data = {
"qty": qty,
"agree_btc_amount_varies": pricevaries
}
response = self.session.post(url=url, data=json.dumps(request_data), params=self.global_request_params)
response_parsed = response.json()
if response_parsed['success'] == False:
return CoinbaseError(response_parsed['errors'])
return CoinbaseTransfer(response_parsed['transfer'])
def sell_btc(self, qty):
"""
Sell BitCoin to Coinbase for USD
:param qty: BitCoin quantity to be sold
:return: CoinbaseTransfer with all transfer details on success or
CoinbaseError with the error list received from Coinbase on failure
"""
url = COINBASE_ENDPOINT + '/sells'
request_data = {
"qty": qty,
}
response = self.session.post(url=url, data=json.dumps(request_data), params=self.global_request_params)
response_parsed = response.json()
if response_parsed['success'] == False:
return CoinbaseError(response_parsed['errors'])
return CoinbaseTransfer(response_parsed['transfer'])
def request(self, from_email, amount, notes='', currency='BTC'):
"""
Request BitCoin from an email address to be delivered to this account
:param from_email: Email from which to request BTC
:param amount: Amount to request in assigned currency
:param notes: Notes to include with the request
:param currency: Currency of the request
:return: CoinbaseTransaction with status and details
"""
url = COINBASE_ENDPOINT + '/transactions/request_money'
if currency == 'BTC':
request_data = {
"transaction": {
"from": from_email,
"amount": amount,
"notes": notes
}
}
else:
request_data = {
"transaction": {
"from": from_email,
"amount_string": str(amount),
"amount_currency_iso": currency,
"notes": notes
}
}
response = self.session.post(url=url, data=json.dumps(request_data), params=self.global_request_params)
response_parsed = response.json()
if response_parsed['success'] == False:
pass
#DO ERROR HANDLING and raise something
return CoinbaseTransaction(response_parsed['transaction'])
def send(self, to_address, amount, notes='', currency='BTC', transaction_params=dict()):
"""
Send BitCoin from this account to either an email address or a BTC address
:param to_address: Email or BTC address to where coin should be sent
:param amount: Amount of currency to send
:param notes: Notes to be included with transaction
:param currency: Currency to send
:return: CoinbaseTransaction with status and details
"""
url = COINBASE_ENDPOINT + '/transactions/send_money'
if currency == 'BTC':
request_data = {
"transaction": {
"to": to_address,
"amount": amount,
"notes": notes
}
}
else:
request_data = {
"transaction": {
"to": to_address,
"amount_string": str(amount),
"amount_currency_iso": currency,
"notes": notes
}
}
request_data['transaction'].update(transaction_params)
response = self.session.post(url=url, data=json.dumps(request_data), params=self.global_request_params)
response_parsed = response.json()
if response_parsed['success'] == False:
raise RuntimeError('Transaction Failed: %s' % response_parsed.get('errors', 'no errors returned'))
return CoinbaseTransaction(response_parsed['transaction'])
def transactions(self, count=30):
"""
Retrieve the list of transactions for the current account
:param count: How many transactions to retrieve
:return: List of CoinbaseTransaction objects
"""
url = COINBASE_ENDPOINT + '/transactions'
pages = count / 30 + 1
transactions = []
reached_final_page = False
for page in xrange(1, pages + 1):
if not reached_final_page:
params = {'page': page}
params.update(self.global_request_params)
response = self.session.get(url=url, params=params)
parsed_transactions = response.json()
if parsed_transactions['num_pages'] == page:
reached_final_page = True
for transaction in parsed_transactions['transactions']:
transactions.append(CoinbaseTransaction(transaction['transaction']))
return transactions
def transfers(self, count=30):
"""
Retrieve the list of transfers for the current account
:param count: How many transfers to retrieve
:return: List of CoinbaseTransfer objects
"""
url = COINBASE_ENDPOINT + '/transfers'
pages = count / 30 + 1
transfers = []
reached_final_page = False
for page in xrange(1, pages + 1):
if not reached_final_page:
params = {'page': page}
params.update(self.global_request_params)
response = self.session.get(url=url, params=params)
parsed_transfers = response.json()
if parsed_transfers['num_pages'] == page:
reached_final_page = True
for transfer in parsed_transfers['transfers']:
transfers.append(CoinbaseTransfer(transfer['transfer']))
return transfers
def get_transaction(self, transaction_id):
"""
Retrieve a transaction's details
:param transaction_id: Unique transaction identifier
:return: CoinbaseTransaction object with transaction details
"""
url = COINBASE_ENDPOINT + '/transactions/' + str(transaction_id)
response = self.session.get(url, params=self.global_request_params)
results = response.json()
if results.get('success', True) == False:
pass
#TODO: Add error handling
return CoinbaseTransaction(results['transaction'])
def get_user_details(self):
"""
Retrieve the current user's details
:return: CoinbaseUser object with user details
"""
url = COINBASE_ENDPOINT + '/users'
response = self.session.get(url, params=self.global_request_params)
results = response.json()
user_details = results['users'][0]['user']
#Convert our balance and limits to proper amounts
balance = CoinbaseAmount(user_details['balance']['amount'], user_details['balance']['currency'])
buy_limit = CoinbaseAmount(user_details['buy_limit']['amount'], user_details['buy_limit']['currency'])
sell_limit = CoinbaseAmount(user_details['sell_limit']['amount'], user_details['sell_limit']['currency'])
user = CoinbaseUser(user_id=user_details['id'],
name=user_details['name'],
email=user_details['email'],
time_zone=user_details['time_zone'],
native_currency=user_details['native_currency'],
balance=balance,
buy_level=user_details['buy_level'],
sell_level=user_details['sell_level'],
buy_limit=buy_limit,
sell_limit=sell_limit)
return user
def generate_receive_address(self, callback_url=None):
"""
Generate a new receive address
:param callback_url: The URL to receive instant payment notifications
:return: The new string address
"""
url = COINBASE_ENDPOINT + '/account/generate_receive_address'
request_data = {
"address": {
"callback_url": callback_url
}
}
response = self.session.post(url=url, data=json.dumps(request_data), params=self.global_request_params)
return response.json()['address']