Bitstamp API wrapper for Python

Overview

NOTICE: THIS REPOSITORY IS NO LONGER ACTIVELY MAINTAINED

It is highly unlikely that I will respond to PRs and questions about usage.

This library was written a long time ago and not kept up to date. It may still hold value for you but it's increasingly out of date with the modern Bitstampy API and Python versions.

I heartily encourage a fork and welcome any contact about taking over ownership - find me at https://twitter.com/unwttng.

bitstampy

Bitstamp API wrapper for Python

Installation

Is pretty bloody easy, as long as you've got pip installed. If you haven't, take a look at the pip documentation - it's worth getting familiar with!

pip install bitstampy

Usage

> from bitstampy import api

Public calls (no API authorisation needed)

Ticker

# Ticker information
> api.ticker()
{
    'timestamp': datetime,   # Datetime
    'volume': decimal,       # Last 24 hours volume
    'last': decimal,         # Last BTC price
    'high': decimal,         # Last 24 hours high
    'low': decimal,          # Last 24 hours low
    'bid': decimal,          # Highest buy order
    'ask': decimal           # Lowest ask order
}

Order Book

# Global order book (see live at https://www.bitstamp.net/market/order_book/)
# Parameters
## [group = True] - Group orders with same price?
##                - boolean
> api.order_book()
{
    'timestamp': datetime,      # Datetime
    'bids': [                   # List of bids
        {
            'price': decimal,   ## Price for bid
            'amount': decimal   ## Amount bid
        }, ...
    ],
    'asks': [                   # List of asks
        {
            'price': decimal,   ## Price for ask
            'amount': decimal   ## Amount asked
        }, ...
    ]
}

Transactions

# Global transactions
# Parameters
## [offset = 0]    - Skip this many transactions before starting return list
##                 - int
## [limit = 100]   - Return this many transactions after the offset
##                 - int
## [sort = 'desc'] - Results are sorted by datetime
##                 - string - api.TRANSACTIONS_SORT_DESCENDING or
##                 -        - api.TRANSACTIONS_SORT_ASCENDING
> api.transactions()
[                           # List of transactions, length 'limit'
    {
        'date': datetime,   ## Datetime
        'tid': string,      ## Transaction ID
        'price': decimal,   ## Transaction price
        'amount': decimal   ## Transaction amount
    }, ...
]

EUR/USD Conversion Rate

# Bitstamp's Dollar to Euro conversion rate
> api.eur_usd_conversion_rate()
{
    'sell': decimal,   # Conversion rate for selling
    'buy': decimal     # Conversion rate for buying
}

Private calls (authorisation required)

Every call after this point requires you to have a working API key and secret associated with your account on Bitstampy. To get one set up, head to your Account > Security > API Access. Choose a set of permissions you'd like the key to have - the meaning of each of these should be pretty clear. After you've created a key, you need to activate it - this is done via a confirmation link in an email.

