Code Monkey home page Code Monkey logo

coinbasepro-python's People

Contributors

aaron235 avatar acontry avatar adamgilman avatar alimcmaster1 avatar apesti avatar arpheno avatar bianjiang avatar brianboonstra avatar bryankaplan avatar danpaquin avatar djstrasser avatar drewrice2 avatar gsmadi avatar haxorjim avatar inkblot avatar jeteon avatar lhl avatar lirenz avatar mcardillo55 avatar paulmest avatar sethfogg avatar skyl avatar squilter avatar tamersaadeh avatar thefrostyboss avatar thekeyboardkowboy avatar timkpaine avatar tobcar avatar velles avatar zrnsm 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  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

coinbasepro-python's Issues

import syntax issue

When importing the module, getting this error message:

f'B {product_id} {json.dumps(book)}\n')

associated with the orderbook

Is there an easy fix to this that I'm ignorant of?

Product historic data range

Running

hist = publicClient.get_product_historic_rates(
            'BTC-EUR',
            start='2015-07-18T14:41:12.809362',
            end='2017-07-18T14:41:12.809362',
            granularity=60)

print(hist[0][0],hist[-1][0])

1500369540 1500345720
which is 2017-07-18T14:49:00 2017-07-18T08:12:00
Shouldn't the bucket start from 2015?

websocket authentication

For which python version is your code?
I'm running python 3.4 and I get an error with this line:
sub_params['signature'] = signature_b64

TypeError: b'...=' is not JSON serializable

Therefore I added ".decode("utf-8")".

I did not use your whole project, since I'm only interested in the websocket authentication part.
My script is able to subscribe to any pair succesfully, but when I add the authentication stuff I get not a single message from gdax.

sub_params = {"type": "subscribe", "product_ids": [self.pair]}

timestamp = str(time.time())
message = timestamp + 'GET' + '/users/self'
message = message.encode('ascii')
hmac_key = base64.b64decode(self.secret)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest())
sub_params['signature'] = signature_b64.decode("utf-8")
sub_params['key'] = self.key
sub_params['passphrase'] = self.passphrase
sub_params['timestamp'] = timestamp

message_json = json.dumps(sub_params)
self.send(message_json)

without the part in the middle I get messages from websocket. But with the authentication stuff, I get nothing...
Can you imagine what the problem can be? Does the authentication works with you script? which python version?

Authenticated client: ValueError: Expecting value: line 1 column 1

Hello,
When I'm trying to connect to GDAX with the authenticated client I get this traceback:

  File "gdax_test.py", line 10, in <module>
    auth_client.get_products()
  File "/root/git/test/env/lib/python3.4/site-packages/gdax/public_client.py", line 50, in get_products
    return r.json()
  File "/root/git/test/env/lib/python3.4/site-packages/requests/models.py", line 866, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.4/json/decoder.py", line 361, in raw_decode
    raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)

The code is very simple :

import gdax

passphrase = "X"
base64 = "Y"
key = "Z"

auth_client = gdax.AuthenticatedClient(key, base64, passphrase, api_url="https://api-public.sandbox.gdax.com")
auth_client.get_products()

When I try to use the public client, I get products.

I tried with false API keys and the result is the same so I suppose one of these bugs:

  • GDAX is returning an empty response and gdax-python is trying to decode,
  • the client is not authenticated and GDAX is returning something not expected.

API guiding principles in refactoring

