def get_coinbase_stats(access_token): """ Get historical investment data across all accounts. """ client = OAuthClient(access_token, access_token) user = client.get_current_user() # TODO(joshblum): Handle wallet pagination. accounts = client.get_accounts() jobs = [] for account in accounts.data: if account.type != 'wallet': # TODO(joshblum): Look into other account types. continue jobs.append(gevent.spawn(_fetch_stats, client, account)) gevent.joinall(jobs) # TODO(joshblum): Handle users with multiple wallets. stats = {} for job in jobs: currency, investment_data = job.value stats[currency] = investment_data native_currency = user.native_currency return { 'stats': stats, 'native_currency': native_currency, 'native_currency_symbol': CURRENCY_MAP.get(native_currency, '$'), }
def priceupdate(): a=OAuthClient("7676d0b819a701688eef2f52652e8cbcf2107e440c9c11113ae811f38dfac1ed","5d2eec22fd3bc63edd19758a448b14975c0832ab8ca0ac6a1be2c6676c28ec3e") spot_price(btc=(float(a.get_buy_price(currency_pair="BTC-USD").amount)), eth=(float(a.get_buy_price(currency_pair="ETH-USD").amount)), bch=(float(a.get_buy_price(currency_pair="BCH-USD").amount)), ltc=(float(a.get_buy_price(currency_pair="LTC-USD").amount)), etc=(float(a.get_buy_price(currency_pair="ETC-USD").amount)), ).save()
def print_price(client: OAuthClient, base: str, currency: str) -> None: currency_pair = '{}-{}'.format(base, currency) print(f'Price for {currency_pair}:') print('Buy price:', client.get_buy_price(currency_pair=currency_pair).amount) print('Sell price:', client.get_sell_price(currency_pair=currency_pair).amount) print('Spot price:', client.get_spot_price(currency_pair=currency_pair).amount)
def update_token(client: OAuthClient) -> None: client.refresh() with open('tokens.json', 'w') as f: json.dump( { 'access_token': client.access_token, 'refresh_token': client.refresh_token, }, f, indent=2)
def _get_user_and_accounts(access_token, cache_date): """ We cache API calls for the Coinbase `User` object and account data, refreshing it once per day. We pass in `cache_date` which has the current date, forcing an API call if the date changes (and eventually evicting expired dates). """ client = OAuthClient(access_token, access_token) user = client.get_current_user() accounts = paginate_response(client, 'get_accounts', **{'limit': '100'}) return (user, accounts)
def get_oauth_client(access_token, refresh_token, user=None): oauth_client = OAuthClient(access_token, refresh_token, base_api_uri=COINBASE_BASE_API_URL) new_credentials = oauth_client.refresh() if user: defaults = { 'token': new_credentials['access_token'], 'token_secret': new_credentials['refresh_token'], # 'expires_at': response['expires_in'] # Coinbase returns an interval here } BTCWallet.objects.update_or_create( user=user, provider=BTC_WALLET_PROVIDER_COINBASE, defaults=defaults ) return oauth_client
def get_oauth_client(access_token, refresh_token, user=None): oauth_client = OAuthClient(access_token, refresh_token, base_api_uri=COINBASE_BASE_API_URL) new_credentials = oauth_client.refresh() if user: defaults = { 'token': new_credentials['access_token'], 'token_secret': new_credentials['refresh_token'], # 'expires_at': response['expires_in'] # Coinbase returns an interval here } BTCWallet.objects.update_or_create( user=user, provider=BTC_WALLET_PROVIDER_COINBASE, defaults=defaults) return oauth_client
def get_coinbase_stats(access_token, currency, period): """ Get historical investment data across all accounts. """ client = OAuthClient(access_token, access_token) cache_date = datetime.datetime.date(datetime.datetime.now()) user, accounts = _get_user_and_accounts(access_token, cache_date) # TODO(joshblum): Look into other account types. accounts = filter(lambda account: account.type == 'wallet', accounts) if currency == 'total': stats_data = _get_total_data(client, accounts) else: accounts = filter( lambda account: account.currency.code.lower() == currency, accounts) stats_data = _get_stats_data_for_period(client, accounts, period) return { 'stats': { currency: stats_data }, 'native_currency': user.native_currency, 'native_currency_symbol': CURRENCY_MAP.get(user.native_currency, '$'), }
def main() -> None: tokens = load_tokens() client = OAuthClient(*tokens) print_price(client, 'BTC', 'USD') print_accounts(client) print_currencies(client)
def test_refresh(self): # Requests to the default BASE_API_URI will noticeably fail by raising an # AssertionError. Requests to the new URL will respond HTTP 200. new_api_base = 'http://example.com/' # If any error is raised by the server, the test suite will never exit when # using Python 3. This strange technique is used to raise the errors # outside of the mocked server environment. errors_in_server = [] server_response_data = { 'access_token': 'newaccesstoken', 'refresh_token': 'newrefreshtoken', } def server_response(request, uri, headers): parsed_uri = urlparse(uri) parsed_reference = urlparse(new_api_base) try: self.assertEqual(parsed_uri.scheme, parsed_reference.scheme) self.assertEqual(parsed_uri.netloc, parsed_reference.netloc) self.assertEqual(parsed_uri.path, parsed_reference.path) except AssertionError as e: errors_in_server.append(e) return (200, headers, json.dumps(server_response_data)) hp.register_uri(hp.POST, OAuthClient.BASE_API_URI + 'oauth/token', body=server_response) hp.register_uri(hp.POST, new_api_base + 'oauth/token', body=server_response) client = OAuthClient(access_token, refresh_token) with self.assertRaises(AssertionError): client.refresh() if errors_in_server: raise errors_in_server.pop() client2 = OAuthClient( access_token, refresh_token, base_api_uri=new_api_base) self.assertEqual(client2.refresh(), server_response_data) # If the response does not include both an access token and refresh token, # an exception will be raised. server_response_data = {'access_token': 'someaccesstoken'} with self.assertRaises(APIError): client2.refresh() server_response_data = {'refresh_token': 'somerefreshtoken'} with self.assertRaises(APIError): client2.refresh()
def forcoin(request): ClientId = "77d5af4941ffd6d5f0c9149e2e303a1c28d9f44c09b63694d6f2f608c60947c0" Clientsecret = "4395c36b93aa972ab4c6da2278cdca48f93e8551d0b13ee502552e249db90eb4" code = request.GET.get('code', '') r2 = requests.post("https://api.coinbase.com/oauth/token", data={ "grant_type": "authorization_code", "code": code, "client_id": ClientId, "client_secret": Clientsecret, "redirect_uri": "http://127.0.0.1:8000/Ali/forcoin/" }) r3 = r2.json() a = OAuthClient(r3['access_token'], r3['refresh_token']) b = a.get_spot_price().amount c = a.get_historic_prices(currency_pair='BTC-USD', period='day')['prices'] user = a.get_current_user().name useremail = a.get_current_user().email access = a.refresh()['access_token'] refresh = a.refresh()['refresh_token'] price = [] price2 = [] time = [] dif1 = [] for i in range(1, 21): price.append(float(c[i]['price'])) price2.append(float(c[i - 1]['price'])) dif1.append(round(price[i - 1] - price2[i - 1], 2)) time.append(c[i]['time']) coinpt = zip(price, dif1, time) context = { 'code': code, 'price': b, 'coinprice': price, 'time': time, 'coinpt': coinpt, 'user': user, 'useremail': useremail, 'access': access, 'refresh': refresh, } return render(request, 'Ali/forcoin.html', context)
def cb_usr_code(request): user=User.objects.filter(username=request.session['user_id']).values()[0] request.session.__delitem__('user_id') userauth=authenticate(request,username=user['username'],password=user['password']) login(request,userauth) ClientId = settings.SOCIAL_AUTH_COINBASE_KEY clientsecret = settings.SOCIAL_AUTH_COINBASE_SECRET code1=request.GET.get('code') r2=requests.post("https://api.coinbase.com/oauth/token",data={"grant_type":"authorization_code","code":code1,"client_id":ClientId,"client_secret":clientsecret,"redirect_uri":"http://www.coinqual.com/coinbase/"}) cbAFtoken=r2.json() usrid=User.objects.filter(username=request.user).values()[0]['id'] #client=OAuthClient(cbAFtoken['access_token'],cbAFtoken['refresh_token']) try: if len(user_token.objects.filter(user_id=usrid).values()[0]['access_token']) >2: user_token.objects.filter(user_id=usrid).update(access_token=cbAFtoken['access_token'],refresh_token=cbAFtoken['refresh_token']) clito=user_token.objects.filter(user_id=usrid).values()[0] client=OAuthClient(clito['access_token'],clito['refresh_token']) userc=client.get_current_user().name price=client.get_spot_price().amount except: save_user_token=user_token(user_id=int(usrid),access_token=cbAFtoken['access_token'],refresh_token=cbAFtoken['refresh_token']) save_user_token.save() clito=user_token.objects.filter(user_id=usrid).values()[0] client=OAuthClient(clito['access_token'],clito['refresh_token']) userc=client.get_current_user()['email'] price=client.get_spot_price().amount # if request.user is not 'ananymous' or request.user is not None: # if client is None: # user_token(access_token=abAFtoken['access_token'],refresh_token=abAFtoken['refresh_token'],user_id=request.user) # user = client.get_current_user() # user_as_json_string = json.dumps(user) # CBtoken(access_token=cbAFtoken['access_token'],refresh_token=cbAFtoken['refresh_token']).save() us=request.user context={ 'us':us, 'code1':code1, 'user':userc, 'price':price,} # return redirect('main') return render(request,'polls/home.html',context)
def test_oauth_details_required(self): with self.assertRaises(ValueError): OAuthClient(None, refresh_token) with self.assertRaises(ValueError): OAuthClient(access_token, None) client = OAuthClient(access_token, refresh_token)
def print_currencies(client: OAuthClient) -> None: print('Currencies:\n', client.get_currencies())
def print_accounts(client: OAuthClient) -> None: print('Accounts:\n', client.get_accounts())
def test_revoke(self): client = OAuthClient(access_token, refresh_token) response = client.revoke() self.assertIs(response, None)
def get_new_token(): for i in range(0,len(user_token.objects.all())): a=OAuthClient(user_token.objects.values()[i]['access_token'],user_token.objects.values()[i]['refresh_token']) a=a.refresh() user_token.objects.filter(user_id=user_token.objects.values()[i]['user_id']).update(access_token=a['access_token'],refresh_token=a['refresh_token'])
def test_response_handling(self): resp200 = lambda r, u, h: (200, h, '{}') resp400 = lambda r, u, h: (400, h, '{}') header_template = ( 'Bearer realm="Doorkeeper" error="{error}" error_description="{message}"') def resp401_revoked(request, uri, headers): error_data = { 'error': 'revoked_token', 'message': 'The access token has been revoked', } headers.update({'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_expired(request, uri, headers): error_data = { 'error': 'expired_token', 'message': 'The access token expired', } headers.update({'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_invalid(request, uri, headers): error_data = { 'error': 'invalid_token', 'message': 'The access token is invalid', } headers.update({'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_generic(request, uri, headers): error_data = { 'error': 'some_error', 'message': 'Some description', } headers.update({'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_nobody(request, uri, headers): return (401, headers, '{}') resp402 = lambda r, u, h: (402, h, '{}') hp.register_uri(hp.GET, re.compile('.*200$'), resp200) hp.register_uri(hp.GET, re.compile('.*400$'), resp400) hp.register_uri(hp.GET, re.compile('.*401_expired$'), resp401_expired) hp.register_uri(hp.GET, re.compile('.*401_revoked$'), resp401_revoked) hp.register_uri(hp.GET, re.compile('.*401_invalid$'), resp401_invalid) hp.register_uri(hp.GET, re.compile('.*401_generic$'), resp401_generic) hp.register_uri(hp.GET, re.compile('.*401_nobody$'), resp401_nobody) hp.register_uri(hp.GET, re.compile('.*402$'), resp402) client = OAuthClient(access_token, refresh_token) self.assertEqual(client._get('200').status_code, 200) with self.assertRaises(APIError): client._get('400') with self.assertRaises(AuthenticationError): client._get('401_generic') with self.assertRaises(InvalidTokenError): client._get('401_invalid') with self.assertRaises(ExpiredTokenError): client._get('401_expired') with self.assertRaises(RevokedTokenError): client._get('401_revoked') with self.assertRaises(AuthenticationError): client._get('401_nobody') with self.assertRaises(TwoFactorRequiredError): client._get('402')
def test_response_handling(self): resp200 = lambda r, u, h: (200, h, '{}') resp400 = lambda r, u, h: (400, h, '{}') header_template = ( 'Bearer realm="Doorkeeper" error="{error}" error_description="{message}"' ) def resp401_revoked(request, uri, headers): error_data = { 'error': 'revoked_token', 'message': 'The access token has been revoked', } headers.update( {'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_expired(request, uri, headers): error_data = { 'error': 'expired_token', 'message': 'The access token expired', } headers.update( {'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_invalid(request, uri, headers): error_data = { 'error': 'invalid_token', 'message': 'The access token is invalid', } headers.update( {'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_generic(request, uri, headers): error_data = { 'error': 'some_error', 'message': 'Some description', } headers.update( {'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_nobody(request, uri, headers): return (401, headers, '{}') resp402 = lambda r, u, h: (402, h, '{}') hp.register_uri(hp.GET, re.compile('.*200$'), resp200) hp.register_uri(hp.GET, re.compile('.*400$'), resp400) hp.register_uri(hp.GET, re.compile('.*401_expired$'), resp401_expired) hp.register_uri(hp.GET, re.compile('.*401_revoked$'), resp401_revoked) hp.register_uri(hp.GET, re.compile('.*401_invalid$'), resp401_invalid) hp.register_uri(hp.GET, re.compile('.*401_generic$'), resp401_generic) hp.register_uri(hp.GET, re.compile('.*401_nobody$'), resp401_nobody) hp.register_uri(hp.GET, re.compile('.*402$'), resp402) client = OAuthClient(access_token, refresh_token) self.assertEqual(client._get('200').status_code, 200) with self.assertRaises(APIError): client._get('400') with self.assertRaises(AuthenticationError): client._get('401_generic') with self.assertRaises(InvalidTokenError): client._get('401_invalid') with self.assertRaises(ExpiredTokenError): client._get('401_expired') with self.assertRaises(RevokedTokenError): client._get('401_revoked') with self.assertRaises(AuthenticationError): client._get('401_nobody') with self.assertRaises(TwoFactorRequiredError): client._get('402')
def test_refresh(self): # Requests to the default BASE_API_URI will noticeably fail by raising an # AssertionError. Requests to the new URL will respond HTTP 200. new_api_base = 'http://example.com/' # If any error is raised by the server, the test suite will never exit when # using Python 3. This strange technique is used to raise the errors # outside of the mocked server environment. errors_in_server = [] server_response_data = { 'access_token': 'newaccesstoken', 'refresh_token': 'newrefreshtoken', } def server_response(request, uri, headers): parsed_uri = urlparse(uri) parsed_reference = urlparse(new_api_base) try: self.assertEqual(parsed_uri.scheme, parsed_reference.scheme) self.assertEqual(parsed_uri.netloc, parsed_reference.netloc) self.assertEqual(parsed_uri.path, parsed_reference.path) except AssertionError as e: errors_in_server.append(e) return (200, headers, json.dumps(server_response_data)) hp.register_uri(hp.POST, OAuthClient.BASE_API_URI + 'oauth/token', body=server_response) hp.register_uri(hp.POST, new_api_base + 'oauth/token', body=server_response) client = OAuthClient(access_token, refresh_token) with self.assertRaises(AssertionError): client.refresh() if errors_in_server: raise errors_in_server.pop() client2 = OAuthClient(access_token, refresh_token, base_api_uri=new_api_base) self.assertEqual(client2.refresh(), server_response_data) # If the response does not include both an access token and refresh token, # an exception will be raised. server_response_data = {'access_token': 'someaccesstoken'} with self.assertRaises(APIError): client2.refresh() server_response_data = {'refresh_token': 'somerefreshtoken'} with self.assertRaises(APIError): client2.refresh()