You'll get an API key and an associated secret. Note these down in your incredibly secure password manager / encrypted system / sneaky hidden notepad of choice, because Bitstampy'll only let you view the API secret for 5 minutes after you activate it ('cus security).

Each of the following API function calls takes three additional parameters - client_id, api_key and api_secret. The API key and secret are obvious, and client_id is your customer ID on Bitstampy (the numerical one). I'll include them in the function prototypes abbreviated as c, k, s.

Let's see the rest of the calls! These are the interesting ones because they get you access to do actual stuff stuff with your account.

Account Balance

# Your account balance
> api.account_balance(c, k, s)
{
    'usd_balance': decimal,     # US Dollar balance
    'btc_balance': decimal,     # Bitcoin balance
    'usd_reserved': decimal,    # US Dollars reserved in open orders
    'btc_reserved': decimal,    # Bitcoins reserved in open orders
    'usd_available': decimal,   # US Dollars available
    'btc_available': decimal,   # Bitcoins available
    'fee': decimal              # Account trading fee (in %)
}

User Transactions

# Your transactions
# Parameters
## [offset = 0]    - Skip this many transactions before starting return list
##                 - int
## [limit = 100]   - Return this many transactions after the offset
##                 - int
## [sort = 'desc'] - Results are sorted by datetime
##                 - string - api.USER_TRANSACTIONS_SORT_DESCENDING or
##                 -        - api.USER_TRANSACTIONS_SORT_ASCENDING
> api.user_transactions(c, k, s)
[                               # List of transactions, length 'limit'
    {
        'datetime': datetime,   ## Datetime
        'id': string,           ## Transaction ID
        'type': string,         ## Transaction type - one of
                                ### api.USER_TRANSACTIONS_TYPE_DEPOSIT,
                                ### api.USER_TRANSACTIONS_TYPE_WITHDRAWAL,
                                ### api.USER_TRANSACTIONS_TYPE_MARKET_TRADE
        'usd': decimal,         ## US Dollar amount
        'btc': decimal,         ## Bitcoin amount
        'fee': decimal,         ## Transaction fee (in %)
        'order_id': decimal     ## Transaction amount
    }, ...
]

Open Orders

# Your open orders
> api.open_orders(c, k, s)
[                               # List of open orders
    {
        'datetime': datetime,   ## Datetime
        'id': string,           ## Order ID
        'type': string,         ## Order type - one of
                                ### api.OPEN_ORDERS_TYPE_BUY,
                                ### api.OPEN_ORDERS_TYPE_SELL
        'price': decimal,       ## Order price
        'amount': decimal       ## Order amount
    }, ...
]

Cancel Order

# Cancel an order
# Parameters
## order_id - ID of order to cancel
##          - string
> api.cancel_order(c, k, s)
True / False   # Returns boolean success

Buy Limit Order

# Place a buy order
## amount - Amount to buy
##        - float
## price  - Price to offer
##        - float
> api.buy_limit_order(c, k, s)
{
    'datetime': datetime,   # Datetime placed
    'id': string,           # Order ID
    'type': string,         # Order type - one of 
                            ## api.BUY_LIMIT_ORDER_TYPE_BUY,
                            ## api.BUY_LIMIT_ORDER_TYPE_SELL
    'price': decimal,       # Placed order price
    'amount': decimal       # Placed order amount
}

Sell Limit Order

# Place a sell order
## amount - Amount to sell
##        - float
## price  - Price to ask for
##        - float
> api.sell_limit_order(c, k, s)
{
    'datetime': datetime,   # Datetime placed
    'id': string,           # Order ID
    'type': string,         # Order type - one of 
                            ## api.SELL_LIMIT_ORDER_TYPE_BUY,
                            ## api.SELL_LIMIT_ORDER_TYPE_SELL
    'price': decimal,       # Placed order price
    'amount': decimal       # Placed order amount
}

Check Bitstamp Code

# Check the value of a bitstamp code
## code - Bitstamp code
##      - string
> api.check_bitstamp_code(c, k, s)
{
    'usd': decimal,   # US Dollar amount in the code
    'btc': decimal    # Bitcoin amount in the code
}

Redeem Bitstamp Code

# Redeem a bitstamp code
## code - Bitstamp code
##      - string
> api.redeem_bitstamp_code(c, k, s)
{
    'usd': decimal,   # US Dollar amount added to account by code
    'btc': decimal    # Bitcoin amount added to account by code
}

Withdrawal Requests

# Get list of withdrawal requests
> api.withdrawal_requests(c, k, s)
[                               # List of withdrawal requests
    {
        'datetime': datetime,   ## Datetime
        'id': string,           ## Withdrawal ID
        'type': string,         ## Request type - one of
                                ### api.WITHDRAWAL_REQUEST_TYPE_SEPA,
                                ### api.WITHDRAWAL_REQUEST_TYPE_BITCOIN,
                                ### api.WITHDRAWAL_REQUEST_TYPE_WIRE,
                                ### api.WITHDRAWAL_REQUEST_TYPE_BITSTAMP_CODE_1,
                                ### api.WITHDRAWAL_REQUEST_TYPE_BITSTAMP_CODE_2,
                                ### api.WITHDRAWAL_REQUEST_TYPE_MTGOX
        'status': string,       ## Request status - one of
                                ### api.WITHDRAWAL_REQUEST_STATUS_OPEN,
                                ### api.WITHDRAWAL_REQUEST_STATUS_IN_PROCESS,
                                ### api.WITHDRAWAL_REQUEST_STATUS_FINISHED,
                                ### api.WITHDRAWAL_REQUEST_STATUS_CANCELLED,
                                ### api.WITHDRAWAL_REQUEST_STATUS_FAILED
        'amount': decimal,      ## Request amount
        'data': string          ## Extra data (specific to type)
    }, ...
]

Bitcoin Withdrawal

# Withdraw bitcoins to an address
## amount  - amount to withdraw in BTC
##         - decimal
## address - bitcoin address to withdraw to
##         - string
> api.bitcoin_withdrawal(c, k, s)
True / False   # Returns boolean success

Bitcoin Deposit Address

# Get your account's address for bitcoin deposits
> api.bitcoin_deposit_address(c, k, s)
# Returns deposit address as string

Unconfirmed Bitcoin Deposits

# Retrieve list of as-yet unconfirmed bitcoin deposits into your account
> api.unconfirmed_bitcoin_deposits(c, k, s)
[                              # List of unconfirmed deposits
    {
        'amount': decimal,     ## Amount deposited
        'address': string,     ## Address deposited to
        'confirmations': int   ## How many confirmations on the deposit so far
    }, ...
]
Comments
  • Getting

    Getting "APIError: Invalid nonce"

    Hi Jack

    Thanks for the API!

    I'm trying to do a buy limit order and I'm getting an error. Is this a problem with Bitstampy or just something that I'm doing wrong... sorry to post this here but I could not find your email address.

    bitstamp.buy_limit_order(c, k, s, 0.01, ask * 1.10)

    Traceback (most recent call last): File "/Users/daniel/bitcoin/coinduit/bank/bank.py", line 17, in bitstamp.buy_limit_order(c, k, s, 0.01, ask * 1.10) File "/Library/Python/2.7/site-packages/bitstampy/api.py", line 62, in buy_limit_order .call(amount=amount, price=price) File "/Library/Python/2.7/site-packages/bitstampy/calls.py", line 86, in call return super(APIPrivateCall, self).call(**params) File "/Library/Python/2.7/site-packages/bitstampy/calls.py", line 57, in call raise APIError(response['error']) APIError: Invalid nonce

    Is there something I need to do to set the nonce?

    opened by dsmurrell 6
  • unicode objects must be encoded

    unicode objects must be encoded

    maybe it's just me but: from bitstampy import api c='999999' k='xXx' s=b'xXx' api.account_balance(c, k, s)

    and I get the error: TypeError: Unicode-objects must be encoded before hashing on pyhton 3.4

    opened by vantessel 3
  • ImportError on Python 3.5

    ImportError on Python 3.5

    When trying to do 'from bistampy import api' i get 'ImportError: No module named calls'

    A simple fix for this was to simply change the first line in api.py from 'import calls' to 'from . import calls'

    opened by johan-bjareholt 3
  • problem with bytes, bytearray ans str

    problem with bytes, bytearray ans str

    Hi, Tried to run the code on python3, and got this stacktrace. It appears to be a python3 compatability issue - the code runs perfectly on python2 Thankyou

    Traceback (most recent call last): File "tr5.py", line 158, in bitstamp_USD_balance=bitstamp_balance(bs_c=bs_c, bs_k=bs_k, bs_s=bs_s, asset="usd_available") File "tr5.py", line 61, in bitstamp_balance bs_data=api.account_balance(bs_c, bs_k, bs_s) File "/home/ubuntu/btc/installstuff/bitstampy/bitstampy/api.py", line 40, in account_balance calls.APIAccountBalanceCall(client_id, api_key, api_secret) File "/home/ubuntu/btc/installstuff/bitstampy/bitstampy/calls.py", line 81, in call self.api_secret, msg=message, digestmod=hashlib.sha256) File "/usr/lib/python3.4/hmac.py", line 144, in new return HMAC(key, msg, digestmod) File "/usr/lib/python3.4/hmac.py", line 42, in init raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).name) TypeError: key: expected bytes or bytearray, but got 'str'

    opened by amnonmel 1
  • Finish off README documentation

    Finish off README documentation

    Still a couple of API calls which are supported but aren't listed in the README.md documentation. I've been working in the same order as the API documentation page so it's everything after the last documented one to go.

    enhancement 
    opened by unwitting 0
  • What type to use for client_id, api_key, api_secret

    What type to use for client_id, api_key, api_secret

    c = '12345'
    k = 'xxxxx'
    s = 'yyyyy'
    api.account_balance(c, k, s)
    
    
    ~/.virtualenvs/bitstamp/lib/python3.6/site-packages/bitstampy/api.py in account_balance(client_id, api_key, api_secret)
         38 def account_balance(client_id, api_key, api_secret):
         39     return (
    ---> 40         calls.APIAccountBalanceCall(client_id, api_key, api_secret)
         41         .call()
         42     )
    
    ~/.virtualenvs/bitstamp/lib/python3.6/site-packages/bitstampy/calls.py in call(self, **params)
         79         message = nonce + self.client_id + self.api_key
         80         signature = hmac.new(
    ---> 81             self.api_secret, msg=message, digestmod=hashlib.sha256)
         82         signature = signature.hexdigest().upper()
         83         params.update({
    
    ~/.virtualenvs/bitstamp/lib/python3.6/hmac.py in new(key, msg, digestmod)
        142     method.
        143     """
    --> 144     return HMAC(key, msg, digestmod)
    
    ~/.virtualenvs/bitstamp/lib/python3.6/hmac.py in __init__(self, key, msg, digestmod)
         40 
         41         if not isinstance(key, (bytes, bytearray)):
    ---> 42             raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
         43 
         44         if digestmod is None:
    
    TypeError: key: expected bytes or bytearray, but got 'str'
    
    
    

    Changed key to bytes :

    k = b'xxxxx' Then :

    api.account_balance(c, k, s)
    
    TypeError                                 Traceback (most recent call last)
    <ipython-input-27-35f3ae0e7115> in <module>()
    ----> 1 api.account_balance(c, k, s)
    
    ~/.virtualenvs/bitstamp/lib/python3.6/site-packages/bitstampy/api.py in account_balance(client_id, api_key, api_secret)
         38 def account_balance(client_id, api_key, api_secret):
         39     return (
    ---> 40         calls.APIAccountBalanceCall(client_id, api_key, api_secret)
         41         .call()
         42     )
    
    ~/.virtualenvs/bitstamp/lib/python3.6/site-packages/bitstampy/calls.py in call(self, **params)
         77     def call(self, **params):
         78         nonce = self._get_nonce()
    ---> 79         message = nonce + self.client_id + self.api_key
         80         signature = hmac.new(
         81             self.api_secret, msg=message, digestmod=hashlib.sha256)
    
    TypeError: must be str, not bytes
    
    

    I am rather confused. Could you please clarify the argument types to use for client_id, api_key, api_secret ? Thanks

    opened by Salan54 1
  • Sub-Account support with the Bitstamp API

    Sub-Account support with the Bitstamp API

    Now supports transfers from Bitstamp Main account to sub-account and from sub-account to main... Also the nonce is more robust (one decimal place greater)

    opened by richardsj 0
Owner
Jack Preston
twitter.com/unwttng
Jack Preston
Aws-lambda-requests-wrapper - Request/Response wrapper for AWS Lambda with API Gateway

AWS Lambda Requests Wrapper Request/Response wrapper for AWS Lambda with API Gat

null 1 May 20, 2022
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022
Python API wrapper around Trello's API

A wrapper around the Trello API written in Python. Each Trello object is represented by a corresponding Python object. The attributes of these objects

Richard Kolkovich 904 Jan 2, 2023
Async ready API wrapper for Revolt API written in Python.

Mutiny Async ready API wrapper for Revolt API written in Python. Installation Python 3.9 or higher is required To install the library, you can just ru

null 16 Mar 29, 2022
A Python API wrapper for the Twitter API!

PyTweet PyTweet is an api wrapper made for twitter using twitter's api version 2! Installation Windows py3 -m pip install PyTweet Linux python -m pip

TheFarGG 1 Nov 19, 2022
Python API wrapper library for Convex Value API

convex-value-python Python API wrapper library for Convex Value API. Further Links: Convex Value homepage @ConvexValue on Twitter JB on Twitter Authen

Aaron DeVera 2 May 11, 2022
This an API wrapper library for the OpenSea API written in Python 3.

OpenSea NFT API Python 3 wrapper This an API wrapper library for the OpenSea API written in Python 3. The library provides a simplified interface to f

Attila Tóth 159 Dec 26, 2022
YARSAW is an Async Python API Wrapper for the Random Stuff API.

Yet Another Random Stuff API Wrapper - YARSAW YARSAW is an Async Python API Wrapper for the Random Stuff API. This module makes it simpler for you to

Bruce 6 Mar 27, 2022
EpikCord.py - This is an API Wrapper for Discord's API for Python

EpikCord.py - This is an API Wrapper for Discord's API for Python! We've decided not to fork discord.py and start completely from scratch for a new, better structuring system!

EpikHost 28 Oct 10, 2022
A simple Python API wrapper for Cloudflare Stream's API.

python-cloudflare-stream A basic Python API wrapper for working with Cloudflare Stream. Arbington.com started off using Cloudflare Stream. We used the

Arbington 3 Sep 8, 2022
Discord-Wrapper - Discord Websocket Wrapper in python

This does not currently work and is in development Discord Websocket Wrapper in

null 3 Oct 25, 2022
An API wrapper around the pythonanywhere's API.

pyaww An API wrapper around the pythonanywhere's API. The name stands for pythonanywherewrapper. 100% api coverage most of the codebase is documented

null 7 Dec 11, 2022
An API Wrapper for Gofile API

Gofile2 from gofile2 import Gofile g_a = Gofile() print(g_a.upload(file="/home/itz-fork/photo.png")) An API Wrapper for Gofile API. About API Gofile

I'm Not A Bot #Left_TG 16 Dec 10, 2022
A simple API wrapper for the Tenor API

Gifpy A simple API wrapper for the Tenor API Installation Python 3.9 or higher is recommended python3 -m pip install gifpy Clone repository: $ git cl

Juan Ignacio Battiston 4 Dec 22, 2021
An API wrapper around Discord API.

NeoCord This project is work in progress not for production use. An asynchronous API wrapper around Discord API written in Python. Features Modern API

Izhar Ahmad 14 Jan 3, 2022
A wrapper for The Movie Database API v3 and v4 that only uses the read access token (not api key).

fulltmdb A wrapper for The Movie Database API v3 and v4 that only uses the read access token (not api key). Installation Use the package manager pip t

Jacob Hale 2 Sep 26, 2021
An API wrapper around the pythonanywhere's API.

pyaww An API wrapper around the pythonanywhere's API. The name stands for pythonanywherewrapper. 100% API coverage Most of the codebase is documented

null 7 Dec 11, 2022
An API wrapper for Henrik's Unofficial VALORANT API

ValorantAPI.py An API wrapper for Henrik's Unofficial VALORANT API Warning!! This project is still in beta and only contains barely anything yet. If y

Jakkaphat Chalermphanaphan 0 Feb 4, 2022