I just wanted to share some details of the guiding principles I'm using in refactoring the API:

  • The Python API should be similar to the official APIs.
  • The API should be Pythonic. We're improving on this front already with naming conventions. Function signatures and general flow control leave room for improvement yet.
  • The API should be self-documenting. Function signatures with appropriate variable names help explain the use to the user and are especially helpful when working in an IDE with autocomplete features. Limit arbitrary input (*args and **kwargs) to parameters that aren't necessary for typical use cases.
  • Don't allow undefined behavior. Allowing requests to be made to GDAX with parameters that don't align to their specs invites undefined behavior from GDAX (if their response simply isn't an error) which is the worst. A minimal amount of checking in the Python API can catch these situations and display informative errors. A couple examples:
    • Required parameters. If the parameter is required by the API spec, it should be required by the Python function. Easy enough to do by not specifying default parameters for those variables.
    • Mutually exclusive parameters. For market orders, you specify either size or funds which correspond to an order in BTC or USD (for example). I don't want to find out what happens when you specify both parameters at once.

OK, that's it for now. Just trying to lay out the thought process behind the large changes that I'll be pushing soon. Happy to hear any input or additional thoughts.

Updated to 1.0.6

Hello, I updated to 1.0.6 and tried your sample code:

import gdax, time
publicClient = gdax.PublicClient()
order_book = gdax.OrderBook()
order_book.start()
time.sleep(10)
order_book.close()

And keep getting the following error:

Traceback (most recent call last):
  File "./book.py", line 10, in <module>
    order_book = gdax.OrderBook()
  File "/usr/local/lib/python2.7/dist-packages/gdax/order_book.py", line 20, in __init__
    self._client = PublicClient(product_id=product_id)
TypeError: __init__() got an unexpected keyword argument 'product_id'

I also noticed that I was receiving the same error when moving a program of mine from a production system running the pre-case-changes version of the library to the up-to-date system, even after making the case changes. Any help is deeply appreciated, so thank you in advance. I am using Python 2.7.9 on Linux

Version 0.4

Recent changes have led to a situation where documentation is completely incorrect for v0.3. Because PRs are being merged into master, anyone who comes along wanting to give this thing a try is going to be frustrated. For that reason, it's important to ship v0.4 sometime very soon. When we do, let's start targeting PRs at version branches.

WebSocket: Segmentation fault: 11

Closing the WebSocket connetion results in the following error message:

Segmentation fault: 11

Pull request #95 fixes this and is a one-liner. Would be great if you could merge it!

Is this a bug or bad vendor documentation?

I am writing a new test module. Specifically, I am currently working validating the responses to make sure there are no truncation errors by creating assertions like

    def testProductTicker(self):
        results = self.publicClient.getProductTicker(product=TEST_PRODUCT_ID)

        trunc_error_message = "value has too few digits after decimal, possible truncation error"
        self.assertEqual(results['ask'][::-1].find('.'), 2, msg=trunc_error_message)
        self.assertEqual(results['bid'][::-1].find('.'), 2, msg=trunc_error_message)
        self.assertEqual(results['price'][::-1].find('.'), 8, msg=trunc_error_message)
        self.assertEqual(results['volume'][::-1].find('.'), 8, msg=trunc_error_message)

While working on .getProducts() I have come across an anomaly which I don't know if it's a bug or bad vendor documentation.

GDAX documentation indicates the response from /products will be:

[
    {
        "id": "BTC-USD",
        "base_currency": "BTC",
        "quote_currency": "USD",
        "base_min_size": "0.01",
        "base_max_size": "10000.00",
        "quote_increment": "0.01"
    }
]

Notice that "base_max_size" has 2 places after the decimal point. My test to verify that our responses also have two spaces after the decimal point is:

for result in results:
    self.assertEqual(result['base_max_size'][::-1].find('.'), 2, msg=trunc_error_message)

This test fails every time however because the actual response that GDAX.PublicClient().getProducts() returns looks like this:

[{
	"quote_currency": "GBP",
	"base_max_size": "10000",
	"id": "BTC-GBP",
	"base_currency": "BTC",
	"quote_increment": "0.01",
	"base_min_size": "0.01",
	"display_name": "BTC/GBP"
}]

Notice that "base_max_size" has no decimal point or values after it as if it was truncated.

Do you think the GDAX documentation is wrong and this response is correct? In this case, I should ditch my truncation test for "base_max_size". Alternatively, is GDAX.PublicClient().getProducts() buggy here and my test is working correctly?

How to commit new branch for tests?

Hi @danpaquin,

I wanted to commit a new branch called tests which contains a file called Tests.py containing unit tests for each method in the library. Right now it's just stubs but wanted to commit early so others can watch my progress and contribute if desired.

When I tried to commit my branch to open a WIP pull request, I receive a 403 error. I suspect I need to be authorized by you. Can you help me out with that? I don't need any rights to the master branch or any kind of admin rights. Just ability to push to a new branch and to open a pull request.

Thanks,
Reed

Docstrings

Let's get some good documentation going by adding docstrings to this package.

I'm thinking we could work with the format from Google's Python Style Guide.

def Foo(bar):
    """Does something.

    Longer explanation of how doing something can be accomplished.

    Args:
       bar: An instance of something.

    Returns:
        Something of type SomeType.

    Raises:
        BarError: An error occurred during Foo.
    """
    pass

sell() takes 1 positional argument but 2 were given

Hi all, I keep getting this error:

TypeError: sell() takes 1 positional argument but 2 were given

when I try to call sell like response = authClient.sell(request) where request is a dictionary.

The sell method looks fine, so I'm at a loss:

def sell(self, **kwargs):
        kwargs["side"] = "sell"
        r = requests.post(self.url + '/orders',
                          data=json.dumps(kwargs),
                          auth=self.auth)
        return r.json()

Pythonic Conventions, PEP 8, & Features

Hey @danpaquin are you guys open to me submitting a PR to modify some things to make this package more Pythonic and compliant with PEP 8?

I have a bunch of things I would like to change and work on but here are a few:

  • Function names should be all lowercase words seperated by underscores (so PublicClient.get_products() instead of PublicClient.getProducts()
  • Add docstrings for modules, classes, and methods.
  • Package name should be lowercase.

I also want to help develop additional features/endpoints if you guys have anything in particular you want implemented/fixed let me know and I will start working on it.

OrderBook init failed

Traceback (most recent call last):
  File "/Users/kingsfield/workspace/quant/spider/bitcoin/websocket_coinbase.py", line 37, in <module>
    order_book = gdax.OrderBook(product_id='BTC-USD')
  File "/usr/local/lib/python2.7/site-packages/gdax/order_book.py", line 20, in __init__
    self._client = PublicClient(product_id=product_id)
TypeError: __init__() got an unexpected keyword argument 'product_id'

Paginate_orders() in authenticated_client.py does not pass auth

The second page comes back with {u'message': u'CB-ACCESS-KEY header is required'}.
The following works for my use case:

     def paginate_orders(self, result, after):
-        r = requests.get(self.url + '/orders?after={}'.format(str(after)))
+        r = requests.get(self.url + '/orders?after={}'.format(str(after)), auth=self.auth)

AttributeError: 'map' object has no attribute 'index'

In OrderBook.py, there is a line that says:

index = map(itemgetter('id'), bids).index(order['order_id'])

and there is another line that does the same thing for asks.

How did this ever work? map objects do not have index attributes.
I recently received this stack trace:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib64/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib64/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/ec2-user/src/gdax/venv/src/gdax/GDAX/WebsocketClient.py", line 28, in _go
    self._listen()
  File "/home/ec2-user/src/gdax/venv/src/gdax/GDAX/WebsocketClient.py", line 59, in _listen
    self.onMessage(msg)
  File "/home/ec2-user/src/gdax/orderbook.py", line 10, in onMessage
    super().onMessage(message)
  File "/home/ec2-user/src/gdax/venv/src/gdax/GDAX/OrderBook.py", line 62, in onMessage
    self.change(message)
  File "/home/ec2-user/src/gdax/venv/src/gdax/GDAX/OrderBook.py", line 149, in change
    index = map(itemgetter('id'), bids).index(order['order_id'])
AttributeError: 'map' object has no attribute 'index'

It looks like maybe you meant to coerce the map into a list before
asking for index, But I'm really not sure.

To be honest, I find these lines to be a pretty confusing way of doing
this. They could use some explanatory comments along with the fix.

Error Handling

Error Handling is very poor with this project. Does anyone have insight on how they have their scripts to work around errors? It will allow me to integrate an error check and return for all calls that works well into the workflows of everyone.

Inconsistence in variable naming

e.g.,

productId vs. product_id
orderId vs. order_id

A lot of places in the order are without the '_', while the GDAX api parameters are all with the underscore. This is somewhat confusing, especially the recent changes on the buy and sell function that takes raw GDAX api parameters.

JSON Request Parameters' Syntax

Which do you prefer?

Hello, I would like to open the discussion and get feedback on the syntax used to make requests with this client. For the most part, functions accept named variables to package information for a given call.

Below you will see the two methods used in this client for sending information to GDAX. They are both very different approaches. Ultimately, we should remain consistent in how a user makes requests to the API. Which method should we adopt for every call? I have included examples below so please make suggestions!

Method Variables

public.getProductHistoricRates(granularity='3000')

vs.

Raw JSON

params = {
'granularity': '3000'
}
public.getProductHistoricRates(params)

import GDAX fails

This was working a wk ago, but now fails with this error, any idea?

/usr/local/lib/python2.7/dist-packages/GDAX/WebsocketClient.py in ()
10 import time
11 from threading import Thread
---> 12 from websocket import create_connection
13
14

ImportError: cannot import name create_connection

Connection is already closed error

Hello, I am receiving the following error with the latest 0.3.1 version.
Could this be cause by a connection drop?

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/GDAX/WebsocketClient.py", line 54, in _listen
msg = json.loads(self.ws.recv())
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 293, in recv
opcode, data = self.recv_data()
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 310, in recv_data
opcode, frame = self.recv_data_frame(control_frame)
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 323, in recv_data_frame
frame = self.recv_frame()
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 357, in recv_frame
return self.frame_buffer.recv_frame()
File "/usr/local/lib/python3.6/site-packages/websocket/_abnf.py", line 336, in recv_frame
self.recv_header()
File "/usr/local/lib/python3.6/site-packages/websocket/_abnf.py", line 286, in recv_header
header = self.recv_strict(2)
File "/usr/local/lib/python3.6/site-packages/websocket/abnf.py", line 371, in recv_strict
bytes
= self.recv(min(16384, shortage))
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 427, in _recv
return recv(self.sock, bufsize)
File "/usr/local/lib/python3.6/site-packages/websocket/_socket.py", line 93, in recv
"Connection is already closed.")
websocket._exceptions.WebSocketConnectionClosedException: Connection is already closed.

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.6/site-packages/GDAX/WebsocketClient.py", line 28, in _go
self._listen()
File "/usr/local/lib/python3.6/site-packages/GDAX/WebsocketClient.py", line 57, in _listen
self.close()
File "/usr/local/lib/python3.6/site-packages/GDAX/WebsocketClient.py", line 68, in close
self.thread.join()
File "/usr/local/lib/python3.6/threading.py", line 1053, in join
raise RuntimeError("cannot join current thread")
RuntimeError: cannot join current thread

.get_product_ticker() hangs forever sometimes

With the following code, sometimes .get_product_ticker() hangs forever. Probably due to bad connection?

import time

# Set a default product
publicClient = gdax.PublicClient(api_url='https://api.gdax.com')

while (True):
	# Get the product ticker for a specific product.
	btc_price = publicClient.get_product_ticker(product_id="BTC-USD")['price']
	print btc_price
	
	time.sleep(60)

Do you have any timeout set in your request?
see: http://requests.readthedocs.io/en/master/user/quickstart/#timeouts

You can tell Requests to stop waiting for a response after a given number of seconds with the timeout parameter. Nearly all production code should use this parameter in nearly all requests. Failure to do so can cause your program to hang indefinitely

May I suggest you include a default timeout of something like 30 seconds in order to prevent the possibility of the request hanging?

buy() takes exactly 1 argument

Hello,

I followed the example here #68 on how to use buy() currently.

Using

buy_params = {'price': '2560', 'size': '0.0001', 'product_id': 'BTC-USD', 'type': 'limit'}
auth_client.buy(buy_params)

I get the error

buy() takes exactly 1 argument (2 given)

RuntimeError: cannot join current thread

Running python 2.7.13 on windows 7 x64.

Running the following code gets a random crash after anywhere between 12-16 hours later.

import GDAX

class myWebsocketClient(GDAX.WebsocketClient):
	def onOpen(self):
		self.url = "wss://ws-feed.gdax.com/"
		self.products = ["BTC-USD"]
	def onMessage(self, msg):
		if 'price' in msg and 'type' in msg and msg["type"] == 'match':
			print msg['time'], float(msg['price'])

			
wsClient = myWebsocketClient()
wsClient.start()

Crash

-- Socket Closed --
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "build\bdist.win32\egg\GDAX\WebsocketClient.py", line 28, in _go
    self._listen()
  File "build\bdist.win32\egg\GDAX\WebsocketClient.py", line 57, in _listen
    self.close()
  File "build\bdist.win32\egg\GDAX\WebsocketClient.py", line 68, in close
    self.thread.join()
  File "C:\Python27\lib\threading.py", line 931, in join
    raise RuntimeError("cannot join current thread")
RuntimeError: cannot join current thread

Pagination List of List

Our documentation says that any request involving pagination will return a list of lists. Each list including one page of results. See AuthenticatedClient.get_orders() for an example. Do we actually want this behavior? My first thought while using that method would be to return a single list including all results.

I have made some changes to make these return a single list, and also to remove all of the current pagination helpers and replace them with while loops. You can see the changes on my "auth-client-cleanup" branch

I think that this matches the API spec better, and conforms to our new guiding principles. If you guys agree I will include those changes in my next PR which includes some other fixes and docstrings for AuthenticatedClient.

gdax/order_book is outdated on pypi

When installing gdax with pip, the order_book module errors on init(). The gdax/order_book init() method on github solves this issue.

order_book = gdax.OrderBook() File "/usr/local/lib/python3.5/dist-packages/gdax/order_book.py", line 20, in __init__ self._client = PublicClient(product_id=product_id) TypeError: __init__() got an unexpected keyword argument 'product_id'

get_product_historic_rates is fetching data outside the time frame for 60s granularity

Hi I have encountered a very strange behaviour.

I am almost sure that it is not the problem of the python GDAX library, but I want to be sure that it is not only my problem before I report it.

This is the code running with gdax installed from master

import gdax
import datetime

product = "{}-{}".format("BTC", "EUR")
publicClient = gdax.PublicClient()
unit = 60
ten_min = datetime.timedelta(minutes=10)
now = datetime.datetime.now()
start = now - ten_min
print((now - start).seconds / unit)
print(now.isoformat())
print(start.isoformat())
hist = publicClient.get_product_historic_rates(
            product,
            start=start.isoformat(),
            end=now.isoformat(),
            granularity=unit)
print(datetime.datetime.fromtimestamp(int(hist[0][0])).isoformat())
print(datetime.datetime.fromtimestamp(int(hist[-1][0])).isoformat())
print(len(hist))

It should return 10 candles from last 10 minutes, but it returns 395 candles from several hours.

10.0
2017-06-19T19:40:51.551975
2017-06-19T19:30:51.551975
2017-06-19T19:39:00
2017-06-19T13:00:00
395

When I changed the granularity to 61 the output looks exactly as expected

9.836065573770492
2017-06-19T19:41:33.666923
2017-06-19T19:31:33.666923
2017-06-19T19:40:38
2017-06-19T19:31:29
10

Can anybody please confirm this behaviour?

add rate limit (by default)

The GDAX API specifies request rate limits as seen below. As far as I could tell this project doesn't limit request rates. I've been using https://github.com/s4w3d0ff/python-poloniex and really like how they have a couch to limit requests by default, see https://github.com/s4w3d0ff/python-poloniex/blob/master/poloniex/__init__.py#L122 and https://github.com/s4w3d0ff/python-poloniex/blob/master/poloniex/coach.py#L26-L47 .

https://docs.gdax.com/#rate-limits

When a rate limit is exceeded, a status of 429 Too Many Requests will be returned.
REST API
PUBLIC ENDPOINTS
We throttle public endpoints by IP: 3 requests per second, up to 6 requests per second in bursts.
PRIVATE ENDPOINTS
We throttle private endpoints by user ID: 5 requests per second, up to 10 requests per second in bursts.
FINANCIAL INFORMATION EXCHANGE API
The FIX API throttles each command type (eg.: NewOrderSingle, OrderCancelRequest) to 30 commands per second.

AttributeError: module 'GDAX' has no attribute 'PublicClient'

I have installed GDAX (pip install GDAX). When I try to import GDAX in Python, I get the below error. Any help would be greatly appreciated. I'm using a Mac if that makes a difference. Thanks!

In [1]: import GDAX
Traceback (most recent call last):

File "ipython-input-1-bbe99608e9f3", line 1, in module
import GDAX

File "/Users/btc/GDAX.py", line 3, in
publicClient = GDAX.PublicClient()

AttributeError: module 'GDAX' has no attribute 'PublicClient'

Misplacement of % in the basic myWebsocketClient in WebsocketClient

In the myWebsocketClient template class in GDAX.WebsocketClient:

print ("\nMessageCount =", "%i \n") % wsClient.MessageCount
The above line causes the type error below.

TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

It should be:
print ("\nMessageCount =", "%i \n" % wsClient.MessageCount)

AttributeError: 'AuthenticatedClient' object has no attribute 'cryptoWithdraw'

I am getting the above error:

AttributeError: 'AuthenticatedClient' object has no attribute 'cryptoWithdraw'

I am wondering if this is on my end or yours. It seems to be a problem on your end?
I am calling this method from AuthenticatedClient:

def cryptoWithdraw(self, amount="", currency="", crypto_address=""):
        payload = {
            "amount": amount,
            "currency": currency,
            "crypto_address": crypto_address
        }
        r = requests.post(self.url + "/withdrawals/crypto", data=json.dumps(payload), auth=self.auth)
        # r.raise_for_status()
        return r.json()

Methods such as buy are working for me.

inconsistent realtime orderbook

Hi :)

