GithubHelp home page GithubHelp logo

coinbase-python's Introduction

Coinbase

The official Python library for the Coinbase API V2.

Important: this library currently targets the API V2, and the OAuth client requires V2 permissions (i.e. wallet:accounts:read). If you're still using the API V1, please use the old version of this library.

Features

  • Near-100% test coverage.
  • Support for both API Key + Secret and OAuth 2 authentication.
  • Convenient methods for making calls to the API - packs JSON for you!
  • Automatic parsing of API responses into relevant Python objects.
  • All objects have tab-completable methods and attributes when using IPython.

Installation

coinbase is available on PYPI. Install with pip:

pip install coinbase

or with easy_install:

easy_install coinbase

The library is currently tested against Python versions 2.7 and 3.4+.

Note: this package name used to refer to the unofficial coinbase_python library maintained by George Sibble. George graciously allowed us to use the name for this package instead. You can still find that package on Github. Thanks, George.

Documentation

The first thing you'll need to do is sign up with Coinbase.

API Key + Secret

If you're writing code for your own Coinbase account, enable an API key.

Next, create a Client object for interacting with the API:

from coinbase.wallet.client import Client
client = Client(api_key, api_secret)

OAuth2

If you're writing code that will act on behalf of another user, start by creating a new OAuth 2 application from the API settings page. You will need to do some work to obtain OAuth credentials for your users; while outside the scope of this document, please refer to our OAuth 2 flow documentation. Once you have these credentials (an access_token and refresh_token), create a client:

from coinbase.wallet.client import OAuthClient
client = OAuthClient(access_token, refresh_token)

Making API Calls

Both the Client and OAuthClient support all of the same API calls. We've included some examples below, but in general the library has Python classes for each of the objects described in our REST API documentation. These classes each have methods for making the relevant API calls; for instance, coinbase.wallet.model.Order.refund maps to the "refund order" API endpoint. The docstring of each method in the code references the endpoint it implements.

Every method supports the passing of arbitrary parameters via keyword. These keyword arguments will be sent directly to the relevant endpoint. If a required parameter is not supplied, the relevant error will be raised.

Each API method returns an APIObject (a subclass of dict) representing the JSON response from the API, with some niceties like pretty-printing and attr-style item access (response.foo is equivalent to response['foo']). All of the models are dumpable with JSON:

user = client.get_current_user()
user_as_json_string = json.dumps(user)

