Git Product home page Git Product logo

python-kucoin's People

Contributors

amirmehdi avatar danieldourado avatar deforation avatar ericwclymer avatar marcelbeining avatar mehdiirh avatar nielskool avatar samjosephmark avatar sammchardy avatar snoozetime 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

python-kucoin's Issues

Python doesnt recognize the module; ModuleNotFoundError

I tried to follow the following steps: http://python-kucoin.readthedocs.io/en/latest/overview.html#initialise-the-client . My pip install looks fine. Yet when I run the code I get the error : "ModuleNotFoundError: No module named 'kucoin.client'; 'kucoin' is not a package"

I am no expert here, sorry if I ask a basic question, but could you help me out getting your module to be recognized by my python?

Just checked out your binance module. That one does work! Makes me more confused.

Getting weird results when trying to create buy orders?

Trying to create a very simple buy on Kucoin

 order = kucoin.create_buy_order("NEO-BTC", 0.00930911, 0.5)
 print(order)

This would not place the order, and I would get.

{'coinType': 'BTC', 'expect': 0.00465456, 'actual': 0.00146454}

as a response.

Originally I thought the issue had to do with precision size, and I tried accounting for that in both my rate and my amount, which did not work.

However, if I try placing an order on a coin which I can buy a full value of (Don't have funds for a full NEO ATM)

        order = kucoin.create_buy_order("PBL-BTC", 0.00018314, 1)

Everything works great, order is placed.

However, if I were to buy less or more than 1 coin, such as 1.1 or .99,
my order becomes "None", and no other output is available. Other times it will spit out the error like the one I provided above.

Any ideas?

No Timestamp

Dear all

After connection to the API, client.get_last_timestamp() return None

But other commands are working well.
Any other idea to get the server timestamp ?

Can't use get_total_balance method

When I am trying to get total balance, I am getting that error
File "C:\Users\User\Desktop\venv\myvenv\lib\site-packages\kucoin\client.py", line 1003, in get_total_balance
coins_csl = ','.join([b['coinType'] for b in balances])
File "C:\Users\User\Desktop\venv\myvenv\lib\site-packages\kucoin\client.py", line 1003, in
coins_csl = ','.join([b['coinType'] for b in balances])
TypeError: string indices must be integers

UNAUTH: Signature Verification Failed

Thank you for writing this package, it's great.

I am running into an issue when trying to use certain order cancellation functions. Cancel_all_orders alone works well.

I run into issues when adding a symbol parameter to the function (ie. 'NULS-ETH') or when using the cancel_order function.

Traceback (most recent call last):
  File "C:/Users/tyler/Google Drive/Crypto/python/kucoin_order.py", line 52, in <module>
    client.cancel_all_orders(symbol=buy_pair)
  File "C:\Python27\lib\site-packages\kucoin\client.py", line 1295, in cancel_all_orders
    return self._post(path, True, data=data)
  File "C:\Python27\lib\site-packages\kucoin\client.py", line 171, in _post
    return self._request('post', path, signed, **kwargs)
  File "C:\Python27\lib\site-packages\kucoin\client.py", line 138, in _request
    return self._handle_response(response)
  File "C:\Python27\lib\site-packages\kucoin\client.py", line 147, in _handle_response
    raise KucoinAPIException(response)
kucoin.exceptions.KucoinAPIException: KucoinAPIException UNAUTH: Signature verification failed

TypeError: __init__() got an unexpected keyword argument 'sandbox'

Hi there,
I was using older version and updated my environments due to use new version but I am getting this error for now. I couldn't recognize where is my fault. Also i created new sandbox api.

Error:
TypeError: init() got an unexpected keyword argument 'sandbox'

Python v=3.6.6

My codes:

api_key = "my_api_key"
api_secret = "my_api_secret"
api_passphrase = "my_api_passphrase"

from kucoin.client import Client
client = Client(api_key, api_secret, api_passphrase, sandbox=True)

currencies = client.get_currencies()
print(currencies)

KucoinAPIException 400005: Invalid KC-API-SIGN

I printed out the kwargs right before the request is sent to the exchange. It is missing required keys/values. This is what the kwargs are as of line 156 in client.py:
KWARGS: {'timeout': 10, 'headers': {'KC-API-TIMESTAMP': '11111111111111', 'KC-API-SIGN': b'xxxxxxxxxxxxxxxxxxxxx'}, 'params': {'status': 'SUCCESS', 'startAt': '0', 'limit': 100}}

According to https://docs.kucoin.com/#creating-a-request all these values are required:
KC-API-KEY
KC-API-SIGN
KC-API-TIMESTAMP
KC-API-PASSPHRASE

It looks like the session headers aren't being utilized after Client instantiation.

Unable to subscribe to more than 21 orderbooks

Hi,

I'm currently trying out the latest websockets implementation, it seems that no matter how slowly I try to subscribe to the level2 orderbook streams I always get an exception thrown saying the connection has been closed when trying to subscribe to more than 21 orderbooks. Has anyone else been able to successfully subscribe to all orderbooks on the exchange using this wrapper?

I get the following:
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1000 (OK), no reason

KucoinAPIException UNAUTH: Invalid nonce when executing certain commands

Hello there,

I am receiving a KucoinAPIException whenever I try to execute certain commands; other commands, like get_languages() or get_historical_klines_tv() work fine.

I created a simple script:

 from kucoin.client import Client
 from kucoin.exceptions import KucoinAPIException
 
 try:
 	client = Client(API_KEY, SECRET_KEY)
 	clientLanguages = client.get_languages()
 	print(clientLanguages)
 	clientActiveOrders = client.get_active_orders('KCS-BTC', True)
 	print(clientActiveOrders)
 except KucoinAPIException as e:
 	print('your exception was due to {}'.format(e) )
 	print('error code {}'.format(e.code) )  # UNAUTH
 	print('error message {}'.format(e.message) )  # Not Found

This returns the following output:

[['en_US', 'English', True], ['ru_RU', 'русский', True], ['ko_KR', '한국어', True], ['ja_JP', '日本語', True], ['pt_PT', 'Portugues', True], ['zh_CN', '中文简体', True], ['nl_NL', 'Nederlands', True], ['zh_HK', '中文繁体', True], ['de_DE', 'Deutsch', True], ['fr_FR', 'Français', True], ['es_ES', 'Español', True]]
your exception was due to KucoinAPIException UNAUTH: Invalid nonce
error code UNAUTH
error message Invalid nonce

So the first command is executing fine, but the second one is not...
Anyone can tell me what I am doing incorrectly?

Thanks in advance!

Api limit

Hey, is the api rate limit accurate? I don't see it anywhere in the kucoin official documents. Thanks

how to show amount of withdrawal

i used function of get_withdrawals('KCS')
But it was not show amount
Just i see these results.
{'total': 0, 'firstPage': True, 'lastPage': False, 'datas': [], 'currPageNo': 1, 'limit': 12, 'pageNos': 1}
I couldn't see amount.
I'll be waiting for the reply.
Finally, thank you for writing a good code.

Can't withdraw using the API

print(kucoin.create_withdrawal('BTC', amount, 'address'))

I just used this code will correct API keys and it raises the kucoin.exceptions.KucoinAPIException: KucoinAPIException : b''

Lots of missing data from Kucoin

I am getting a lot of None data from kucoin, some times for several minutes, is this a kucoin bug?

ts = time.time()

 kline = self.kucoin_client.get_kline_data_tv(self.pair_code, Client.RESOLUTION_1MINUTE, int(ts-60), int(ts))

data = {'t': kline[0], 'o': kline[1], 'c': kline[4], 'h': kline[2], 'l': kline[3], 's': self.pair_code}
print(data)`

gives a lot of this:

{'t': 1518064740, 'o': None, 'c': None, 'h': None, 'l': None, 's': 'BTC-USDT'}
{'t': 1518064800, 'o': None, 'c': None, 'h': None, 'l': None, 's': 'BTC-USDT'}
{'t': 1518064860, 'o': 8116.5, 'c': 8119.0, 'h': 8119.0, 'l': 8116.5, 's': 'BTC-USDT'}
{'t': 1518064920, 'o': None, 'c': None, 'h': None, 'l': None, 's': 'BTC-USDT'}
{'t': 1518064980, 'o': 8120.500006, 'c': 8119.1, 'h': 8125.0, 'l': 8119.1, 's': 'BTC-USDT'}

[V2] Invalid query string param ordering for signature

As of KuCoin API v2, the query string parameters used in signature generation should be ordered as specified in docs and not alphabetically.

Essentially the sorted() function call here is incorrect:

for key in sorted(data):

To reproduce:

from kucoin.client import Client

client = Client('<key>', '<secret>', '<passphrase>')
client.get_orders(status='done', symbol='ETH-BTC')

Funds stolen

Someone made a withdrawal order 1 hour after I installed library and started using it. PC is clean, nothing else on it has ever been touched

Request. Level 3 MatchEngine

Hi,

First of all, great library. I've been using it for quite some time now.
The new Kucoin API offers level 3 MatchEngine which I could use very much. So my question is, do you have any plans on implementing this? I might consider looking into your code and try to implement it myself.

source: https://docs.kucoin.com/#match-execution-data

ReconnectingWebsocket is not reconnecting

Hi there,
I have the issue that the websocket seems to be closed after approx 60 seconds.
I subscribed to a 3 tickers and my callback function informs me when it was not called for at least 15 sec. The first minute everything works fine, but then I do not receive messages anymore from the websocket. When I then run ksm.unsubscribe for my tickers, I get:

  File "C:/Users/xxxxxxxxxx", line 307, in kunsubscribe
    await self.ksm.unsubscribe('/market/ticker:ETH-BTC')

  File "C:\ProgramData\Anaconda3\lib\site-packages\kucoin\asyncio\websockets.py", line 239, in unsubscribe
    await self._conn.send_message(req_msg)

  File "C:\ProgramData\Anaconda3\lib\site-packages\kucoin\asyncio\websockets.py", line 133, in send_message
    await self._socket.send(json.dumps(msg))

  File "C:\ProgramData\Anaconda3\lib\site-packages\websockets\protocol.py", line 361, in send
    yield from self.ensure_open()

  File "C:\ProgramData\Anaconda3\lib\site-packages\websockets\protocol.py", line 501, in ensure_open
    self.close_code, self.close_reason) from self.transfer_data_exc

ConnectionClosed: WebSocket connection is closed: code = 1006 (connection closed abnormally [internal]), no reason

This error does not appear when I unsubscribe from the websocket before the 1 minute has passed.
So altogether it seems the ReconnectingWebsocket class you created does not reconnect in this case as the Websocket connection is down according to the error. Any idea what is wrong?

Cancel order stopped working: "Signature verification failed"

*Windows 10
*Python 3.6.4
*I tried both python-kucoin v0.1.8 and v0.1.7

The API and the Client library is working for me in everything except any functions for cancelling orders which started failing last night (before that they were working fine as well). The error I keep getting is "Signature verification failed". Also today briefly, for a few hours, the cancel order functions started working again (!), without me changing anything in my code.

I tried using cancel_order or cancel_all_orders in many different ways, providing symbol or order type only, providing order_id etc. Nothing helped.
Is this some issue on the Kucoin side or is there something we could do? Did Kucoin change anything?

It's strange how everything works except the cancel order calls...

Difference between "type" and "direction"

Hello, when i get my orders, i have those two informations, "type" and "direction". They are basically the same everytime, if one is SELL the other one would be also SELL and same for BUY. What is the difference between both ? Thanks !

cancel_withdrawal() giving a 'Method Not Allowed' error

Have you been able to use the cancel_withdrawal() method successfully? When I run it it gives a me this error:

kucoin.exceptions.KucoinAPIException: KucoinAPIException : Method Not Allowed

Also which tx id should be passed as an argument? I'm currently trying to cancel a pending withdrawal and when I view it with get_withdrawals() there is a outerWalletTxid property and an oid property. Is outerWalletTxid the argument to pass to cancel_withdrawal()?

get_recent_orders should actually be get_recent_trades

get_recent_orders in the python-kucoin library points towards the endpoint

"GET https://api.kucoin.com/v1/open/deal-orders"

deal-orders is actually the trades. (The orders that became deals).

I did some testing and this is true.

I bought 10 PRL and a qty 10 trade for 10PRL appeared. I put out an order for 10PRL at an outrageous price and nothing appeared

here is a screenshot comparing data i got from the endpoint to the recent trades on the kucoin site

https://i.imgur.com/K07gZxK.png

List all active orders for all Symbols

Is there a way to get all active orders for any symbol? Doesn't seem obvious from the KuCoin API docs but the website itself has a page (Assets->Active Orders) which shows all orders. Am I missing something or is this not possible from the API?

nm

fixed nm

client.get_order_details not working

Unfortunately there are several issues with the get_order_details method:

  1. could not find the method in your documentation
  2. From your code comments I extracted that the order id would be optional, but then the API responds "KucoinAPIException : Bad Request - Required String parameter 'orderOid' is not present" , so I guess it is not optional anymore
  3. adding the order_id to the input arguments (symbol,order_type and order_id) does not give an error, but it also does not return anything (None). The order id and everything is correct and I tried it for different orders and symbols.

Thanks for having made that python wrapper!

Timeout for requests

I've had an issue with a request for the get_trading_symbols() causing my script to get stuck with no error code or anyway to break the run. I noticed this same behavior with a Bittrex wrapper I was using and changed the request call to include a timeout. I noticed this wrapper does not include the timeout in the request call but the Binance one does. Is there a specific reason for not including the timeout in this call? Exact line I'm referring to is in client.py:

response = getattr(self.session, method)(uri, **kwargs)

Changed to:
response = getattr(self.session, method)(uri, timeout=10, **kwargs)

Unable to auth API

Hey Guys,

My bot has worked for a long time; however, in the past few weeks I haven't used it, ran it again and received an auth error, I've also updated my API key without success.

Anyone have any idea whether there has been an update with the Kucoin API causing issues?

raceback (most recent call last):
File "Z:\06. Programming Projects\00_02_CryptoBots\python-kucoin-develop\tradingbot.py", line 34, in
option1.getbalance()
File "Z:\06. Programming Projects\00_02_CryptoBots\python-kucoin-develop\option1.py", line 12, in getbalance
pprint.pprint(client.get_coin_balance('DENT'))
File "Z:\06. Programming Projects\00_02_CryptoBots\python-kucoin-develop\kucoin\client.py", line 944, in get_coin_balance
return self._get('account/{}/balance'.format(coin), True)
File "Z:\06. Programming Projects\00_02_CryptoBots\python-kucoin-develop\kucoin\client.py", line 177, in _get
return self._request('get', path, signed, **kwargs)
File "Z:\06. Programming Projects\00_02_CryptoBots\python-kucoin-develop\kucoin\client.py", line 147, in _request
return self._handle_response(response)
File "Z:\06. Programming Projects\00_02_CryptoBots\python-kucoin-develop\kucoin\client.py", line 161, in _handle_response
raise KucoinAPIException(response)
kucoin.exceptions.KucoinAPIException: KucoinAPIException UNAUTH: Invalid API Key
Press any key to continue . . .

Regards
Chris

[V2] Incorrect keys to place orders

Placing orders does not work for me.
There appear to be some inconsistencies between the code and the API docs (https://docs.kucoin.com/#place-a-new-order)

  • The endpoint should be '/api/v1/orders' but in the code it is currently '/api/v1/order'
  • The body should contain "clientOid" and "size" instead of "orderOid" and "amount", respectively

However, even when doing these changes locally, I get a 401 error with b'{"code":"400005","msg":"Invalid KC-API-SIGN"}'. There appears to be some other problem elsewhere, but I couldn't find what.

Documentation Issue: Limit order returns 'orderId' not 'orderOid'

Minor issue but the comments for the create_limit_order() function state the function returns "orderOid":

.. code:: python
order = client.create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000')
:returns: ApiResponse
.. code:: python
{
"orderOid": "596186ad07015679730ffa02"
}
:raises: KucoinResponseException, KucoinAPIException, LimitOrderException
"""

but after running the code, the buy_response I'm getting appears to be returning "orderId"

502 Bad Gateway response leads to KucoinAPIException, not KucoinRequestException

Traceback (most recent call last):
File "My file which calls get_all_balances",
result = ku_api.get_all_balances()
File "/usr/local/lib/python3.5/dist-packages/kucoin/client.py", line 975, in get_all_balances
return self._get('account/balance', True, data=data)
File "/usr/local/lib/python3.5/dist-packages/kucoin/client.py", line 177, in _get
return self._request('get', path, signed, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/kucoin/client.py", line 147, in _request
return self._handle_response(response)
File "/usr/local/lib/python3.5/dist-packages/kucoin/client.py", line 156, in _handle_response
raise KucoinAPIException(response)
kucoin.exceptions.KucoinAPIException: KucoinAPIException :
b'\r\n<title>502 Bad Gateway</title>\r\n\r\n

502 Bad Gateway

\r\n\r\n\r\n'

It seems like 502 Bad Gateway response has to raise KucoinRequestException since it is not a valid json format. I wrote a code to print out error code and error message when KucoinAPIException has been raised.

The following is how I handle KucoinAPIException

errormsg = 'KU API error with code: ' + str(e.status_code) + ' msg: ' + e.message

And at this time, it raises TypeError remarks that I cannot convert bytes to str implicitly.

Invalid nonce since 2 days ago.

I have this trouble about two days. With simlple code get_coin_balance or get_active_orders I get a message 'code: ''UNAUTH', msg: 'Invalid nonce', success: ''False", timestamp: '1522315377283'.
I tried 'import os' or synchronized my PC time with web - no good result.
Yesterday this code worked. Please help.
Should I ise def'generate_signature' or def_request in my code?

get_coin_balance

Hello

When I try to use get_coin_balance or get_coin_address, I get a 'missing 1 required positional argument: 'coin'. An idea why ?

Thanks

    print(kucoinClient.get_coin_balance('NEO'))
TypeError: get_coin_balance() missing 1 required positional argument: 'coin'

Websockets variable declaration

I run python 3.5.2

When I try to use the websocket features it raises an error at:
MAX_RECONNECTS: int = 5

Is there something I need for python to allow for such variable declarations?

//edit
On windows python version 3.6.2 it works.
Ubuntu doesn't have the newer python version in their standard packages (yet).
Trying to get python through other means on the ubuntu server, but websockets import is not comming through then....

//edit2
I ended up changing all the newer python syntax of asyncio/websockets.py

import asyncio
import json
import logging
import time
from random import random
from typing import Dict, Callable, Awaitable, Optional

import websockets as ws

from kucoin.client import Client


class ReconnectingWebsocket:

    MAX_RECONNECTS = 5
    MAX_RECONNECT_SECONDS = 60
    MIN_RECONNECT_WAIT = 0.1
    TIMEOUT = 10
    PROTOCOL_VERSION = '1.0.0'

    def __init__(self, loop, client: Client, coro, private: bool = False):
        self._loop = loop
        self._log = logging.getLogger(__name__)
        self._coro = coro
        self._reconnect_attempts = 0
        self._conn = None
        self._ws_details = None
        self._connect_id = None
        self._client = client
        self._private = private
        self._socket = None

        self._connect()

    def _connect(self):
        self._conn = asyncio.ensure_future(self._run())

    async def _run(self):

        keep_waiting = True

        # get the websocket details
        self._ws_details = None
        self._ws_details = self._client.get_ws_endpoint(self._private)

        async with ws.connect(self._get_ws_endpoint(), ssl=self._get_ws_encryption()) as socket:
            self._socket = socket
            self._reconnect_attempts = 0

            try:
                while keep_waiting:
                    try:
                        evt = await asyncio.wait_for(self._socket.recv(), timeout=self._get_ws_pingtimeout())
                    except asyncio.TimeoutError:
                        self._log.debug("no message in {} seconds".format(self._get_ws_pingtimeout()))
                        await self.send_ping()
                    except asyncio.CancelledError:
                        self._log.debug("cancelled error")
                        await self._socket.ping()
                    else:
                        try:
                            evt_obj = json.loads(evt)
                        except ValueError:
                            pass
                        else:
                            await self._coro(evt_obj)
            except ws.ConnectionClosed:
                keep_waiting = False
                await self._reconnect()
            except Exception as e:
                self._log.debug('ws exception:{}'.format(e))
                keep_waiting = False
                await self._reconnect()

    def _get_ws_endpoint(self) -> str:
        if not self._ws_details:
            raise Exception("Unknown Websocket details")

        self._ws_connect_id = str(int(time.time() * 1000))
        token = self._ws_details['token']
        endpoint = self._ws_details['instanceServers'][0]['endpoint']

        #ws_endpoint = f"{endpoint}?token={token}&connectId={self._ws_connect_id}"
        ws_endpoint = "%s?token=%s&connectId=%s" %(endpoint, token, self._ws_connect_id)
        return ws_endpoint

    def _get_ws_encryption(self) -> bool:
        if not self._ws_details:
            raise Exception("Unknown Websocket details")

        return self._ws_details['instanceServers'][0]['encrypt']

    def _get_ws_pingtimeout(self) -> int:

        if not self._ws_details:
            raise Exception("Unknown Websocket details")

        ping_timeout = int(self._ws_details['instanceServers'][0]['pingTimeout'] / 1000) - 1
        return ping_timeout

    async def _reconnect(self):
        await self.cancel()
        self._reconnect_attempts += 1
        if self._reconnect_attempts < self.MAX_RECONNECTS:

            #self._log.debug(f"websocket reconnecting {self.MAX_RECONNECTS - self._reconnect_attempts} attempts left")
            self._log.debug("websocket reconnecting %s attempts left") %(self.MAX_RECONNECTS - self._reconnect_attempts)
            reconnect_wait = self._get_reconnect_wait(self._reconnect_attempts)
            await asyncio.sleep(reconnect_wait)
            self._connect()
        else:
            # maybe raise an exception
            #self._log.error(f"websocket could not reconnect after {self._reconnect_attempts} attempts")
            self._log.error("websocket could not reconnect after %s attempts") %(self._reconnect_attempts)
            pass

    def _get_reconnect_wait(self, attempts: int) -> int:
        expo = 2 ** attempts
        return round(random() * min(self.MAX_RECONNECT_SECONDS, expo - 1) + 1)

    async def send_ping(self):
        msg = {
            'id': str(int(time.time() * 1000)),
            'type': 'ping'
        }
        await self._socket.send(json.dumps(msg))

    async def send_message(self, msg, retry_count=0):
        if not self._socket:
            if retry_count < 5:
                await asyncio.sleep(1)
                await self.send_message(msg, retry_count + 1)
        else:
            msg['id'] = str(int(time.time() * 1000))
            msg['privateChannel'] = self._private
            await self._socket.send(json.dumps(msg))

    async def cancel(self):
        try:
            self._conn.cancel()
        except asyncio.CancelledError:
            pass


class KucoinSocketManager:

    def __init__(self):
        """Initialise the IdexSocketManager

        """
        #self._callback: Callable[[int], Awaitable[str]]
        self._conn = None
        self._loop = None
        self._client = None
        self._private = False
        self._log = logging.getLogger(__name__)

    @classmethod
    async def create(cls, loop, client: Client, callback: Callable[[int], Awaitable[str]], private: bool = False):
        self = KucoinSocketManager()
        self._loop = loop
        self._client = client
        self._private = private
        self._callback = callback
        self._conn = ReconnectingWebsocket(loop, client, self._recv, private)
        return self

    async def _recv(self, msg: Dict):
        if 'data' in msg:
            await self._callback(msg)

    async def subscribe(self, topic: str):
        """Subscribe to a channel

        :param topic: required
        :returns: None

        Sample ws response

        .. code-block:: python

            {
                "type":"message",
                "topic":"/market/ticker:BTC-USDT",
                "subject":"trade.ticker",
                "data":{
                    "sequence":"1545896668986",
                    "bestAsk":"0.08",
                    "size":"0.011",
                    "bestBidSize":"0.036",
                    "price":"0.08",
                    "bestAskSize":"0.18",
                    "bestBid":"0.049"
                }
            }

        Error response

        .. code-block:: python

            {
                'code': 404,
                'data': 'topic /market/ticker:BTC-USDT is not found',
                'id': '1550868034537',
                'type': 'error'
            }

        """

        req_msg = {
            'type': 'subscribe',
            'topic': topic,
            'response': True
        }

        await self._conn.send_message(req_msg)

    async def unsubscribe(self, topic: str):
        """Unsubscribe from a topic

        :param topic: required

        :returns: None

        Sample ws response

        .. code-block:: python

            {
                "id": "1545910840805",
                "type": "ack"
            }

        """

        req_msg = {
            'type': 'unsubscribe',
            'topic': topic,
            'response': True
        }

        await self._conn.send_message(req_msg)

Client Class

Can we please change the class name of "Client" to "KucoinClient" so that if someone is using your other libraries (like your binance library) in a single python application that the program can differentiate from the two? Otherwise the program terminates with error codes

UNAUTH: Invalid nonce

Since today's morning I just keep getting this errors. For example, when I am trying to cancel order I have got this
Traceback (most recent call last):
File "test.py", line 23, in
client.cancel_order(transaction['orderOid'], Client.SIDE_BUY, 'ETH-BTC')
File "C:\Users\roofu\Desktop\Bot\myvenv\lib\site-packages\kucoin\client.py", line 1313, in cancel_order
return self._post('cancel-order', True, data=data)
File "C:\Users\roofu\Desktop\Bot\myvenv\lib\site-packages\kucoin\client.py", line 180, in _post
return self._request('post', path, signed, **kwargs)
File "C:\Users\roofu\Desktop\Bot\myvenv\lib\site-packages\kucoin\client.py", line 147, in _request
return self._handle_response(response)
File "C:\Users\roofu\Desktop\Bot\myvenv\lib\site-packages\kucoin\client.py", line 161, in _handle_response
raise KucoinAPIException(response)
kucoin.exceptions.KucoinAPIException: KucoinAPIException UNAUTH: Invalid nonce
What's the reason of this error?

Missing get all tickers

The function get_ticker has the optional variable symbol but doesnt work when symbol is not set.

def get_ticker(self, symbol):
data = {
            'symbol': symbol
        }
        return self._get('market/orderbook/level1', False, data=data)

might chance to:??

def get_ticker(self, symbol=None):
    if symbol:
        data = {
            'symbol': symbol
        }

        return self._get('market/orderbook/level1', False, data=data)
    else:
        return self._get('market/allTickers', False)

source: https://docs.kucoin.com/#get-ticker

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.