it is really difficult or maybe inpossible to have a correct orderbook with this type of websocket..
I already wrote my own solution to build an orderbook with the websocket feed, but after some time it gets inconsistent (bid > ask).

Therefore I tried now your solution.
But again after some time best bid > best ask =/
(I used your code from order_book.py, but my own websocket client, basically ws4py module)

But I still don't know if it is just our code that is not good, or if it is the websocket feed that is faulty =/

All in all I think this "changes"-websocket orderbook feed (where websocket only send changes) is rubbish for trading. Every exchange should instead send sth like best 20 bids/asks per second. This way it is always consistent...

Version 0.3 from PyPi not working

I just installed version 0.3 from PyPi and it's not working because it includes a git conflict in WebsocketClient.py

if __name__ == "__main__":
    import GDAX, time
    class myWebsocketClient(GDAX.WebsocketClient):
        def onOpen(self):
            self.url = "wss://ws-feed.gdax.com/"
            self.products = ["BTC-USD", "ETH-USD"]
            self.MessageCount = 0
            print ("Lets count the messages!")

        def onMessage(self, msg):
            print ("Message type:", msg["type"], "\t@ %.3f" % float(msg["price"
]))
            self.MessageCount += 1

        def onClose(self):
            print ("-- Goodbye! --")

    wsClient = myWebsocketClient()
    wsClient.start()
    print(wsClient.url, wsClient.products)
    # Do some logic with the data
    while (wsClient.MessageCount < 500):