And, when the response data is parsed into Python objects, the appropriate APIObject subclasses will be used automatically. See the code in coinbase.wallet.model for all of the relevant classes, or the examples below. API methods that return lists of objects (for instance, client.get_accounts() return APIObject instances with nice wrappers around the data of the response body. These objects support direct indexing and slicing of the list referenced by data.

accounts = client.get_accounts()
assert isinstance(accounts.data, list)
assert accounts[0] is accounts.data[0]
assert len(accounts[::]) == len(accounts.data)

But, the APIObject is not actually a list (it's a subclass of dict) so you cannot iterate through the items of data directly. Simple slicing and index access are provided to make common uses easier, but to access the actual list you must reference the data attribute.

Refreshing

All the objects returned by API methods are subclasses of the APIObject and support being "refreshed" from the server. This will update their attributes and all nested data by making a fresh GET request to the relevant API endpoint:

accounts = client.get_accounts()
# Create a new account via the web UI
accounts.refresh()
# Now, the new account is present in the list

Warnings

The API V2 will return relevant *warnings* along with the response data. In a successful API response, any warnings will be present as a list on the returned APIObject:

accounts = client.get_accounts()
assert (accounts.warnings is None) or isinstance(accounts.warnings, list)

All warning messages will also be alerted using the Python stdlib warnings module.

Pagination

Several of the API V2 endpoints are paginated. By default, only the first page of data is returned. All pagination data will be present under the pagination attribute of the returned APIObject:

accounts = client.get_accounts()
assert (accounts.pagination is None) or isinstance(accounts.pagination, dict)

Error Handling

All errors occuring during interaction with the API will be raised as exceptions. These exceptions will be subclasses of coinbase.wallet.error.CoinbaseError. When the error involves an API request and/or response, the error will be a subclass of coinbase.error.APIError, and include request and response attributes with more information about the failed interaction. For full details of error responses, please refer to the relevant API documentation.

Error HTTP Status Code
APIError
TwoFactorRequiredError 402
ParamRequiredError 400
ValidationError 422
InvalidRequestError 400
PersonalDetailsRequiredError 400
AuthenticationError 401
UnverifiedEmailError 401
InvalidTokenError 401
RevokedTokenError 401
ExpiredTokenError 401
InvalidScopeError 403
NotFoundError 404
RateLimitExceededError 429
InternalServerError 500
ServiceUnavailableError 503

OAuth Client

The OAuth client provides a few extra methods to refresh and revoke the access token.

# exchange the current access_token and refresh_token for a new pair
oauth_client.refresh()

This method will update the values stored in the client and return a dict containing information from the token endpoint so that you can update your records.

# revoke the current access_token and refresh_token
oauth_client.revoke()

Protip: You can test OAuth2 authentication easily with Developer Access Tokens which can be created in your OAuth2 application settings. These are short lived tokens which authenticate but don't require full OAuth2 handshake to obtain.

Two Factor Authentication

Sending money may require the user to supply a 2FA token in certain situations. If this is the case, a TwoFactorRequiredError will be raised:

from coinbase.wallet.client import Client
from coinbase.wallet.error import TwoFactorRequiredError

client = Client(api_key, api_secret)
account = client.get_primary_account()
try:
  tx = account.send_money(to='[email protected]', amount='1', currency='BTC')
except TwoFactorRequiredError:
  # Show 2FA dialog to user and collect 2FA token
  # two_factor_token = ...
  # Re-try call with the `two_factor_token` parameter
  tx = account.send_money(to='[email protected]', amount='1', currency='BTC', two_factor_token="123456")

Verify notification authenticity

client.verify_callback(request.body, request.META['CB-SIGNATURE']) # true/false

Usage

This is not intended to provide complete documentation of the API. For more details, please refer to the official documentation. For more information on the included models and abstractions, please read the code – we've done our best to make it clean, commented, and understandable.

Get supported native currencies

client.get_currencies()

Get exchange rates

client.get_exchange_rates()

Buy price

client.get_buy_price(currency_pair = 'BTC-USD')

Sell price

client.get_sell_price(currency_pair = 'BTC-USD')

Spot price

client.get_spot_price(currency_pair = 'BTC-USD')

Current server time

client.get_time()

Get authorization info

client.get_auth_info()

Get user

client.get_user(user_id)

Get current user

client.get_current_user()

Update current user

client.update_current_user(name="New Name")
# or
current_user.modify(name="New Name")

Get all accounts

client.get_accounts()

Get account

client.get_account(account_id)

Get primary account

client.get_primary_account()

Set account as primary

client.set_primary_account(account_id)
# or
account.set_primary()

Create a new bitcoin account

client.create_account()

Update an account

client.update_account(account_id, name="New Name")
# or
account.modify(name="New Name")

Delete an account

client.delete_account(account_id)
# or
account.delete()

Get receive addresses for an account

client.get_addresses(account_id)
# or
account.get_addresses()

Get a receive address

client.get_address(account_id, address_id)
# or
account.get_address(address_id)

Get transactions for an address

client.get_address_transactions(account_id, address_id)
# or
account.get_address_transactions(address_id)

Create a new receive address

client.create_address(account_id)
# or
account.create_address(address_id)

Get transactions

client.get_transactions(account_id)
# or
account.get_transactions()

Get a transaction

client.get_transaction(account_id, transaction_id)
# or
account.get_transaction(transaction_id)

Send money

client.send_money(
    account_id,
    to="3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy",
    amount="1",
    currency="BTC")
# or
account.send_money(to="3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy",
                   amount="1",
                   currency="BTC")

Transfer money

client.transfer_money(
    account_id,
    to="<coinbase_account_id>",
    amount="1",
    currency="BTC")
# or
account.transfer_money(to="<coinbase_account_id>",
                       amount="1",
                       currency="BTC")

Request money

client.request_money(
    account_id,
    to="<email_address>",
    amount="1",
    currency="BTC")
# or
account.request_money(to="<email_address>",
                      amount="1",
                      currency="BTC")

Resend request

client.resend_request(account_id, request_id)

Complete request

client.complete_request(account_id, request_id)

Cancel request

client.cancel_request(account_id, request_id)

Get all reports

client.get_reports()

Get report

client.get_report(report_id)

Create report

client.create_report(type='transactions', email='[email protected]')  # types can also be 'orders' or 'transfers'

Get buys

client.get_buys(account_id)
# or
account.get_buys()

Get a buy

client.get_buy(account_id, buy_id)
# or
account.get_buy(buy_id)

Buy bitcoins

client.buy(account_id, amount='1', currency='BTC')
# or
account.buy(amount='1', currency='BTC')

Commit a buy

You only need to do this if the initial buy was explicitly uncommitted.

buy = account.buy(amount='1', currency='BTC', commit=False)

client.commit_buy(account_id, buy.id)
# or
account.commit_buy(buy.id)
# or
buy.commit()

Get sells

client.get_sells(account_id)
# or
account.get_sells()

Get a sell

client.get_sell(account_id, sell_id)
# or
account.get_sell(sell_id)

Sell bitcoins

client.sell(account_id, amount='1', currency='BTC')
# or
account.sell(amount='1', currency='BTC')

Commit a sell

You only need to do this if the initial sell was explicitly uncommitted.

sell = account.sell(amount='1', currency='BTC', commit=False)

client.commit_sell(account_id, sell.id)
# or
account.commit_sell(sell.id)
# or
sell.commit()

Get deposits

client.get_deposits(account_id)
# or
account.get_deposits()

Get a deposit

client.get_deposit(account_id, deposit_id)
# or
account.get_deposit(deposit_id)

Deposit money

client.deposit(account_id, amount='1', currency='USD')
# or
account.deposit(amount='1', currency='USD')

Commit a deposit

You only need to do this if the initial deposit was explicitly uncommitted.

deposit = account.deposit(amount='1', currency='USD', commit=False)

client.commit_deposit(account_id, deposit.id)
# or
account.commit_deposit(deposit.id)
# or
deposit.commit()

Get withdrawals

client.get_withdrawals(account_id)
# or
account.get_withdrawals()

Get a withdrawal

client.get_withdrawal(account_id, withdrawal_id)
# or
account.get_withdrawal(withdrawal_id)

Withdraw money

client.withdraw(account_id, amount='1', currency='USD')
# or
account.withdraw(amount='1', currency='USD')

Commit a withdrawal

You only need to do this if the initial withdrawal was explicitly uncommitted.

withdrawal = account.withdrawal(amount='1', currency='USD', commit=False)

client.commit_withdrawal(account_id, withdrawal.id)
# or
account.commit_withdrawal(withdrawal.id)
# or
withdrawal.commit()

Get payment methods

client.get_payment_methods()

Get a payment method

client.get_payment_method(payment_method_id)

Get a merchant

client.get_merchant(merchant_id)

Get orders

client.get_orders()

Get a order

client.get_order(order_id)

Create an order

client.create_order(amount='1', currency='BTC', name='Order #1234')

Refund an order

client.refund_order(order_id)
# or
order = client.get_order(order_id)
order.refund()

Get checkouts

client.get_checkouts()

Get a checkout

client.get_checkout(checkout_id)

Create a checkout

client.create_checkout(amount='1', currency='BTC', name='Order #1234')

Get a checkout's orders

client.get_checkout_orders(checkout_id)
# or
checkout = client.get_checkout(checkout_id)
checkout.get_orders()

Create an order for a checkout

client.create_checkout_order(checkout_id)
# or
checkout = client.get_checkout(checkout_id)
checkout.create_order()

Testing / Contributing

Any and all contributions are welcome! The process is simple: fork this repo, make your changes, run the test suite, and submit a pull request. Tests are run via nosetest. To run the tests, clone the repository and then:

# Install the requirements
pip install -r requirements.txt
pip install -r test-requirements.txt

# Run the tests for your current version of Python
make tests

If you'd also like to generate an HTML coverage report (useful for figuring out which lines of code are actually being tested), make sure the requirements are installed and then run:

make coverage

We use tox to run the test suite against multiple versions of Python. You can install tox with pip or easy_install:

pip install tox
easy_install tox

Tox requires the appropriate Python interpreters to run the tests in different environments. We recommend using pyenv for this. Once you've installed the appropriate interpreters, running the tests in every environment is simple:

tox

coinbase-python's People

Contributors

aianus avatar ashishb avatar balloob avatar hugovk avatar johnclause avatar johnlzeller avatar jorilallo avatar joshblum avatar maksim-s avatar mardlin avatar netanelkl avatar peterldowns avatar sds avatar spiliopoulos avatar xhockey5 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

coinbase-python's Issues

Visual Studio Dependency Issue?

Greetings,

When I tried to install the library with pip and easy_install it gave me an error saying I didn't have a VS exe on my machine. Error is below... but this sounds weird considering all of my past Python dev hasn't given me any issues with a Microsoft specific update.

Running pycrypto-2.6.1\setup.py -q bdist_egg --dist-dir C:\Users\matth\AppData\Local\Temp\easy_install-rv4q42w9\pycrypto-2.6.1\egg-dist-tmp-zx9qqsbw warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath. winrand.c C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(26): error C2061: syntax error: identifier 'intmax_t' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(27): error C2061: syntax error: identifier 'rem' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(27): error C2059: syntax error: ';' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(28): error C2059: syntax error: '}' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(30): error C2061: syntax error: identifier 'imaxdiv_t' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(30): error C2059: syntax error: ';' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(40): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2146: syntax error: missing ')' before identifier '_Number' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2061: syntax error: identifier '_Number' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2059: syntax error: ';' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(42): error C2059: syntax error: ')' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(45): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2146: syntax error: missing ')' before identifier '_Numerator' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2061: syntax error: identifier '_Numerator' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2059: syntax error: ';' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2059: syntax error: ',' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(48): error C2059: syntax error: ')' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(50): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(56): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(63): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(69): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(76): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(82): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(89): error C2143: syntax error: missing '{' before '__cdecl' C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(95): error C2143: syntax error: missing '{' before '__cdecl' error: Setup script exited with error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2

TypeError: send_money() takes exactly 2 arguments (3 given)

Tried using this code to make a payment:

tx = client.send_money(
        'WALLET-ID',
        {'to': deposit_address,'amount': deposit_amount,'currency': 'BTC'}
)

which should be correct according to the docs but it throws this error:

TypeError: send_money() takes exactly 2 arguments (3 given)

method code for reference:

def send_money(self, account_id, **params):
    """https://developers.coinbase.com/api/v2#send-money"""
    for required in ['to', 'amount', 'currency']:
      if required not in params:
        raise ValueError("Missing required parameter: %s" % required)
    params['type'] = 'send'
    response = self._post('v2', 'accounts', account_id, 'transactions', data=params)
    return self._make_api_object(response, Transaction)

However, it worked fine when I temporarily modified it to:

def send_money(self, account_id, params):
    """https://developers.coinbase.com/api/v2#send-money"""
    for required in ['to', 'amount', 'currency']:
      if required not in params:
        raise ValueError("Missing required parameter: %s" % required)
    params['type'] = 'send'
    response = self._post('v2', 'accounts', account_id, 'transactions', data=params)
    return self._make_api_object(response, Transaction)

with this code to execute it:

tx = client.send_money('WALLET-ID',params={'to': deposit_address,'amount': deposit_amount,'currency': 'BTC'})

Can't get notifications

Code:

import os
from coinbase.wallet.client import Client

client = Client(os.environ['COINBASE_API_KEY'], os.environ['COINBASE_API_SECRET'])
notifications = client.get_notifications()

Error:

Traceback (most recent call last):
  File "coinbase.get_notifications.py", line 6, in <module>
    notifications = client.get_notifications()
  File "/Users/user/Work/smoothkeyscroll-server/.virtualenv/lib/python2.7/site-packages/coinbase/wallet/client.py", line 264, in get_notifications
    return self._make_api_object(response, Notification)
  File "/Users/user/Work/smoothkeyscroll-server/.virtualenv/lib/python2.7/site-packages/coinbase/wallet/client.py", line 161, in _make_api_object
    obj.data = new_api_object(self, data, model_type)
  File "/Users/user/Work/smoothkeyscroll-server/.virtualenv/lib/python2.7/site-packages/coinbase/wallet/model.py", line 28, in new_api_object
    return [new_api_object(client, v, cls) for v in obj]
  File "/Users/user/Work/smoothkeyscroll-server/.virtualenv/lib/python2.7/site-packages/coinbase/wallet/model.py", line 25, in new_api_object
    result[k] = new_api_object(client, v)
  File "/Users/user/Work/smoothkeyscroll-server/.virtualenv/lib/python2.7/site-packages/coinbase/wallet/model.py", line 15, in new_api_object
    cls = _resource_to_model.get(resource, None)
TypeError: unhashable type: 'dict'
ERROR: exit status 1

Got read notification read permissions, any idea what is wrong?

Basic call for ETH-USD returning BTC-USD

Hello

I am new to the library, but with a very basic piece of code that looks like the following:

from coinbase.wallet.client import Client
api_key = "api_key"
api_secret = "api_secret"

client = Client(api_key, api_secret)

currency_code = 'ETH-USD'  # can also use EUR, CAD, etc.

# Make the request
price = client.get_spot_price(currency_code = 'ETH-USD')

print 'Current  price in %s: %s' % (currency_code, price.amount)

But it is returning:
Current price in ETH-USD: 2615.60

Which is obviously the BTC-USD price.

What am I doing wrong here?

Coinbase - get_spot_price - historical

Must be a newbie question. Trying to fetch the historical daily spot prices on coinbase. Using the python implementation of the api as follows.

https://developers.coinbase.com/api/v2#get-spot-price

price = client.get_spot_price(currency_pair= 'BTC-USD', date='2016-05-10')

Result (actually today's price):

    2016-5-10
{
  "amount": "5613.84",
  "base": "BTC",
  "currency": "USD"
}

I get the current spot price. Could anyone shade some light on what I am missing? Thanks!

Bug with get_address_transactions

So I am using coinbase API and the python library available by them.

accounts = client.get_accounts()

accountId=accounts["data"][0]["id"]    
print(client.get_address_transactions(accountId, id))

The above returns

{
  "data": []
}

But if I do:

txs = client.get_transactions(accountId)
print(txs["data"][0])

I get the following results:

{
  "address": {
    "id": id, 
    "resource": "address", 
    "resource_path": 
  }, 
  ......
  "status": "completed", 
  "type": "send"
}

It doesn't make sense, I have send money to myself to test this feature and the transactions don't seem to show in that api call.

The IDs are the same

Get price and get exchange rates not working.

Hi when writing a simple python script to test Coinbase Features as per documentation I am getting the following results:

rates = client.get_exchange_rates(currency='BTC') rates
Result:

<APIObject @ 0x115841468> {
"currency": "USD",
"rates": {
"AED": "3.67",
"AFN": "69.77",
"ALL": "109.45"...

I also get similar issues when I try getting the price
price = client.get_buy_price(currency_pair = 'LTC-USD') price
Output

<APIObject @ 0x115841fc0> {
"amount": "13830.94",
"base": "BTC",
"currency": "USD"

I am using API keys with all functionality allowed.

502 causes JSONDecodeError

I wrote a little program that ended up sending a traceback that ended with:

  File "/usr/local/lib/python2.7/dist-packages/coinbase/wallet/client.py", line 221, in get_accounts
    response = self._get('v2', 'accounts', data=params)
  File "/usr/local/lib/python2.7/dist-packages/coinbase/wallet/client.py", line 125, in _get
    return self._request('get', *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/coinbase/wallet/client.py", line 112, in _request
    return self._handle_response(response)
  File "/usr/local/lib/python2.7/dist-packages/coinbase/wallet/client.py", line 121, in _handle_response
    raise build_api_error(response)
  File "/usr/local/lib/python2.7/dist-packages/coinbase/wallet/error.py", line 49, in build_api_error
    blob = blob or response.json()
  File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 805, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 488, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 389, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

..which is what happens when the _handle_response gets a 502 ; this should be bubbled up differently, I think.

Is it possible to transfer coin -> coin?

I am trying to transfer between a BTC -> LTC, or ETH -> LTC account.

I am not able to get this to work either via this package or via simple Postman requests.

Here's my approach. After Oauth, I get the client's account IDs. I then get the account for BTC and account for ETH.

I then create a transfer between the two, with a request body like this (below). The code below is in Javascript, but applies as well to Python:

const url = `${endpoint}/v2/accounts/${accountId}/transactions`
const type = 'transfer';
const to = 'TO_ID';
const currency = 'BTC';
const amount = '0.00000001';
const response = await request.post(url, { type, to, amount, currency }, { headers });

Here, response comes back with a 'Not found' error:

{
    "errors": [
        {
            "id": "not_found",
            "message": "Not found"
        }
    ],
    "warnings": [
        {
            "id": "missing_version",
            "message": "Please supply API version (YYYY-MM-DD) as CB-VERSION header",
            "url": "https://developers.coinbase.com/api#versioning"
        }
    ]
}

I would appreciate any help in getting this to work! Thank you!

ValueError from None and build_api_error

Hello,

I recently answered a post on stackoverflow about a strange behaviour of your API
(http://stackoverflow.com/questions/37638359/api-coinbase-valueerror-from-get-buy-price/37646769#37646769).

There seems to be an internal error (build_api_error seems to confirm my assertion) under some conditions (which I can't reproduce because I'm not the author of the post).

I suspect that's something related to a network connectivity problem that causes a null JSON file.
It's why the code throws a raise ValueError(errmsg("Expecting value", s, err.value)) from None error.

It also seems quite related to that other issue: #15

I hope it will help :)

PyPI version is out of date

I was having problems with fetching spot prices for different currency pair combinations but I kept getting only spot prices for bitcoin so I decide to look into the source of the coinbase version that I had installed with pip. It basically had an older version of the source for all the prices api hence the reason for the bad response. Could this be updated?

create_checkout() takes exactly 1 argument (4 given)

No idea what's wrong:

>>> c = Client(COINBASE_API_KEY, COINBASE_API_SECRET, COINBASE_SANDBOX_URI)
>>> b = c.create_checkout('1', 'BTC', 'New Item')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: create_checkout() takes exactly 1 argument (4 given)
>>>

Iterating through paginated results should be built-in

Currently it appears that I have to drop down to manually GETing the next_uri strings provided in the pagination responses to iterate through the pages of a return value.

This should be built into this API client's interface. For example, account.get_transactions(page=5).

InternalServerError when calling get_notifications

When using client.get_notifications() I get the following error:

Traceback (most recent call last):
  File "D:/SourceCode/Python/untitled/test.py", line 10, in <module>
    print client.get_notifications()
  File "C:\Python27_32\envs\test\lib\site-packages\coinbase\wallet\client.py", line 268, in get_notifications
    response = self._get('v2', 'notifications', params=params)
  File "C:\Python27_32\envs\test\lib\site-packages\coinbase\wallet\client.py", line 128, in _get
    return self._request('get', *args, **kwargs)
  File "C:\Python27_32\envs\test\lib\site-packages\coinbase\wallet\client.py", line 115, in _request
    return self._handle_response(response)
  File "C:\Python27_32\envs\test\lib\site-packages\coinbase\wallet\client.py", line 124, in _handle_response
    raise build_api_error(response)
coinbase.wallet.error.InternalServerError: APIError(id=internal_server_error): An error has occurred. If this problem persists, please visit https://support.coinbase.com for assistance.

client.get_notification is working fine.

Method get_exchange_rates passing params as data

Whilst trying out the coinbase python client I noticed that the following code returned incorrect results:

client = Client('x','z')
for cur in ['ETH', 'BTC', 'LTC']:
  r = client.get_exchange_rates(currency=cur)
  print('{} => {}'.format(cur, r['currency']))

It returned:

BTC => ETH
ETH => ETH
LTC => ETH

When it should have returned:

BTC => BTC
ETH => ETH
LTC => LTC

I believe the problem is somewhere in this method. I've tried changing the key-word arguments from self._get('v2', 'exchange-rates', data=params) to self._get('v2', 'exchange-rates', params=params) and it worked as expected.

The documentation of the requests python module (used by coinbase to make the actual requests) states that params should be used to specify the URL parameters and since the coinbasa API expects a URL parameter currency it seems to make sense.

Does this make sense or have I done something wrong?

EUR-Wallet: APIError (id=invalid_request): Can't buy with this account

Dear guys,

i am trying to do a trade on coinbase via script. I can pull the prices, i get the account data, the payment methods and so on....finally i would like to buy some coins with my EUR-Wallet. There is some amount of money on this account for testing purposes.
The ID of the payment method etc shall be chosen correctly but nevertheless the error above in the headline arises. I would be glad for your experiences and help;) with kind regards, John

In the following ,i will try to describe all the actions done in my script for reproducing this error:

accounts=client.get_accounts()       #get my accounts (i have EUR-Wallet, ETH, LTC and BTC Accounts)
payment_method=client.get_payment_methods()[0]     #Chooses the EUR-Wallet as my paymentmethod

account=client.get_account("abcdefghihklmnoqrstuvwxyz") # Argument is the ID of EUR-Wallet

buy = account.buy(amount='0.00001', currency="LTC", payment_method=payment_method.id)


print payment_method 

shows:

{
  "allow_buy": true, 
  "allow_deposit": true, 
  "allow_sell": true, 
  "allow_withdraw": true, 
  "created_at": "2017-10-09T19:12:29Z", 
  "currency": "EUR", 
  "fiat_account": {
    "id": "abcdefghihklmnoqrstuvwxyz", 
    "resource": "account", 
    "resource_path": "/v2/accounts/abcdefghihklmnoqrstuvwxyz"
  }, 
  "id": "1234567891011121314151617", 
  "instant_buy": true, 
  "instant_sell": true, 
  "limits": {
    "buy": [
      {
        "description": "\u20ac9,000 of your \u20ac9,000 weekly Coinbase account limit remaining", 
        "label": "Total EUR limit", 
        "next_requirement": {
          "type": "identity_verification"
        }, 
        "period_in_days": 7, 
        "remaining": {
          "amount": "9000.00", 
          "currency": "EUR"
        }, 
        "total": {
          "amount": "9000.00", 
          "currency": "EUR"
        }
      }
    ], 
    "name": "Coinbase Account", 
    "sell": [
      {
        "description": "\u20ac9,000 of your \u20ac9,000 weekly Coinbase account limit remaining", 
        "label": "Total EUR limit", 
        "next_requirement": {
          "type": "identity_verification"
        }, 
        "period_in_days": 7, 
        "remaining": {
          "amount": "9000.00", 
          "currency": "EUR"
        }, 
        "total": {
          "amount": "9000.00", 
          "currency": "EUR"
        }
      }
    ], 
    "type": "fiat_account"
  }, 
  "name": "EUR Wallet", 
  "primary_buy": true, 
  "primary_sell": true, 
  "resource": "payment_method", 
  "resource_path": "/v2/payment-methods/1234567891011121314151617", 
  "type": "fiat_account", 
  "updated_at": "2017-10-09T19:12:29Z", 
  "verified": true
}

So as you can see i have the correct payment_method ID as well as the correct EUR-Wallet ID. And all my accounts are allowed to deal with the whole set of requests that coinbase API can offer. this is done in the configuration on my coinbase account.
I would be glad for support.

This is the full error message:

Traceback (most recent call last):
  File "/home/pi/Desktop/First_Script.py", line 265, in <module>
    payment_method=payment_method.id)
  File "/usr/local/lib/python2.7/dist-packages/coinbase-2.0.6-py2.7.egg/coinbase/wallet/model.py", line 200, in buy
    return self.api_client.buy(self.id, **params)
  File "/usr/local/lib/python2.7/dist-packages/coinbase-2.0.6-py2.7.egg/coinbase/wallet/client.py", line 381, in buy
    response = self._post('v2', 'accounts', account_id, 'buys', data=params)
  File "/usr/local/lib/python2.7/dist-packages/coinbase-2.0.6-py2.7.egg/coinbase/wallet/client.py", line 132, in _post
    return self._request('post', *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/coinbase-2.0.6-py2.7.egg/coinbase/wallet/client.py", line 116, in _request
    return self._handle_response(response)
  File "/usr/local/lib/python2.7/dist-packages/coinbase-2.0.6-py2.7.egg/coinbase/wallet/client.py", line 125, in _handle_response
    raise build_api_error(response)
InvalidRequestError: APIError(id=invalid_request): Can't buy with this account

and this the relevant section in the package that throws the error:

def _request(self, method, *relative_path_parts, **kwargs):
    """Internal helper for creating HTTP requests to the Coinbase API.

    Raises an APIError if the response is not 20X. Otherwise, returns the
    response object. Not intended for direct use by API consumers.
    """
    uri = self._create_api_uri(*relative_path_parts)
    data = kwargs.get('data', None)
    if data and isinstance(data, dict):
      kwargs['data'] = encode_params(data)
    if self.VERIFY_SSL:
      kwargs.setdefault('verify', COINBASE_CRT_PATH)
    else:
      kwargs.setdefault('verify', False)
    kwargs.update(verify=self.VERIFY_SSL)
    response = getattr(self.session, method)(uri, **kwargs)
    return self._handle_response(response)

  def _handle_response(self, response):
    """Internal helper for handling API responses from the Coinbase server.

    Raises the appropriate exceptions when necessary; otherwise, returns the
    response.
    """
    if not str(response.status_code).startswith('2'):
      raise build_api_error(response)
    return response

  def _get(self, *args, **kwargs):
    return self._request('get', *args, **kwargs)

  def _post(self, *args, **kwargs):
    return self._request('post', *args, **kwargs)

  def _put(self, *args, **kwargs):
    return self._request('put', *args, **kwargs)

How can I send USD/EUR to an exchange?

This is rather a question as I did not find any information about it.

Is it possible to send USD or EUR to an exchange (like Kraken)? If yes, how it is possible? I could not find any information about this.
Thank you very much in advance!

"cannot make memory view because object does not have the buffer interface"

requests using the python lib started breaking.
I'm using coinbase 2.8.1, python 2.7.9.

and I noticed, after upgrading my packages (I believe specifically the requests package from 2.7.0 to 2.8.1), that I started receiving
"cannot make memory view because object does not have the buffer interface".
I believe the reason is a change in either the requests package or the encompassed urllib3 lib.
I did some debugging into it, and noticed that the body of the request (actually the headers are being converted to a memoryview. Problem is, it doesnt support unicode (as far as I could tell).
I traced the exception down to requests.packages.urllib3.contrib.pyopenssl.py
I noticed that if I remove:
from future import unicode_literals
on the coinbase library so that str types would be passed in the header keys, the problem disappears.

Cannot install on Rasperry Pi

I always have problems installing on the rasperry pi, failing with error "Python.h: No such file or directory"
I have tried:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libpython3-dev
sudo apt-get install python3.4-dev
sudo apt-get install python3.2-dev
sudo apt-get install libpython3.4-dev
and also reinstalling python-dev.

Nothing has worked.

always getting error

{"data": "{" error \ ": " invalid_request \ ", " error_description \ ": " The request is missing a prescribed parameter, contains an unsupported parameter value, or is different Way buggy. \ "}"}

get_buy_price broken

from coinbase.wallet.client import Client
client = Client(apikey, keysecret)
print(client.get_buy_price(currency_pay="BTC-EUR"))
print(client.get_buy_price(currency_pay="BTC-USD"))
print(client.get_buy_price(currency_pay="BTC-ETH"))

result is:

{
  "amount": "1374.55",
  "currency": "USD"
}
{
  "amount": "1374.55",
  "currency": "USD"
}
{
  "amount": "1374.55",
  "currency": "USD"
}

Regards,
Carl Chenet

API_VERSION warning

I am just getting started into using my auth tokens to do operations...

BASE_API_URI = 'https://api.sandbox.coinbase.com/v2'
client = OAuthClient(token.access_token, token.refresh_token, base_api_uri=BASE_API_URI)
cb_user = client.get_current_user()

Then I get the warning...
coinbase/wallet/client.py:149: UserWarning: Please supply API version (YYYY-MM-DD) as CB-VERSION header (https://developers.coinbase.com/api#versioning)

I see that CB-VERSION is set when building the request. Wanted to ask if I am using this properly, and whether I can do something to prevent the warning? Hopefully, as I use this more, I will be able to contribute.

Thanks.

transfer_money method only supports BTC

Hello,
I'm doing the following (Python3):

client.transfer_money(usdwalletid, to=ltcwalletid, amount='{0}'.format(float(usdwallet['balance']['amount'])))

Where usdwalletid and ltcwalletid are pulled from the client.get_accounts() method. I realize the float wasn't necessary. I get the following response:

ValueError: Missing required parameter: currency

Which is fine, I guess. The Python documentation here doesn't call that out in the example and should probably be updated (even though currency is specified as required in the arguments).

Anyway, I do this instead:

client.transfer_money(usdwalletid, to=ltcwalletid, amount='{0}'.format(float(usdwallet['balance']['amount'])), currency='USD')

The currency parameter seems redundant given that each wallet type (I presume) can only hold one type of currency, such that you could derive the currency from the targetted wallet. But that's not why I'm here:

coinbase.wallet.error.InvalidRequestError: APIError(id=invalid_request): You can only move BTC out of a wallet

It doesn't support the other cryptocurrencies Coinbase supports? That's weird:

client.transfer_money(btcwalletid, to=usdwalletid, amount='0.00274735', currency='BTC')

And the reply:

coinbase.wallet.error.InvalidRequestError: APIError(id=invalid_request): You can only move BTC into a wallet or a vault account

So I guess I can only move BTC out of a wallet in to another BTC wallet or Vault? Is that right?

ConnectionError: HTTPSConnectionPool (host='api.coinbase', port 443): Max retries exceeded with url: /v2/prices/LTC-EUR/sell

Hey Guys,

i just run a script for one night, getting the prices of LTC in EUR and was confronted with the following error:

ConnectionError: HTTPSConnectionPool (host='api.coinbase', port 443): Max retries exceeded with url: /v2/prices/LTC-EUR/sell (Caused by NewConnectionErro ('<urllib3.connection.VerifiedHTTPSConnection object at 0x71f45a10>: Failed to establish a new connection: [Errno -2] Name or service not know',))

Is there a limit on how often you can push requests? i pushed those requests for 6 hours until i got this error. Does anyone know how one can prevent this error or give me some details about it?

I would be glad for your help! many thanks!;)

Pagination Tools

As far as I can tell, this library provides no way of easily navigating paginated API endpoints.

The coinbase-node API makes it super easy. See the "Using pagination" section:

account.getTransactions(null, function(err, txns, pagination) {
  txns.forEach(function(txn) {
    console.log('my txn: ' + txn.id);
  });
  console.log(pagination.next_uri);
  account.getTransactions(pagination, function(err, txns) {
    txns.forEach(function(txn) {
      console.log('my txn: ' + txn.id);
    });
  });
});

SSL Connection error

Traceback (most recent call last):
File "C:\Users\mboyle\Desktop\tmp.py", line 5, in
user = sandbox_client.get_current_user()
File "C:\Python27\lib\site-packages\coinbase-2.0.6-py2.7.egg\coinbase\wallet\client.py", line 213, in get_current_user
response = self._get('v2', 'user', data=params)
File "C:\Python27\lib\site-packages\coinbase-2.0.6-py2.7.egg\coinbase\wallet\client.py", line 129, in _get
return self._request('get', _args, *_kwargs)
File "C:\Python27\lib\site-packages\coinbase-2.0.6-py2.7.egg\coinbase\wallet\client.py", line 115, in _request
response = getattr(self.session, method)(uri, *_kwargs)
File "C:\Python27\lib\site-packages\requests-2.10.0-py2.7.egg\requests\sessions.py", line 487, in get
return self.request('GET', url, *_kwargs)
File "C:\Python27\lib\site-packages\requests-2.10.0-py2.7.egg\requests\sessions.py", line 475, in request
resp = self.send(prep, *_send_kwargs)
File "C:\Python27\lib\site-packages\requests-2.10.0-py2.7.egg\requests\sessions.py", line 585, in send
r = adapter.send(request, *_kwargs)
File "C:\Python27\lib\site-packages\requests-2.10.0-py2.7.egg\requests\adapters.py", line 477, in send
raise SSLError(e, request=request)
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

Prices are weird

where does this pull its numbers from?

if use:

file_get_contents('https://api.coinbase.com/v1/prices/sell?qty=1');

it returns 1198.27 that matches the sell price on coinbase.com, but:

print client.get_sell_price(currency_pair = 'BTC-USD').amount

it returns 1192.28.

just showing its off from the actual coinbase site, if its using exchange numbers then that's why its off.

get_*_price doesn't use specified currency

It appears to mostly return in CAD instead of USD, despite asking for USD:

In [9]: client.get_spot_price(currency_pair='BTC-USD')
Out[9]:
<APIObject @ 0x38b7880> {
  "amount": "1386.45",
  "currency": "CAD"
}

Although sometimes it returns USD....

For the time being I'm using the REST API without authentication as a workaround.

Bug in granularity (historical prices) + Get percentage change since yesterday

Is there any way to display the 'percentage change since yesterday' with the coinbase API?

I tried something like this to get the historic prices of BTC, so i can add the values ​​together and calculate the percentage share with this. Maybe there is an easier way.

test = client._make_api_object(client._get('v2', 'prices', 'BTC-USD', 'historic'), APIObject)
print '%s' % (test)
print '%s' % (test.prices)

Anyway, even that does not work, because I get a list and can not parse the individual price.

AttributeError: 'list' object has no attribute 'price'

And even if this works, that only shows me the value of the past hour in 10 seconds steps. While we're at it, can this somehow be used to show the value of a specific given day?

Get buy/sell price ignores the currency pair requested

When asking for BTC-USD I am regularly seeing EUR prices come up - though it does at least also report that the currency is EUR when that happens:
>>> client.get_buy_price(currency_pair='BTC-USD')
{ "amount": "13471.88", "base": "BTC", "currency": "EUR" }
I presume it is actually reporting the most recent BTC price without considering the underlying currency that was traded against it.

Resolution:

  • recommend accepting single 'currency' on the price request for the current operation (ie, just get most recent Bitcoin price, tell me the currency it is against)
  • recommend API also gets the exchange rate and applies it on a pair price request that is not correctly honoured, and adds 'exchangeRate' and 'exchangeCurrency' elements to the results.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.