Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes from upstream #1

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ Decimal('0.00500000')
Ticker(ask=7866.27, bid=7795.00, high=7866.27, last=7866.27, low=7707.43, datetime=2016-04-22 16:46:25, vwaplow=7795.00)
>>> tick.last
Decimal('7866.27')
>>> tick.datetime
>>> tick.created_at
datetime.datetime(2016, 4, 22, 16, 46, 53)
```

Expand Down Expand Up @@ -256,7 +256,7 @@ Decimal('0.001')
## - string - 'asc' or
## - 'desc'

>>> fundings = api. fundings()
>>> fundings = api.fundings()
>>> fundings
[Funding(fid=4e28aa988a74d8b9868f400a18d00910, amount=49596.65217865, currency=mxn),
Funding(fid=3799c39ea8f1ccf6e6bbcaea1a0cbed1, amount=8.12500000, currency=btc)]
Expand Down Expand Up @@ -324,7 +324,7 @@ Decimal('7780.00')
[Order(oid=s5ntlud6oupippk8iigw5dazjdxwq5vibjcwdp32ksk9i4h0nyxsc8svlpscuov5, side=buy, price=7000.00, original_amount=0.01000000, created_datetime=2016-04-22 14:31:10)]
>>> oo[0].price
Decimal('7000.00')
>>> oo[0].order_id
>>> oo[0].oid
s5ntlud6oupippk8iigw5dazjdxwq5vibjcwdp32ksl9i4h0nyxsc8svlpscuov5

```
Expand Down Expand Up @@ -378,13 +378,13 @@ u'true' #on success
```


### Fungind Destination Address ###
### Funding Destination Address ###

```python
## Gets a Funding destination address to fund your account
## fund_currency - Specifies the currency you want to fund your account with (btc, eth, mxn)
## - str
>>> fd = api.funding_destination(''btc')
>>> fd = api.funding_destination('btc')
>>> fd
FundingDestination(account_identifier_name=Bitcoin address)
## Returns a FundingDestination object
Expand Down Expand Up @@ -606,7 +606,8 @@ if __name__ == '__main__':
listener = BasicBitsoListener()
client = websocket.Client(listener)
channels = ['trades']
client.connect(channels)
book = 'btc_mxn'
client.connect(channels, book)

```

Expand Down
30 changes: 22 additions & 8 deletions bitso/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,25 @@
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.

from __future__ import absolute_import

import hashlib
import hmac
import json
import time
import requests
from urlparse import urlparse
from urllib import urlencode
from future.utils import iteritems

try:
basestring
except NameError:
from past.builtins import basestring

try:
from urllib.parse import urlparse, urlencode
except ImportError:
from urlparse import urlparse
from urllib import urlencode


from bitso import (ApiError, ApiClientError, Ticker, OrderBook, Balances, Fees, Trade, UserTrade, Order, TransactionQuote, TransactionOrder, LedgerEntry, FundingDestination, Withdrawal, Funding, AvailableBooks, AccountStatus, AccountRequiredField)
Expand Down Expand Up @@ -66,7 +77,7 @@ class Api(object):
>>> print balance.mxn_available
"""

def __init__(self, key=None, secret=None):
def __init__(self, key=None, secret=None, timeout=0):
"""Instantiate a bitso.Api object.

Args:
Expand All @@ -81,6 +92,7 @@ def __init__(self, key=None, secret=None):
self.base_url = "https://bitso.com/api/v3"
self.key = key
self._secret = secret
self.timeout = timeout

def available_books(self):
"""
Expand Down Expand Up @@ -843,7 +855,7 @@ def transfer_create(self,
parameters['currency'] = currency
parameters['rate'] = str(rate).encode('utf-8')
parameters['payment_outlet'] = payment_outlet
for k, v in kwargs.iteritems():
for k, v in iteritems(kwargs):
parameters[k] = str(v).encode('utf-8')
resp = self._request_url(url, 'POST', params=parameters, private=True)
return TransactionOrder._NewFromJsonDict(resp['payload'])
Expand Down Expand Up @@ -895,27 +907,29 @@ def _request_url(self, url, verb, params=None, private=False):
headers=None
if params == None:
params = {}
params = {k: v.decode("utf-8") if isinstance(v, bytes) else v for k, v in params.items()}
if private:
headers = self._build_auth_header(verb, url, json.dumps(params))
if verb == 'GET':
url = self._build_url(url, params)
if private:
headers = self._build_auth_header(verb, url)
try:
resp = requests.get(url, headers=headers)
resp = requests.get(url, headers=headers, timeout=self.timeout)
except requests.RequestException as e:
raise
elif verb == 'POST':
try:
resp = requests.post(url, json=params, headers=headers)
resp = requests.post(url, json=params, headers=headers, timeout=self.timeout)
except requests.RequestException as e:
raise
elif verb == 'DELETE':
try:
resp = requests.delete(url, headers=headers)
resp = requests.delete(url, headers=headers, timeout=self.timeout)
except requests.RequestException as e:
raise
data = self._parse_json(resp.content.decode('utf-8'))
content = resp.content
data = self._parse_json(content if isinstance(content, basestring) else content.decode('utf-8'))
return data

def _build_url(self, url, params):
Expand Down
14 changes: 8 additions & 6 deletions bitso/bitsows.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

import json
import websocket
from models import StreamUpdate
from .models import StreamUpdate


class Listener(object):
Expand All @@ -49,26 +49,28 @@ def __init__(self, listener):
on_error = self._on_error,
on_close = self._on_close)
self.channels = []
self.book = None

def connect(self, channels):
def connect(self, channels, book):
self.channels = channels
self.book = book
self.ws_client.on_open = self._on_open
self.ws_client.run_forever()

def close(self):
print "received close"
print("received close")
self.ws_client.close()

def _on_close(self, ws):
print "closing connection"
print("closing connection")
self.listener.on_close()

def _on_error(self, ws, error):
print error
print(error)

def _on_open(self, ws):
for channel in self.channels:
self.ws_client.send(json.dumps({ 'action': 'subscribe', 'book': 'btc_mxn', 'type': channel }))
self.ws_client.send(json.dumps({ 'action': 'subscribe', 'book': self.book, 'type': channel }))
self.listener.on_connect()

def _on_message(self, ws, m):
Expand Down
11 changes: 8 additions & 3 deletions bitso/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,14 @@
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.

try:
basestring
except NameError:
basestring = str

from decimal import Decimal
from datetime import datetime
from decimal import Decimal
from future.utils import iteritems
import dateutil.parser


Expand Down Expand Up @@ -269,7 +274,7 @@ class WithdrawalFees(BaseModel):

def __init__(self, **kwargs):
self.currencies = []
for currency,fee in kwargs.iteritems():
for currency,fee in iteritems(kwargs):
self.currencies.append(currency)
setattr(self, currency, Decimal(fee))

Expand Down Expand Up @@ -425,7 +430,7 @@ def __init__(self, **kwargs):
setattr(self, param, value)

def __repr__(self):
return "BalanceUpdate(currency={currency}, amount={amount}".format(
return "BalanceUpdate(currency={currency}, amount={amount})".format(
currency=self.currency,
amount=self.amount)

Expand Down
3 changes: 2 additions & 1 deletion examples/livebookexample.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ def start_live_book():
listener = LiveBookListener()
client = bitso.bitsows.Client(listener)
channels = ['diff-orders', 'trades']
client.connect(channels)
book = "btc_mxn"
client.connect(channels, book)


if __name__ == '__main__':
Expand Down
7 changes: 4 additions & 3 deletions examples/ws_trades.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,18 @@

class BasicBitsoListener(Listener):
def on_connect(self):
print "Connected"
print("Connected")

def on_update(self, data):
for obj in data.updates:
print obj
print(obj)

if __name__ == '__main__':
listener = BasicBitsoListener()
client = Client(listener)
channels = ['diff-orders']
client.connect(channels)
book = "btc_mxn"
client.connect(channels, book)



Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"requests >= 2.2.1",
"websocket-client == 0.40.0",
"python-dateutil >= 1.5",
"mock >= 2.0.0"
"mock >= 2.0.0",
"future >= 0.18.2"
],
)
5 changes: 5 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
import sys
import requests

try:
basestring
except NameError:
basestring = str

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import bitso
Expand Down