<<<<<<< HEAD
        print ("\nMessageCount =", "%i \n" % wsClient.MessageCount)
=======
        print("\nMessageCount =", "%i \n" % wsClient.MessageCount)
>>>>>>> e5d2bb8d930db1ddf64ab446467845a41f0ab5cd
        time.sleep(1)
    wsClient.close()

I'm using Python 3.5 with a freshly created virtualenv.

getProductHistoricRates not responding to start=, end=

When looking at the official documentation of GDAX, the getProductHistoricRates takes arguments start, end and granularity. However only the latter one seems to work. Whenever using start or end it just returns the latest result from the server.

Any thoughts to why?

Deposit doesn't take JSON, requires currency.

I'm seeing a few issues with the AuthenticatedClient.deposit() method.

  1. The docs say it takes its args in a Dict, but the method requires keywords.
  2. Currency types aren't inferred; calling deposit with amount and payment_method_id returns currency is required.
  3. Calling deposit on a coinbase_account_id instead of payment_method_id gives us an unexpected keyword error.
  4. Passing in the payment_method_id for my USD wallet yields: ValueError: No JSON object could be decoded. Passing an ACH bank account yields a good deposit.

AttributeError: 'myWebsocketClient' object has no attribute 'start'

Following the readme.md:

import GDAX, time
class myWebsocketClient(GDAX.WebsocketClient):
    def onOpen(self):
        self.MessageCount = 0
        print "Lets count the messages!"
    def onMessage(self, msg):
        print "Message type:", msg["type"], "\t@ %.3f" % float(msg["price"])
        self.MessageCount += 1
    def onClose(self):
        print "-- Goodbye! --"

wsClient = myWebsocketClient()
wsClient.start()
# Do some logic with the data
while (wsClient.MessageCount < 500):
    print "\nMessageCount =", "%i \n" % wsClient.MessageCount
    time.sleep(1)
wsClient.close()

Gives error:

  File "myscript.py", line 90, in <module>
    wsClient.start()
AttributeError: 'myWebsocketClient' object has no attribute 'start'

environment:

GDAX==0.2.0
numpy==1.12.1
pandas==0.19.2
python-dateutil==2.6.0
pytz==2016.10
requests==2.13.0
six==1.10.0
websocket-client==0.40.0

shell$ python --version
Python 3.5.2 :: Continuum Analytics, Inc.

Python Crashes at the end of websocket Implementation

I have noticed that "python crashed. windows is collecting information" constantly in Windows environment.
The program perfectly finishes and says goodbye, then python crashes with exit code 255
same crash on both 2.7 and 3.6

I modified the code a bit to avoid tihs error,

def onMessage(self, msg):
    print("Message type:", msg)
    self.MessageCount += 1
    if(self.MessageCount >= 100):
    	exit()

The last 2 lines are added in my program and it solved the issue.

Websocket closes

Hi,

When I use the websocket, it stops receiving data after three or four hours. It doesn't raise an error. It doesn't report "Socket Closed" or anything. It just stops receiving data. I don't know if this is an issue of the GDAX API or an issue of gdax-python.

Accept pull requests for test module?

Hi @danpaquin,

Would you accept a pull request for a suite of unit tests? It seems that sense people are using this library to trade money, there should be a baseline set of tests. I would like to put these together.

With your go-ahead, I would expect to work on this over the next 3-4 weeks.

Test scripts incomplete

Within the development branch you will find test scripts for the private client. Before committing these to master, we will need test scripts for every function of this project.

Binary floating point arithmetic

OrderBook.py coerces numeric strings to floats in a variety of places. This is a problem because it changes the numbers. A better solution would be better to use decimal.

I would issue a PR to make this change myself, but OrderBook.py exists in the master branch, not in the development branch.

Buy & sell orders fail with "got an unexpected keyword argument"

Thank you for the work you do on this package.

Successful

auth_client.getAccounts()

Not successful

auth_client.buy(price='2560.00', size='0.01', product_id='BTC-USD')
Traceback (most recent call last):
File "", line 1, in
TypeError: buy() got an unexpected keyword argument 'price'
auth_client.sell(price='2560', #USD
... size='0.0001', #BTC
... product_id='BTC-USD')
Traceback (most recent call last):
File "", line 3, in
TypeError: sell() got an unexpected keyword argument 'price'

AttributeError: 'AuthenticatedClient' object has no attribute 'cancelAll'

authClient.cancelAll() doesn't seem to be working.

Any ideas?

import GDAX

authClient = GDAX.AuthenticatedClient(api_key, secret, passphrase, product_id="BTC-USD")

authClient.cancelAll()
Traceback (most recent call last):
  File "C:/PythonApps/gdax/run.py", line 42, in <module>
    authClient.cancelAll()
AttributeError: 'AuthenticatedClient' object has no attribute 'cancelAll'

Very willing to believe that this is something I am doing wrong but still can't figure out what it might be. I do see that AuthenticatedClient.cancelAll() exists in AuthenticatedClient.py.

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.