Welcome to python-kucoin v2.1.2

https://img.shields.io/pypi/v/python-kucoin.svg https://img.shields.io/pypi/l/python-kucoin.svg https://img.shields.io/travis/sammchardy/python-kucoin.svg https://img.shields.io/coveralls/sammchardy/python-kucoin.svg https://img.shields.io/pypi/wheel/python-kucoin.svg https://img.shields.io/pypi/pyversions/python-kucoin.svg

This is an unofficial Python wrapper for the Kucoin exchanges REST and Websocket API v2. I am in no way affiliated with Kucoin, use at your own risk.

PyPi
https://pypi.python.org/pypi/python-kucoin
Source code
https://github.com/sammchardy/python-kucoin
Documentation
https://python-kucoin.readthedocs.io/en/latest/
Blog with examples
https://sammchardy.github.io

Features

  • Implementation of REST endpoints
  • Simple handling of authentication
  • Response exception handling
  • Implement websockets (note only python3.5+)

TODO

  • L2 and L3 Local Order Books

Quick Start

Register an account with Kucoin.

To test on the Sandbox register with Kucoin Sandbox.

Generate an API Key or Generate an API Key in Sandbox and enable it.

pip install python-kucoin
from kucoin.client import Client

api_key = '<api_key>'
api_secret = '<api_secret>'
api_passphrase = '<api_passphrase>'

client = Client(api_key, api_secret, api_passphrase)

# or connect to Sandbox
# client = Client(api_key, api_secret, api_passphrase, sandbox=True)

# get currencies
currencies = client.get_currencies()

# get market depth
depth = client.get_order_book('KCS-BTC')

# get symbol klines
klines = client.get_kline_data('KCS-BTC')

# get list of markets
markets = client.get_markets()

# place a market buy order
order = client.create_market_order('NEO', Client.SIDE_BUY, size=20)

# get list of active orders
orders = client.get_active_orders('KCS-BTC')

Websockets

Note only for python3.5+

import asyncio

from kucoin.client import Client
from kucoin.asyncio import KucoinSocketManager

api_key = '<api_key>'
api_secret = '<api_secret>'
api_passphrase = '<api_passphrase>'


async def main():
    global loop

    # callback function that receives messages from the socket
    async def handle_evt(msg):
        if msg['topic'] == '/market/ticker:ETH-USDT':
            print(f'got ETH-USDT tick:{msg["data"]}')

        elif msg['topic'] == '/market/snapshot:BTC':
            print(f'got BTC market snapshot:{msg["data"]}')

        elif msg['topic'] == '/market/snapshot:KCS-BTC':
            print(f'got KCS-BTC symbol snapshot:{msg["data"]}')

        elif msg['topic'] == '/market/ticker:all':
            print(f'got all market snapshot:{msg["data"]}')

        elif msg['topic'] == '/account/balance':
            print(f'got account balance:{msg["data"]}')

        elif msg['topic'] == '/market/level2:KCS-BTC':
            print(f'got L2 msg:{msg["data"]}')

        elif msg['topic'] == '/market/match:BTC-USDT':
            print(f'got market match msg:{msg["data"]}')

        elif msg['topic'] == '/market/level3:BTC-USDT':
            if msg['subject'] == 'trade.l3received':
                if msg['data']['type'] == 'activated':
                    # must be logged into see these messages
                    print(f"L3 your order activated: {msg['data']}")
                else:
                    print(f"L3 order received:{msg['data']}")
            elif msg['subject'] == 'trade.l3open':
                print(f"L3 order open: {msg['data']}")
            elif msg['subject'] == 'trade.l3done':
                print(f"L3 order done: {msg['data']}")
            elif msg['subject'] == 'trade.l3match':
                print(f"L3 order matched: {msg['data']}")
            elif msg['subject'] == 'trade.l3change':
                print(f"L3 order changed: {msg['data']}")

    client = Client(api_key, api_secret, api_passphrase)

    ksm = await KucoinSocketManager.create(loop, client, handle_evt)

    # for private topics such as '/account/balance' pass private=True
    ksm_private = await KucoinSocketManager.create(loop, client, handle_evt, private=True)

    # Note: try these one at a time, if all are on you will see a lot of output

    # ETH-USDT Market Ticker
    await ksm.subscribe('/market/ticker:ETH-USDT')
    # BTC Symbol Snapshots
    await ksm.subscribe('/market/snapshot:BTC')
    # KCS-BTC Market Snapshots
    await ksm.subscribe('/market/snapshot:KCS-BTC')
    # All tickers
    await ksm.subscribe('/market/ticker:all')
    # Level 2 Market Data
    await ksm.subscribe('/market/level2:KCS-BTC')
    # Market Execution Data
    await ksm.subscribe('/market/match:BTC-USDT')
    # Level 3 market data
    await ksm.subscribe('/market/level3:BTC-USDT')
    # Account balance - must be authenticated
    await ksm_private.subscribe('/account/balance')

    while True:
        print("sleeping to keep loop open")
        await asyncio.sleep(20, loop=loop)


if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

For more check out the documentation.

Other Exchanges

If you use Binance check out my python-binance library.

If you use Binance Chain check out my python-binance-chain library.

If you use Allcoin check out my python-allcoin library.

If you use IDEX check out my python-idex library.

If you use BigONE check out my python-bigone library.

https://analytics-pixel.appspot.com/UA-111417213-1/github/python-kucoin?pixel

Contents

Getting Started

This API has been updated to work with the v2 Sandbox

Installation

python-kucoin is available on PYPI. Install with pip:

pip install python-kucoin

For previous v1 API install with

pip install python-kucoin==0.1.12
Register on Kucoin

Firstly register an account with Kucoin.

To test on the Sandbox register with Kucoin Sandbox.

Generate an API Key

To use signed account methods you are required to create an API Key and enable it.

Initialise the client

Pass your API Key, Secret and API Passphrase

from kucoin.client import Client
client = Client(api_key, api_secret, api_passphrase)
Requests Settings

python-kucoin uses the requests library.

You can set custom requests parameters for all API calls when creating the client.

client = Client("api-key", "api-secret", "api-passphrase", {"verify": False, "timeout": 20})

Check out the requests documentation for all options.

Proxy Settings

You can use the Requests Settings method above

proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://10.10.1.10:1080'
}

# in the Client instantiation
client = Client("api-key", "api-secret", {'proxies': proxies})

Or set an environment variable for your proxy if required to work across all requests.

An example for Linux environments from the requests Proxies documentation is as follows.

$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"

For Windows environments

C:\>set HTTP_PROXY=http://10.10.1.10:3128
C:\>set HTTPS_PROXY=http://10.10.1.10:1080
API Rate Limit

Public Endpoints - 30 requests per ten seconds.

Private Endpoints - 50 requests per ten seconds.

  • Websocket *

Connect - 30 times per minutes

Subscribe - 120 times per minute

Unsubscribe - 120 times per minute

Constants

Kucoin defines constants for Redord Types, Order Side, Order Status and Resolution. These are accessible from the Client class.

SIDE_BUY = 'buy'
SIDE_SELL = 'sell'

ACCOUNT_MAIN = 'main'
ACCOUNT_TRADE = 'trade'


ORDER_LIMIT = 'limit'
ORDER_MARKET = 'market'
ORDER_LIMIT_STOP = 'limit_stop'
ORDER_MARKET_STOP = 'market_stop'

STOP_LOSS = 'loss'
STOP_ENTRY = 'entry'

STP_CANCEL_NEWEST = 'CN'
STP_CANCEL_OLDEST = 'CO'
STP_DECREASE_AND_CANCEL = 'DC'
STP_CANCEL_BOTH = 'CB'

TIMEINFORCE_GOOD_TILL_CANCELLED = 'GTC'
TIMEINFORCE_GOOD_TILL_TIME = 'GTT'
TIMEINFORCE_IMMEDIATE_OR_CANCEL = 'IOC'
TIMEINFORCE_FILL_OR_KILL = 'FOK'

Use in your code like below.

from kucoin.client import Client

order_side = Client.SIDE_BUY

General Endpoints

class kucoin.client.Client(api_key, api_secret, passphrase, sandbox=False, requests_params=None)[source]
get_timestamp()[source]

Get the server timestamp

https://docs.kucoin.com/#time

Returns:response timestamp in ms

Currency Endpoints

class kucoin.client.Client(api_key, api_secret, passphrase, sandbox=False, requests_params=None)[source]
get_currencies()[source]

List known currencies

https://docs.kucoin.com/#get-currencies

currencies = client.get_currencies()
Returns:API Response
[
    {
        "currency": "BTC",
        "name": "BTC",
        "fullName": "Bitcoin",
        "precision": 8
    },
    {
        "currency": "ETH",
        "name": "ETH",
        "fullName": "Ethereum",
        "precision": 7
    }
]
Raises:KucoinResponseException, KucoinAPIException
get_currency(currency)[source]

Get single currency detail

https://docs.kucoin.com/#get-currency-detail

# call with no coins
currency = client.get_currency('BTC')
Returns:API Response
{
    "currency": "BTC",
    "name": "BTC",
    "fullName": "Bitcoin",
    "precision": 8,
    "withdrawalMinSize": "0.002",
    "withdrawalMinFee": "0.0005",
    "isWithdrawEnabled": true,
    "isDepositEnabled": true
}
Raises:KucoinResponseException, KucoinAPIException

Account Endpoints

class kucoin.client.Client(api_key, api_secret, passphrase, sandbox=False, requests_params=None)[source]
cancel_withdrawal(withdrawal_id)[source]

Cancel a withdrawal

https://docs.kucoin.com/#cancel-withdrawal

Parameters:withdrawal_id (string) – ID of withdrawal
client.cancel_withdrawal('5bffb63303aa675e8bbe18f9')
Returns:None
Raises:KucoinResponseException, KucoinAPIException
create_account(account_type, currency)[source]

Create an account

https://docs.kucoin.com/#create-an-account

Parameters:
  • account_type (string) – Account type - main or trade
  • currency (string) – Currency code
account = client.create_account('trade', 'BTC')
Returns:API Response
{
    "id": "5bd6e9286d99522a52e458de"
}
Raises:KucoinResponseException, KucoinAPIException
create_deposit_address(currency)[source]

Create deposit address of currency for deposit. You can just create one deposit address.

https://docs.kucoin.com/#create-deposit-address

Parameters:currency (string) – Name of currency
address = client.create_deposit_address('NEO')
Returns:ApiResponse
{
    "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
    "memo": "5c247c8a03aa677cea2a251d"
}
Raises:KucoinResponseException, KucoinAPIException
create_inner_transfer(from_account_id, to_account_id, amount, order_id=None)[source]

Get account holds placed for any active orders or pending withdraw requests

https://docs.kucoin.com/#get-holds

Parameters:
  • from_account_id (str) – ID of account to transfer funds from - from list_accounts()
  • to_account_id (str) – ID of account to transfer funds to - from list_accounts()
  • amount (int) – Amount to transfer
  • order_id (string) – (optional) Request ID (default flat_uuid())
transfer = client.create_inner_transfer('5bd6e9216d99522a52e458d6', 5bc7f080b39c5c03286eef8e', 20)
Returns:API Response
{
    "orderId": "5bd6e9286d99522a52e458de"
}
Raises:KucoinResponseException, KucoinAPIException
create_withdrawal(currency, amount, address, memo=None, is_inner=False, remark=None)[source]

Process a withdrawal

https://docs.kucoin.com/#apply-withdraw

Parameters:
  • currency (string) – Name of currency
  • amount (number) – Amount to withdraw
  • address (string) – Address to withdraw to
  • memo (string) – (optional) Remark to the withdrawal address
  • is_inner (bool) – (optional) Remark to the withdrawal address
  • remark (string) – (optional) Remark
withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851')
Returns:ApiResponse
{
    "withdrawalId": "5bffb63303aa675e8bbe18f9"
}
Raises:KucoinResponseException, KucoinAPIException
get_account(account_id)[source]

Get an individual account

https://docs.kucoin.com/#get-an-account

Parameters:account_id (string) – ID for account - from list_accounts()
account = client.get_account('5bd6e9216d99522a52e458d6')
Returns:API Response
{
    "currency": "KCS",
    "balance": "1000000060.6299",
    "available": "1000000060.6299",
    "holds": "0"
}
Raises:KucoinResponseException, KucoinAPIException
get_account_holds(account_id, page=None, page_size=None)[source]

Get account holds placed for any active orders or pending withdraw requests

https://docs.kucoin.com/#get-holds

Parameters:
  • account_id (string) – ID for account - from list_accounts()
  • page (int) – (optional) Current page - default 1
  • page_size (int) – (optional) Number of results to return - default 50
holds = client.get_account_holds('5bd6e9216d99522a52e458d6')

holds = client.get_account_holds('5bd6e9216d99522a52e458d6', page=2, page_size=10)
Returns:API Response
{
    "currentPage": 1,
    "pageSize": 10,
    "totalNum": 2,
    "totalPage": 1,
    "items": [
        {
            "currency": "ETH",
            "holdAmount": "5083",
            "bizType": "Withdraw",
            "orderId": "5bc7f080b39c5c03286eef8e",
            "createdAt": 1545898567000,
            "updatedAt": 1545898567000
        },
        {
            "currency": "ETH",
            "holdAmount": "1452",
            "bizType": "Withdraw",
            "orderId": "5bc7f518b39c5c033818d62d",
            "createdAt": 1545898567000,
            "updatedAt": 1545898567000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_accounts()[source]

Get a list of accounts

https://docs.kucoin.com/#accounts

accounts = client.get_accounts()
Returns:API Response
[
    {
        "id": "5bd6e9286d99522a52e458de",
        "currency": "BTC",
        "type": "main",
        "balance": "237582.04299",
        "available": "237582.032",
        "holds": "0.01099"
    },
    {
        "id": "5bd6e9216d99522a52e458d6",
        "currency": "BTC",
        "type": "trade",
        "balance": "1234356",
        "available": "1234356",
        "holds": "0"
    }
]
Raises:KucoinResponseException, KucoinAPIException
get_deposit_address(currency)[source]

Get deposit address for a currency

https://docs.kucoin.com/#get-deposit-address

Parameters:currency (string) – Name of currency
address = client.get_deposit_address('NEO')
Returns:ApiResponse
{
    "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
    "memo": "5c247c8a03aa677cea2a251d"
}
Raises:KucoinResponseException, KucoinAPIException
get_deposits(currency=None, status=None, start=None, end=None, page=None, limit=None)[source]

Get deposit records for a currency

https://docs.kucoin.com/#get-deposit-list

Parameters:
  • currency (string) – Name of currency (optional)
  • status (string) – optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Page to fetch
  • limit (int) – (optional) Number of transactions
deposits = client.get_deposits('NEO')
Returns:ApiResponse
{
    "currentPage": 1,
    "pageSize": 5,
    "totalNum": 2,
    "totalPage": 1,
    "items": [
        {
            "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989",
            "memo": "5c247c8a03aa677cea2a251d",
            "amount": 1,
            "fee": 0.0001,
            "currency": "KCS",
            "isInner": false,
            "walletTxId": "5bbb57386d99522d9f954c5a@test004",
            "status": "SUCCESS",
            "createdAt": 1544178843000,
            "updatedAt": 1544178891000
        }, {
            "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989",
            "memo": "5c247c8a03aa677cea2a251d",
            "amount": 1,
            "fee": 0.0001,
            "currency": "KCS",
            "isInner": false,
            "walletTxId": "5bbb57386d99522d9f954c5a@test003",
            "status": "SUCCESS",
            "createdAt": 1544177654000,
            "updatedAt": 1544178733000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_withdrawal_quotas(currency)[source]

Get withdrawal quotas for a currency

https://docs.kucoin.com/#get-withdrawal-quotas

Parameters:currency (string) – Name of currency
quotas = client.get_withdrawal_quotas('ETH')
Returns:ApiResponse
{
    "currency": "ETH",
    "availableAmount": 2.9719999,
    "remainAmount": 2.9719999,
    "withdrawMinSize": 0.1000000,
    "limitBTCAmount": 2.0,
    "innerWithdrawMinFee": 0.00001,
    "isWithdrawEnabled": true,
    "withdrawMinFee": 0.0100000,
    "precision": 7
}
Raises:KucoinResponseException, KucoinAPIException
get_withdrawals(currency=None, status=None, start=None, end=None, page=None, limit=None)[source]

Get deposit records for a currency

https://docs.kucoin.com/#get-withdrawals-list

Parameters:
  • currency (string) – Name of currency (optional)
  • status (string) – optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Page to fetch
  • limit (int) – (optional) Number of transactions
withdrawals = client.get_withdrawals('NEO')
Returns:ApiResponse
{
    "currentPage": 1,
    "pageSize": 10,
    "totalNum": 1,
    "totalPage": 1,
    "items": [
        {
            "id": "5c2dc64e03aa675aa263f1ac",
            "address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9",
            "memo": "",
            "currency": "ETH",
            "amount": 1.0000000,
            "fee": 0.0100000,
            "walletTxId": "3e2414d82acce78d38be7fe9",
            "isInner": false,
            "status": "FAILURE",
            "createdAt": 1546503758000,
            "updatedAt": 1546504603000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException

Trading Endpoints

class kucoin.client.Client(api_key, api_secret, passphrase, sandbox=False, requests_params=None)[source]
cancel_all_orders(symbol=None)[source]

Cancel all orders

https://docs.kucoin.com/#cancel-all-orders

res = client.cancel_all_orders()
Returns:ApiResponse
{
    "cancelledOrderIds": [
        "5bd6e9286d99522a52e458de"
    ]
}
Raises:KucoinResponseException, KucoinAPIException
cancel_order(order_id)[source]

Cancel an order

https://docs.kucoin.com/#cancel-an-order

Parameters:order_id (string) – Order id
res = client.cancel_order('5bd6e9286d99522a52e458de)
Returns:ApiResponse
{
    "cancelledOrderIds": [
        "5bd6e9286d99522a52e458de"
    ]
}
Raises:KucoinResponseException, KucoinAPIException

KucoinAPIException If order_id is not found

create_limit_order(symbol, side, price, size, client_oid=None, remark=None, time_in_force=None, stop=None, stop_price=None, stp=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None)[source]

Create an order

https://docs.kucoin.com/#place-a-new-order

Parameters:
  • symbol (string) – Name of symbol e.g. KCS-BTC
  • side (string) – buy or sell
  • price (string) – Name of coin
  • size (string) – Amount of base currency to buy or sell
  • client_oid (string) – (optional) Unique order_id default flat_uuid()
  • remark (string) – (optional) remark for the order, max 100 utf8 characters
  • stp (string) – (optional) self trade protection CN, CO, CB or DC (default is None)
  • time_in_force (string) – (optional) GTC, GTT, IOC, or FOK (default is GTC)
  • stop (string) – (optional) stop type loss or entry - requires stop_price
  • stop_price (string) – (optional) trigger price for stop order
  • cancel_after (string) – (optional) number of seconds to cancel the order if not filled required time_in_force to be GTT
  • post_only (bool) – (optional) indicates that the order should only make liquidity. If any part of the order results in taking liquidity, the order will be rejected and no part of it will execute.
  • hidden (bool) – (optional) Orders not displayed in order book
  • iceberg (bool) – (optional) Only visible portion of the order is displayed in the order book
  • visible_size (bool) – (optional) The maximum visible size of an iceberg order
order = client.create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000')
Returns:ApiResponse
{
    "orderOid": "596186ad07015679730ffa02"
}
Raises:KucoinResponseException, KucoinAPIException, LimitOrderException
create_market_order(symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None)[source]

Create a market order

One of size or funds must be set

https://docs.kucoin.com/#place-a-new-order

Parameters:
  • symbol (string) – Name of symbol e.g. KCS-BTC
  • side (string) – buy or sell
  • size (string) – (optional) Desired amount in base currency
  • funds (string) – (optional) Desired amount of quote currency to use
  • client_oid (string) – (optional) Unique order id (default flat_uuid())
  • remark (string) – (optional) remark for the order, max 100 utf8 characters
  • stp (string) – (optional) self trade protection CN, CO, CB or DC (default is None)
order = client.create_market_order('NEO', Client.SIDE_BUY, size=20)
Returns:ApiResponse
{
    "orderOid": "596186ad07015679730ffa02"
}
Raises:KucoinResponseException, KucoinAPIException, MarketOrderException
get_fills(order_id=None, symbol=None, side=None, order_type=None, start=None, end=None, page=None, limit=None)[source]

Get a list of recent fills.

https://docs.kucoin.com/#list-fills

Parameters:
  • order_id (string) – (optional) generated order id
  • symbol (string) – (optional) Name of symbol e.g. KCS-BTC
  • side (string) – (optional) buy or sell
  • order_type (string) – (optional) limit, market, limit_stop or market_stop
  • start (string) – Start time as unix timestamp (optional)
  • end (string) – End time as unix timestamp (optional)
  • page (int) – optional - Page to fetch
  • limit (int) – optional - Number of orders
fills = client.get_fills()
Returns:ApiResponse
{
    "currentPage":1,
    "pageSize":1,
    "totalNum":251915,
    "totalPage":251915,
    "items":[
        {
            "symbol":"BTC-USDT",
            "tradeId":"5c35c02709e4f67d5266954e",
            "orderId":"5c35c02703aa673ceec2a168",
            "counterOrderId":"5c1ab46003aa676e487fa8e3",
            "side":"buy",
            "liquidity":"taker",
            "forceTaker":true,
            "price":"0.083",
            "size":"0.8424304",
            "funds":"0.0699217232",
            "fee":"0",
            "feeRate":"0",
            "feeCurrency":"USDT",
            "stop":"",
            "type":"limit",
            "createdAt":1547026472000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_order(order_id)[source]

Get order details

https://docs.kucoin.com/#get-an-order

Parameters:order_id (str) – orderOid value
order = client.get_order('5c35c02703aa673ceec2a168')
Returns:ApiResponse
{
    "id": "5c35c02703aa673ceec2a168",
    "symbol": "BTC-USDT",
    "opType": "DEAL",
    "type": "limit",
    "side": "buy",
    "price": "10",
    "size": "2",
    "funds": "0",
    "dealFunds": "0.166",
    "dealSize": "2",
    "fee": "0",
    "feeCurrency": "USDT",
    "stp": "",
    "stop": "",
    "stopTriggered": false,
    "stopPrice": "0",
    "timeInForce": "GTC",
    "postOnly": false,
    "hidden": false,
    "iceberge": false,
    "visibleSize": "0",
    "cancelAfter": 0,
    "channel": "IOS",
    "clientOid": null,
    "remark": null,
    "tags": null,
    "isActive": false,
    "cancelExist": false,
    "createdAt": 1547026471000
}
Raises:KucoinResponseException, KucoinAPIException
get_orders(symbol=None, status=None, side=None, order_type=None, start=None, end=None, page=None, limit=None)[source]

Get list of orders

https://docs.kucoin.com/#list-orders

Parameters:
  • symbol (string) – (optional) Name of symbol e.g. KCS-BTC
  • status (string) – (optional) Specify status active or done (default done)
  • side (string) – (optional) buy or sell
  • order_type (string) – (optional) limit, market, limit_stop or market_stop
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Page to fetch
  • limit (int) – (optional) Number of orders
orders = client.get_orders(symbol='KCS-BTC', status='active')
Returns:ApiResponse
{
    "currentPage": 1,
    "pageSize": 1,
    "totalNum": 153408,
    "totalPage": 153408,
    "items": [
        {
            "id": "5c35c02703aa673ceec2a168",
            "symbol": "BTC-USDT",
            "opType": "DEAL",
            "type": "limit",
            "side": "buy",
            "price": "10",
            "size": "2",
            "funds": "0",
            "dealFunds": "0.166",
            "dealSize": "2",
            "fee": "0",
            "feeCurrency": "USDT",
            "stp": "",
            "stop": "",
            "stopTriggered": false,
            "stopPrice": "0",
            "timeInForce": "GTC",
            "postOnly": false,
            "hidden": false,
            "iceberge": false,
            "visibleSize": "0",
            "cancelAfter": 0,
            "channel": "IOS",
            "clientOid": null,
            "remark": null,
            "tags": null,
            "isActive": false,
            "cancelExist": false,
            "createdAt": 1547026471000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException

Market Endpoints

class kucoin.client.Client(api_key, api_secret, passphrase, sandbox=False, requests_params=None)[source]
get_24hr_stats(symbol)[source]

Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units.

Parameters:symbol (string) – (optional) Name of symbol e.g. KCS-BTC
stats = client.get_24hr_stats('ETH-BTC')
Returns:ApiResponse

Without a symbol param

{
    "symbol": "BTC-USDT",
    "changeRate": "0.0128",   # 24h change rate
    "changePrice": "0.8",     # 24h rises and falls in price (if the change rate is a negative number,
                              # the price rises; if the change rate is a positive number, the price falls.)
    "open": 61,               # Opening price
    "close": 63.6,            # Closing price
    "high": "63.6",           # Highest price filled
    "low": "61",              # Lowest price filled
    "vol": "244.78",          # Transaction quantity
    "volValue": "15252.0127"  # Transaction amount
}
Raises:KucoinResponseException, KucoinAPIException
get_full_order_book(symbol)[source]

Get a list of all bids and asks aggregated by price for a symbol.

This call is generally used by professional traders because it uses more server resources and traffic, and Kucoin has strict access frequency control.

https://docs.kucoin.com/#get-full-order-book-aggregated

Parameters:symbol (string) – Name of symbol e.g. KCS-BTC
orders = client.get_order_book('KCS-BTC')
Returns:ApiResponse
{
    "sequence": "3262786978",
    "bids": [
        ["6500.12", "0.45054140"],  # [price size]
        ["6500.11", "0.45054140"]
    ],
    "asks": [
        ["6500.16", "0.57753524"],
        ["6500.15", "0.57753524"]
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_full_order_book_level3(symbol)[source]

Get a list of all bids and asks non-aggregated for a symbol.

This call is generally used by professional traders because it uses more server resources and traffic, and Kucoin has strict access frequency control.

https://docs.kucoin.com/#get-full-order-book-atomic

Parameters:symbol (string) – Name of symbol e.g. KCS-BTC
orders = client.get_order_book('KCS-BTC')
Returns:ApiResponse
{
    "sequence": "1545896707028",
    "bids": [
        [
            "5c2477e503aa671a745c4057",   # orderId
            "6",                          # price
            "0.999"                       # size
        ],
        [
            "5c2477e103aa671a745c4054",
            "5",
            "0.999"
        ]
    ],
    "asks": [
        [
            "5c24736703aa671a745c401e",
            "200",
            "1"
        ],
        [
            "5c2475c903aa671a745c4033",
            "201",
            "1"
        ]
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_historical_orders(symbol=None, side=None, start=None, end=None, page=None, limit=None)[source]

List of KuCoin V1 historical orders.

https://docs.kucoin.com/#get-v1-historical-orders-list

Parameters:
  • symbol (string) – (optional) Name of symbol e.g. KCS-BTC
  • side (string) – (optional) buy or sell
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Page to fetch
  • limit (int) – (optional) Number of orders
orders = client.get_historical_orders(symbol='KCS-BTC')
Returns:ApiResponse
{
    "currentPage": 1,
    "pageSize": 50,
    "totalNum": 1,
    "totalPage": 1,
    "items": [
        {
            "symbol": "SNOV-ETH",
            "dealPrice": "0.0000246",
            "dealValue": "0.018942",
            "amount": "770",
            "fee": "0.00001137",
            "side": "sell",
            "createdAt": 1540080199
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_kline_data(symbol, kline_type='5min', start=None, end=None)[source]

Get kline data

For each query, the system would return at most 1500 pieces of data. To obtain more data, please page the data by time.

Parameters:
  • symbol (string) – Name of symbol e.g. KCS-BTC
  • kline_type (string) – type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour, 4hour, 6hour, 8hour, 12hour, 1day, 1week
  • start (int) – Start time as unix timestamp (optional) default start of day in UTC
  • end (int) – End time as unix timestamp (optional) default now in UTC

https://docs.kucoin.com/#get-historic-rates

klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278)
Returns:ApiResponse
[
    [
        "1545904980",             //Start time of the candle cycle
        "0.058",                  //opening price
        "0.049",                  //closing price
        "0.058",                  //highest price
        "0.049",                  //lowest price
        "0.018",                  //Transaction amount
        "0.000945"                //Transaction volume
    ],
    [
        "1545904920",
        "0.058",
        "0.072",
        "0.072",
        "0.058",
        "0.103",
        "0.006986"
    ]
]
Raises:KucoinResponseException, KucoinAPIException
get_markets()[source]

Get supported market list

https://docs.kucoin.com/#get-market-list

markets = client.get_markets()
Returns:ApiResponse
{
    "data": [
        "BTC",
        "ETH",
        "USDT"
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_order_book(symbol)[source]

Get a list of bids and asks aggregated by price for a symbol.

Returns up to 100 depth each side. Fastest Order book API

https://docs.kucoin.com/#get-part-order-book-aggregated

Parameters:symbol (string) – Name of symbol e.g. KCS-BTC
orders = client.get_order_book('KCS-BTC')
Returns:ApiResponse
{
    "sequence": "3262786978",
    "bids": [
        ["6500.12", "0.45054140"],  # [price, size]
        ["6500.11", "0.45054140"]
    ],
    "asks": [
        ["6500.16", "0.57753524"],
        ["6500.15", "0.57753524"]
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_symbols()[source]

Get a list of available currency pairs for trading.

https://docs.kucoin.com/#symbols-amp-ticker

symbols = client.get_symbols()
Returns:ApiResponse
[
    {
        "symbol": "BTC-USDT",
        "name": "BTC-USDT",
        "baseCurrency": "BTC",
        "quoteCurrency": "USDT",
        "baseMinSize": "0.00000001",
        "quoteMinSize": "0.01",
        "baseMaxSize": "10000",
        "quoteMaxSize": "100000",
        "baseIncrement": "0.00000001",
        "quoteIncrement": "0.01",
        "priceIncrement": "0.00000001",
        "enableTrading": true
    }
]
Raises:KucoinResponseException, KucoinAPIException
get_ticker(symbol=None)[source]

Get symbol tick

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

Parameters:symbol (string) – (optional) Name of symbol e.g. KCS-BTC
all_ticks = client.get_ticker()

ticker = client.get_ticker('ETH-BTC')
Returns:ApiResponse
{
    "sequence": "1545825031840",      # now sequence
    "price": "3494.367783",           # last trade price
    "size": "0.05027185",             # last trade size
    "bestBid": "3494.367783",         # best bid price
    "bestBidSize": "2.60323254",      # size at best bid price
    "bestAsk": "3499.12",             # best ask price
    "bestAskSize": "0.01474011"       # size at best ask price
}
Raises:KucoinResponseException, KucoinAPIException
get_trade_histories(symbol)[source]

List the latest trades for a symbol

https://docs.kucoin.com/#get-trade-histories

Parameters:symbol (string) – Name of symbol e.g. KCS-BTC
orders = client.get_trade_histories('KCS-BTC')
Returns:ApiResponse
[
    {
        "sequence": "1545896668571",
        "price": "0.07",                # Filled price
        "size": "0.004",                # Filled amount
        "side": "buy",                  # Filled side. The filled side is set to the taker by default.
        "time": 1545904567062140823     # Transaction time
    },
    {
        "sequence": "1545896668578",
        "price": "0.054",
        "size": "0.066",
        "side": "buy",
        "time": 1545904581619888405
    }
]
Raises:KucoinResponseException, KucoinAPIException

Websockets

Note: The websocket client is only available for python3.5+

This feature is still in development so check the documentation around message topics here https://docs.kucoin.com/#websocket-feed

For private topics such as ‘/account/balance’ pass private=True to the KucoinSocketManager, see example below

TODO:
  • Helper functions for topics
  • Multiplexing
  • Local Order book level 2 & 3
Sample Code
import asyncio

from kucoin.client import Client
from kucoin.asyncio import KucoinSocketManager

api_key = '<api_key>'
api_secret = '<api_secret>'
api_passphrase = '<api_passphrase>'


async def main():
    global loop

    # callback function that receives messages from the socket
    async def handle_evt(msg):
        if msg['topic'] == '/market/ticker:ETH-USDT':
            print(f'got ETH-USDT tick:{msg["data"]}')

        elif msg['topic'] == '/market/snapshot:BTC':
            print(f'got BTC market snapshot:{msg["data"]}')

        elif msg['topic'] == '/market/snapshot:KCS-BTC':
            print(f'got KCS-BTC symbol snapshot:{msg["data"]}')

        elif msg['topic'] == '/market/ticker:all':
            print(f'got all market snapshot:{msg["data"]}')

        elif msg['topic'] == '/account/balance':
            print(f'got account balance:{msg["data"]}')

        elif msg['topic'] == '/market/level2:KCS-BTC':
            print(f'got L2 msg:{msg["data"]}')

        elif msg['topic'] == '/market/match:BTC-USDT':
            print(f'got market match msg:{msg["data"]}')

        elif msg['topic'] == '/market/level3:BTC-USDT':
            if msg['subject'] == 'trade.l3received':
                if msg['data']['type'] == 'activated':
                    # must be logged into see these messages
                    print(f"L3 your order activated: {msg['data']}")
                else:
                    print(f"L3 order received:{msg['data']}")
            elif msg['subject'] == 'trade.l3open':
                print(f"L3 order open: {msg['data']}")
            elif msg['subject'] == 'trade.l3done':
                print(f"L3 order done: {msg['data']}")
            elif msg['subject'] == 'trade.l3match':
                print(f"L3 order matched: {msg['data']}")
            elif msg['subject'] == 'trade.l3change':
                print(f"L3 order changed: {msg['data']}")

    client = Client(api_key, api_secret, api_passphrase)

    ksm = await KucoinSocketManager.create(loop, client, handle_evt)

    # for private topics such as '/account/balance' pass private=True
    ksm_private = await KucoinSocketManager.create(loop, client, handle_evt, private=True)

    # Note: try these one at a time, if all are on you will see a lot of output

    # ETH-USDT Market Ticker
    await ksm.subscribe('/market/ticker:ETH-USDT')
    # BTC Symbol Snapshots
    await ksm.subscribe('/market/snapshot:BTC')
    # KCS-BTC Market Snapshots
    await ksm.subscribe('/market/snapshot:KCS-BTC')
    # All tickers
    await ksm.subscribe('/market/ticker:all')
    # Level 2 Market Data
    await ksm.subscribe('/market/level2:KCS-BTC')
    # Market Execution Data
    await ksm.subscribe('/market/match:BTC-USDT')
    # Level 3 market data
    await ksm.subscribe('/market/level3:BTC-USDT')
    # Account balance - must be authenticated
    await ksm_private.subscribe('/account/balance')

    while True:
        print("sleeping to keep loop open")
        await asyncio.sleep(20, loop=loop)


if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
Unsubscribe from channel

Send the same topic name to the unsubscribe function

await ksm.unsubscribe('/market/ticker:ETH-USDT')

Exceptions

KucoinResponseException

Raised if a non JSON response is returned

KucoinAPIException

On an API call error a kucoin.exceptions.KucoinAPIException will be raised.

The exception provides access to the

  • status_code - response status code
  • response - response object
  • message - Kucoin error message=
  • request - request object if available
try:
    client.get_coin_list()
except KucoinAPIException as e:
    print(e.status_code)
    print(e.message)
MarketOrderException

Raised if market order params are incorrect

LimitOrderException

Raised if limit order params are incorrect

Changelog

v2.1.2 - 2019-04-17

Added

  • exception if using a private websocket topic but not connected with private

Removed

  • removed py3.6 type annotations for py3.5 support
v2.1.1 - 2019-04-17

Added

  • websocket support for private messages
  • get_historical_orders function to get V1 historical orders

Fixed

  • fixed get_ticker to work for all tickers
  • websocket reconnect ability
v2.1.0 - 2019-02-25

Added

  • websocket support
  • get_fiat_prices function to get fiat price for currency
  • get_markets function to get supported market list
  • iceberg order support
  • util functions to generate uuid and convert dict to compact json string

Updated

  • get_ticker to have optional symbol param

Fixed

  • market and limit order create functions
  • get_kline_data function
  • get_account_holds function endpoint
  • LimitOrderException message
v2.0.2 - 2019-02-23

Fixed

  • signature generation for get requests
v2.0.1 - 2019-01-23

Fixed

  • added auth for get_fills()
v2.0.0 - 2019-01-22

Added

  • support for REST endpoint of v2 API
v0.1.12 - 2018-04-27

Added

  • timestamp in milliseconds to get_historical_klines_tv function

Fixed

  • make coin parameter required in get_coin_info function
v0.1.11 - 2018-03-01

Added

  • option for passing requests module parameters on Client initialisation

Restored

  • old get_all_balances non-paged functionality
v0.1.10 - 2018-02-10

Fixed

  • remove slash in path in get_order_details function
v0.1.9 - 2018-02-09

Updated

  • path for get_all_balances to match update in Kucoin docs, now supports pagination
v0.1.8 - 2018-01-20

Added

  • better exception error messages

Fixed

  • cancel_order format to make order_type required
v0.1.7 - 2018-01-17

Fixed

  • cancel_order format to send symbol in payload, remove URL params
  • cancel_all_orders format to send symbol in payload, remove URL params
v0.1.6 - 2018-01-15

Added

  • constants for transfer types, pending, finished and cancelled
  • documentation for group param on get_order_book, get_buy_orders and get_sell_orders
  • add get_trading_markets endpoint
  • add market param to get_trading_symbols and get_trending_coins
  • add get_coin_info function with optional coin param

Fixed

  • set coin param to optional for get_reward_info, get_reward_summary and extract_invite_bonus
  • actually use the kv_format param on get_active_orders
  • cancel_order format to send symbol in URL
  • cancel_all_orders format to send symbol in URL
  • order_details removed symbol from URL
  • get_tick symbol is now optional
  • fix get_coin_list URL
v0.1.5 - 2018-01-14

Fixed

  • remove debug output
v0.1.4 - 2018-01-14

Added

  • add function get_historical_klines_tv to get klines in OHLCV format

Fixed

  • handle success: false type errors properly to raise exception
  • fix passed param name on get_kline_data
v0.1.3 - 2018-01-12

Added

  • add function get_total_balance to get balance in Fiat
  • added pagination params to get_all_balances
v0.1.2 - 2018-01-07

Added

  • api key endpoints
  • set default currency function
  • extract invite bonus function
v0.1.1 - 2018-01-02

Added

  • cancel all orders function
  • get order details function
  • get dealt orders function

Updated

  • old get_deal_orders function to get_symbol_dealt_orders
v0.1.0 - 2017-11-12

Added

  • Kucoin client interface
  • Coverage for all main endpoints
  • Constants for transfer type and status, order side and kline resolution
  • Full documentation

Kucoin API

client module
class kucoin.client.Client(api_key, api_secret, passphrase, sandbox=False, requests_params=None)[source]

Bases: object

REST_API_URL = 'https://openapi-v2.kucoin.com'
SANDBOX_API_URL = 'https://openapi-sandbox.kucoin.com'
API_VERSION = 'v1'
SIDE_BUY = 'buy'
SIDE_SELL = 'sell'
ACCOUNT_MAIN = 'main'
ACCOUNT_TRADE = 'trade'
ORDER_LIMIT = 'limit'
ORDER_MARKET = 'market'
ORDER_LIMIT_STOP = 'limit_stop'
ORDER_MARKET_STOP = 'market_stop'
STOP_LOSS = 'loss'
STOP_ENTRY = 'entry'
STP_CANCEL_NEWEST = 'CN'
STP_CANCEL_OLDEST = 'CO'
STP_DECREASE_AND_CANCEL = 'DC'
STP_CANCEL_BOTH = 'CB'
TIMEINFORCE_GOOD_TILL_CANCELLED = 'GTC'
TIMEINFORCE_GOOD_TILL_TIME = 'GTT'
TIMEINFORCE_IMMEDIATE_OR_CANCEL = 'IOC'
TIMEINFORCE_FILL_OR_KILL = 'FOK'
__init__(api_key, api_secret, passphrase, sandbox=False, requests_params=None)[source]

Kucoin API Client constructor

https://docs.kucoin.com/

Parameters:
  • api_key (string) – Api Token Id
  • api_secret (string) – Api Secret
  • passphrase (string) – Api Passphrase used to create API
  • sandbox (bool) – (optional) Use the sandbox endpoint or not (default False)
  • requests_params (dict.) – (optional) Dictionary of requests params to use for all calls
client = Client(api_key, api_secret, api_passphrase)
get_timestamp()[source]

Get the server timestamp

https://docs.kucoin.com/#time

Returns:response timestamp in ms
get_currencies()[source]

List known currencies

https://docs.kucoin.com/#get-currencies

currencies = client.get_currencies()
Returns:API Response
[
    {
        "currency": "BTC",
        "name": "BTC",
        "fullName": "Bitcoin",
        "precision": 8
    },
    {
        "currency": "ETH",
        "name": "ETH",
        "fullName": "Ethereum",
        "precision": 7
    }
]
Raises:KucoinResponseException, KucoinAPIException
get_currency(currency)[source]

Get single currency detail

https://docs.kucoin.com/#get-currency-detail

# call with no coins
currency = client.get_currency('BTC')
Returns:API Response
{
    "currency": "BTC",
    "name": "BTC",
    "fullName": "Bitcoin",
    "precision": 8,
    "withdrawalMinSize": "0.002",
    "withdrawalMinFee": "0.0005",
    "isWithdrawEnabled": true,
    "isDepositEnabled": true
}
Raises:KucoinResponseException, KucoinAPIException
get_accounts()[source]

Get a list of accounts

https://docs.kucoin.com/#accounts

accounts = client.get_accounts()
Returns:API Response
[
    {
        "id": "5bd6e9286d99522a52e458de",
        "currency": "BTC",
        "type": "main",
        "balance": "237582.04299",
        "available": "237582.032",
        "holds": "0.01099"
    },
    {
        "id": "5bd6e9216d99522a52e458d6",
        "currency": "BTC",
        "type": "trade",
        "balance": "1234356",
        "available": "1234356",
        "holds": "0"
    }
]
Raises:KucoinResponseException, KucoinAPIException
get_account(account_id)[source]

Get an individual account

https://docs.kucoin.com/#get-an-account

Parameters:account_id (string) – ID for account - from list_accounts()
account = client.get_account('5bd6e9216d99522a52e458d6')
Returns:API Response
{
    "currency": "KCS",
    "balance": "1000000060.6299",
    "available": "1000000060.6299",
    "holds": "0"
}
Raises:KucoinResponseException, KucoinAPIException
create_account(account_type, currency)[source]

Create an account

https://docs.kucoin.com/#create-an-account

Parameters:
  • account_type (string) – Account type - main or trade
  • currency (string) – Currency code
account = client.create_account('trade', 'BTC')
Returns:API Response
{
    "id": "5bd6e9286d99522a52e458de"
}
Raises:KucoinResponseException, KucoinAPIException
get_account_activity(account_id, start=None, end=None, page=None, limit=None)[source]

Get list of account activity

https://docs.kucoin.com/#get-account-history

Parameters:
  • account_id (string) – ID for account - from list_accounts()
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Current page - default 1
  • limit (int) – (optional) Number of results to return - default 50
history = client.get_account_activity('5bd6e9216d99522a52e458d6')

history = client.get_account_activity('5bd6e9216d99522a52e458d6', start='1540296039000')

history = client.get_account_activity('5bd6e9216d99522a52e458d6', page=2, page_size=10)
Returns:API Response
{
    "currentPage": 1,
    "pageSize": 10,
    "totalNum": 2,
    "totalPage": 1,
    "items": [
        {
            "currency": "KCS",
            "amount": "0.0998",
            "fee": "0",
            "balance": "1994.040596",
            "bizType": "withdraw",
            "direction": "in",
            "createdAt": 1540296039000,
            "context": {
                 "orderId": "5bc7f080b39c5c03286eef8a",
                 "currency": "BTC"
             }
        },
        {
            "currency": "KCS",
            "amount": "0.0998",
            "fee": "0",
            "balance": "1994.140396",
            "bizType": "trade exchange",
            "direction": "in",
            "createdAt": 1540296039000,
            "context": {
                 "orderId": "5bc7f080b39c5c03286eef8e",
                 "tradeId": "5bc7f080b3949c03286eef8a",
                 "symbol": "BTC-USD"
            }
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_account_holds(account_id, page=None, page_size=None)[source]

Get account holds placed for any active orders or pending withdraw requests

https://docs.kucoin.com/#get-holds

Parameters:
  • account_id (string) – ID for account - from list_accounts()
  • page (int) – (optional) Current page - default 1
  • page_size (int) – (optional) Number of results to return - default 50
holds = client.get_account_holds('5bd6e9216d99522a52e458d6')

holds = client.get_account_holds('5bd6e9216d99522a52e458d6', page=2, page_size=10)
Returns:API Response
{
    "currentPage": 1,
    "pageSize": 10,
    "totalNum": 2,
    "totalPage": 1,
    "items": [
        {
            "currency": "ETH",
            "holdAmount": "5083",
            "bizType": "Withdraw",
            "orderId": "5bc7f080b39c5c03286eef8e",
            "createdAt": 1545898567000,
            "updatedAt": 1545898567000
        },
        {
            "currency": "ETH",
            "holdAmount": "1452",
            "bizType": "Withdraw",
            "orderId": "5bc7f518b39c5c033818d62d",
            "createdAt": 1545898567000,
            "updatedAt": 1545898567000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
create_inner_transfer(from_account_id, to_account_id, amount, order_id=None)[source]

Get account holds placed for any active orders or pending withdraw requests

https://docs.kucoin.com/#get-holds

Parameters:
  • from_account_id (str) – ID of account to transfer funds from - from list_accounts()
  • to_account_id (str) – ID of account to transfer funds to - from list_accounts()
  • amount (int) – Amount to transfer
  • order_id (string) – (optional) Request ID (default flat_uuid())
transfer = client.create_inner_transfer('5bd6e9216d99522a52e458d6', 5bc7f080b39c5c03286eef8e', 20)
Returns:API Response
{
    "orderId": "5bd6e9286d99522a52e458de"
}
Raises:KucoinResponseException, KucoinAPIException
create_deposit_address(currency)[source]

Create deposit address of currency for deposit. You can just create one deposit address.

https://docs.kucoin.com/#create-deposit-address

Parameters:currency (string) – Name of currency
address = client.create_deposit_address('NEO')
Returns:ApiResponse
{
    "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
    "memo": "5c247c8a03aa677cea2a251d"
}
Raises:KucoinResponseException, KucoinAPIException
get_deposit_address(currency)[source]

Get deposit address for a currency

https://docs.kucoin.com/#get-deposit-address

Parameters:currency (string) – Name of currency
address = client.get_deposit_address('NEO')
Returns:ApiResponse
{
    "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
    "memo": "5c247c8a03aa677cea2a251d"
}
Raises:KucoinResponseException, KucoinAPIException
get_deposits(currency=None, status=None, start=None, end=None, page=None, limit=None)[source]

Get deposit records for a currency

https://docs.kucoin.com/#get-deposit-list

Parameters:
  • currency (string) – Name of currency (optional)
  • status (string) – optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Page to fetch
  • limit (int) – (optional) Number of transactions
deposits = client.get_deposits('NEO')
Returns:ApiResponse
{
    "currentPage": 1,
    "pageSize": 5,
    "totalNum": 2,
    "totalPage": 1,
    "items": [
        {
            "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989",
            "memo": "5c247c8a03aa677cea2a251d",
            "amount": 1,
            "fee": 0.0001,
            "currency": "KCS",
            "isInner": false,
            "walletTxId": "5bbb57386d99522d9f954c5a@test004",
            "status": "SUCCESS",
            "createdAt": 1544178843000,
            "updatedAt": 1544178891000
        }, {
            "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989",
            "memo": "5c247c8a03aa677cea2a251d",
            "amount": 1,
            "fee": 0.0001,
            "currency": "KCS",
            "isInner": false,
            "walletTxId": "5bbb57386d99522d9f954c5a@test003",
            "status": "SUCCESS",
            "createdAt": 1544177654000,
            "updatedAt": 1544178733000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_withdrawals(currency=None, status=None, start=None, end=None, page=None, limit=None)[source]

Get deposit records for a currency

https://docs.kucoin.com/#get-withdrawals-list

Parameters:
  • currency (string) – Name of currency (optional)
  • status (string) – optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Page to fetch
  • limit (int) – (optional) Number of transactions
withdrawals = client.get_withdrawals('NEO')
Returns:ApiResponse
{
    "currentPage": 1,
    "pageSize": 10,
    "totalNum": 1,
    "totalPage": 1,
    "items": [
        {
            "id": "5c2dc64e03aa675aa263f1ac",
            "address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9",
            "memo": "",
            "currency": "ETH",
            "amount": 1.0000000,
            "fee": 0.0100000,
            "walletTxId": "3e2414d82acce78d38be7fe9",
            "isInner": false,
            "status": "FAILURE",
            "createdAt": 1546503758000,
            "updatedAt": 1546504603000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_withdrawal_quotas(currency)[source]

Get withdrawal quotas for a currency

https://docs.kucoin.com/#get-withdrawal-quotas

Parameters:currency (string) – Name of currency
quotas = client.get_withdrawal_quotas('ETH')
Returns:ApiResponse
{
    "currency": "ETH",
    "availableAmount": 2.9719999,
    "remainAmount": 2.9719999,
    "withdrawMinSize": 0.1000000,
    "limitBTCAmount": 2.0,
    "innerWithdrawMinFee": 0.00001,
    "isWithdrawEnabled": true,
    "withdrawMinFee": 0.0100000,
    "precision": 7
}
Raises:KucoinResponseException, KucoinAPIException
create_withdrawal(currency, amount, address, memo=None, is_inner=False, remark=None)[source]

Process a withdrawal

https://docs.kucoin.com/#apply-withdraw

Parameters:
  • currency (string) – Name of currency
  • amount (number) – Amount to withdraw
  • address (string) – Address to withdraw to
  • memo (string) – (optional) Remark to the withdrawal address
  • is_inner (bool) – (optional) Remark to the withdrawal address
  • remark (string) – (optional) Remark
withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851')
Returns:ApiResponse
{
    "withdrawalId": "5bffb63303aa675e8bbe18f9"
}
Raises:KucoinResponseException, KucoinAPIException
cancel_withdrawal(withdrawal_id)[source]

Cancel a withdrawal

https://docs.kucoin.com/#cancel-withdrawal

Parameters:withdrawal_id (string) – ID of withdrawal
client.cancel_withdrawal('5bffb63303aa675e8bbe18f9')
Returns:None
Raises:KucoinResponseException, KucoinAPIException
create_market_order(symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None)[source]

Create a market order

One of size or funds must be set

https://docs.kucoin.com/#place-a-new-order

Parameters:
  • symbol (string) – Name of symbol e.g. KCS-BTC
  • side (string) – buy or sell
  • size (string) – (optional) Desired amount in base currency
  • funds (string) – (optional) Desired amount of quote currency to use
  • client_oid (string) – (optional) Unique order id (default flat_uuid())
  • remark (string) – (optional) remark for the order, max 100 utf8 characters
  • stp (string) – (optional) self trade protection CN, CO, CB or DC (default is None)
order = client.create_market_order('NEO', Client.SIDE_BUY, size=20)
Returns:ApiResponse
{
    "orderOid": "596186ad07015679730ffa02"
}
Raises:KucoinResponseException, KucoinAPIException, MarketOrderException
create_limit_order(symbol, side, price, size, client_oid=None, remark=None, time_in_force=None, stop=None, stop_price=None, stp=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None)[source]

Create an order

https://docs.kucoin.com/#place-a-new-order

Parameters:
  • symbol (string) – Name of symbol e.g. KCS-BTC
  • side (string) – buy or sell
  • price (string) – Name of coin
  • size (string) – Amount of base currency to buy or sell
  • client_oid (string) – (optional) Unique order_id default flat_uuid()
  • remark (string) – (optional) remark for the order, max 100 utf8 characters
  • stp (string) – (optional) self trade protection CN, CO, CB or DC (default is None)
  • time_in_force (string) – (optional) GTC, GTT, IOC, or FOK (default is GTC)
  • stop (string) – (optional) stop type loss or entry - requires stop_price
  • stop_price (string) – (optional) trigger price for stop order
  • cancel_after (string) – (optional) number of seconds to cancel the order if not filled required time_in_force to be GTT
  • post_only (bool) – (optional) indicates that the order should only make liquidity. If any part of the order results in taking liquidity, the order will be rejected and no part of it will execute.
  • hidden (bool) – (optional) Orders not displayed in order book
  • iceberg (bool) – (optional) Only visible portion of the order is displayed in the order book
  • visible_size (bool) – (optional) The maximum visible size of an iceberg order
order = client.create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000')
Returns:ApiResponse
{
    "orderOid": "596186ad07015679730ffa02"
}
Raises:KucoinResponseException, KucoinAPIException, LimitOrderException
cancel_order(order_id)[source]

Cancel an order

https://docs.kucoin.com/#cancel-an-order

Parameters:order_id (string) – Order id
res = client.cancel_order('5bd6e9286d99522a52e458de)
Returns:ApiResponse
{
    "cancelledOrderIds": [
        "5bd6e9286d99522a52e458de"
    ]
}
Raises:KucoinResponseException, KucoinAPIException

KucoinAPIException If order_id is not found

cancel_all_orders(symbol=None)[source]

Cancel all orders

https://docs.kucoin.com/#cancel-all-orders

res = client.cancel_all_orders()
Returns:ApiResponse
{
    "cancelledOrderIds": [
        "5bd6e9286d99522a52e458de"
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_orders(symbol=None, status=None, side=None, order_type=None, start=None, end=None, page=None, limit=None)[source]

Get list of orders

https://docs.kucoin.com/#list-orders

Parameters:
  • symbol (string) – (optional) Name of symbol e.g. KCS-BTC
  • status (string) – (optional) Specify status active or done (default done)
  • side (string) – (optional) buy or sell
  • order_type (string) – (optional) limit, market, limit_stop or market_stop
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Page to fetch
  • limit (int) – (optional) Number of orders
orders = client.get_orders(symbol='KCS-BTC', status='active')
Returns:ApiResponse
{
    "currentPage": 1,
    "pageSize": 1,
    "totalNum": 153408,
    "totalPage": 153408,
    "items": [
        {
            "id": "5c35c02703aa673ceec2a168",
            "symbol": "BTC-USDT",
            "opType": "DEAL",
            "type": "limit",
            "side": "buy",
            "price": "10",
            "size": "2",
            "funds": "0",
            "dealFunds": "0.166",
            "dealSize": "2",
            "fee": "0",
            "feeCurrency": "USDT",
            "stp": "",
            "stop": "",
            "stopTriggered": false,
            "stopPrice": "0",
            "timeInForce": "GTC",
            "postOnly": false,
            "hidden": false,
            "iceberge": false,
            "visibleSize": "0",
            "cancelAfter": 0,
            "channel": "IOS",
            "clientOid": null,
            "remark": null,
            "tags": null,
            "isActive": false,
            "cancelExist": false,
            "createdAt": 1547026471000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_historical_orders(symbol=None, side=None, start=None, end=None, page=None, limit=None)[source]

List of KuCoin V1 historical orders.

https://docs.kucoin.com/#get-v1-historical-orders-list

Parameters:
  • symbol (string) – (optional) Name of symbol e.g. KCS-BTC
  • side (string) – (optional) buy or sell
  • start (string) – (optional) Start time as unix timestamp
  • end (string) – (optional) End time as unix timestamp
  • page (int) – (optional) Page to fetch
  • limit (int) – (optional) Number of orders
orders = client.get_historical_orders(symbol='KCS-BTC')
Returns:ApiResponse
{
    "currentPage": 1,
    "pageSize": 50,
    "totalNum": 1,
    "totalPage": 1,
    "items": [
        {
            "symbol": "SNOV-ETH",
            "dealPrice": "0.0000246",
            "dealValue": "0.018942",
            "amount": "770",
            "fee": "0.00001137",
            "side": "sell",
            "createdAt": 1540080199
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_order(order_id)[source]

Get order details

https://docs.kucoin.com/#get-an-order

Parameters:order_id (str) – orderOid value
order = client.get_order('5c35c02703aa673ceec2a168')
Returns:ApiResponse
{
    "id": "5c35c02703aa673ceec2a168",
    "symbol": "BTC-USDT",
    "opType": "DEAL",
    "type": "limit",
    "side": "buy",
    "price": "10",
    "size": "2",
    "funds": "0",
    "dealFunds": "0.166",
    "dealSize": "2",
    "fee": "0",
    "feeCurrency": "USDT",
    "stp": "",
    "stop": "",
    "stopTriggered": false,
    "stopPrice": "0",
    "timeInForce": "GTC",
    "postOnly": false,
    "hidden": false,
    "iceberge": false,
    "visibleSize": "0",
    "cancelAfter": 0,
    "channel": "IOS",
    "clientOid": null,
    "remark": null,
    "tags": null,
    "isActive": false,
    "cancelExist": false,
    "createdAt": 1547026471000
}
Raises:KucoinResponseException, KucoinAPIException
get_fills(order_id=None, symbol=None, side=None, order_type=None, start=None, end=None, page=None, limit=None)[source]

Get a list of recent fills.

https://docs.kucoin.com/#list-fills

Parameters:
  • order_id (string) – (optional) generated order id
  • symbol (string) – (optional) Name of symbol e.g. KCS-BTC
  • side (string) – (optional) buy or sell
  • order_type (string) – (optional) limit, market, limit_stop or market_stop
  • start (string) – Start time as unix timestamp (optional)
  • end (string) – End time as unix timestamp (optional)
  • page (int) – optional - Page to fetch
  • limit (int) – optional - Number of orders
fills = client.get_fills()
Returns:ApiResponse
{
    "currentPage":1,
    "pageSize":1,
    "totalNum":251915,
    "totalPage":251915,
    "items":[
        {
            "symbol":"BTC-USDT",
            "tradeId":"5c35c02709e4f67d5266954e",
            "orderId":"5c35c02703aa673ceec2a168",
            "counterOrderId":"5c1ab46003aa676e487fa8e3",
            "side":"buy",
            "liquidity":"taker",
            "forceTaker":true,
            "price":"0.083",
            "size":"0.8424304",
            "funds":"0.0699217232",
            "fee":"0",
            "feeRate":"0",
            "feeCurrency":"USDT",
            "stop":"",
            "type":"limit",
            "createdAt":1547026472000
        }
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_symbols()[source]

Get a list of available currency pairs for trading.

https://docs.kucoin.com/#symbols-amp-ticker

symbols = client.get_symbols()
Returns:ApiResponse
[
    {
        "symbol": "BTC-USDT",
        "name": "BTC-USDT",
        "baseCurrency": "BTC",
        "quoteCurrency": "USDT",
        "baseMinSize": "0.00000001",
        "quoteMinSize": "0.01",
        "baseMaxSize": "10000",
        "quoteMaxSize": "100000",
        "baseIncrement": "0.00000001",
        "quoteIncrement": "0.01",
        "priceIncrement": "0.00000001",
        "enableTrading": true
    }
]
Raises:KucoinResponseException, KucoinAPIException
get_ticker(symbol=None)[source]

Get symbol tick

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

Parameters:symbol (string) – (optional) Name of symbol e.g. KCS-BTC
all_ticks = client.get_ticker()

ticker = client.get_ticker('ETH-BTC')
Returns:ApiResponse
{
    "sequence": "1545825031840",      # now sequence
    "price": "3494.367783",           # last trade price
    "size": "0.05027185",             # last trade size
    "bestBid": "3494.367783",         # best bid price
    "bestBidSize": "2.60323254",      # size at best bid price
    "bestAsk": "3499.12",             # best ask price
    "bestAskSize": "0.01474011"       # size at best ask price
}
Raises:KucoinResponseException, KucoinAPIException
get_fiat_prices(base=None, symbol=None)[source]

Get fiat price for currency

https://docs.kucoin.com/#get-fiat-price

Parameters:
  • base (string) – (optional) Fiat,eg.USD,EUR, default is USD.
  • symbol (string) – (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with comma one by one. default is all
prices = client.get_fiat_prices()
Returns:ApiResponse
{
    "BTC": "3911.28000000",
    "ETH": "144.55492453",
    "LTC": "48.45888179",
    "KCS": "0.45546856"
}
Raises:KucoinResponseException, KucoinAPIException
get_24hr_stats(symbol)[source]

Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units.

Parameters:symbol (string) – (optional) Name of symbol e.g. KCS-BTC
stats = client.get_24hr_stats('ETH-BTC')
Returns:ApiResponse

Without a symbol param

{
    "symbol": "BTC-USDT",
    "changeRate": "0.0128",   # 24h change rate
    "changePrice": "0.8",     # 24h rises and falls in price (if the change rate is a negative number,
                              # the price rises; if the change rate is a positive number, the price falls.)
    "open": 61,               # Opening price
    "close": 63.6,            # Closing price
    "high": "63.6",           # Highest price filled
    "low": "61",              # Lowest price filled
    "vol": "244.78",          # Transaction quantity
    "volValue": "15252.0127"  # Transaction amount
}
Raises:KucoinResponseException, KucoinAPIException
get_markets()[source]

Get supported market list

https://docs.kucoin.com/#get-market-list

markets = client.get_markets()
Returns:ApiResponse
{
    "data": [
        "BTC",
        "ETH",
        "USDT"
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_order_book(symbol)[source]

Get a list of bids and asks aggregated by price for a symbol.

Returns up to 100 depth each side. Fastest Order book API

https://docs.kucoin.com/#get-part-order-book-aggregated

Parameters:symbol (string) – Name of symbol e.g. KCS-BTC
orders = client.get_order_book('KCS-BTC')
Returns:ApiResponse
{
    "sequence": "3262786978",
    "bids": [
        ["6500.12", "0.45054140"],  # [price, size]
        ["6500.11", "0.45054140"]
    ],
    "asks": [
        ["6500.16", "0.57753524"],
        ["6500.15", "0.57753524"]
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_full_order_book(symbol)[source]

Get a list of all bids and asks aggregated by price for a symbol.

This call is generally used by professional traders because it uses more server resources and traffic, and Kucoin has strict access frequency control.

https://docs.kucoin.com/#get-full-order-book-aggregated

Parameters:symbol (string) – Name of symbol e.g. KCS-BTC
orders = client.get_order_book('KCS-BTC')
Returns:ApiResponse
{
    "sequence": "3262786978",
    "bids": [
        ["6500.12", "0.45054140"],  # [price size]
        ["6500.11", "0.45054140"]
    ],
    "asks": [
        ["6500.16", "0.57753524"],
        ["6500.15", "0.57753524"]
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_full_order_book_level3(symbol)[source]

Get a list of all bids and asks non-aggregated for a symbol.

This call is generally used by professional traders because it uses more server resources and traffic, and Kucoin has strict access frequency control.

https://docs.kucoin.com/#get-full-order-book-atomic

Parameters:symbol (string) – Name of symbol e.g. KCS-BTC
orders = client.get_order_book('KCS-BTC')
Returns:ApiResponse
{
    "sequence": "1545896707028",
    "bids": [
        [
            "5c2477e503aa671a745c4057",   # orderId
            "6",                          # price
            "0.999"                       # size
        ],
        [
            "5c2477e103aa671a745c4054",
            "5",
            "0.999"
        ]
    ],
    "asks": [
        [
            "5c24736703aa671a745c401e",
            "200",
            "1"
        ],
        [
            "5c2475c903aa671a745c4033",
            "201",
            "1"
        ]
    ]
}
Raises:KucoinResponseException, KucoinAPIException
get_trade_histories(symbol)[source]

List the latest trades for a symbol

https://docs.kucoin.com/#get-trade-histories

Parameters:symbol (string) – Name of symbol e.g. KCS-BTC
orders = client.get_trade_histories('KCS-BTC')
Returns:ApiResponse
[
    {
        "sequence": "1545896668571",
        "price": "0.07",                # Filled price
        "size": "0.004",                # Filled amount
        "side": "buy",                  # Filled side. The filled side is set to the taker by default.
        "time": 1545904567062140823     # Transaction time
    },
    {
        "sequence": "1545896668578",
        "price": "0.054",
        "size": "0.066",
        "side": "buy",
        "time": 1545904581619888405
    }
]
Raises:KucoinResponseException, KucoinAPIException
get_kline_data(symbol, kline_type='5min', start=None, end=None)[source]

Get kline data

For each query, the system would return at most 1500 pieces of data. To obtain more data, please page the data by time.

Parameters:
  • symbol (string) – Name of symbol e.g. KCS-BTC
  • kline_type (string) – type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour, 4hour, 6hour, 8hour, 12hour, 1day, 1week
  • start (int) – Start time as unix timestamp (optional) default start of day in UTC
  • end (int) – End time as unix timestamp (optional) default now in UTC

https://docs.kucoin.com/#get-historic-rates

klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278)
Returns:ApiResponse
[
    [
        "1545904980",             //Start time of the candle cycle
        "0.058",                  //opening price
        "0.049",                  //closing price
        "0.058",                  //highest price
        "0.049",                  //lowest price
        "0.018",                  //Transaction amount
        "0.000945"                //Transaction volume
    ],
    [
        "1545904920",
        "0.058",
        "0.072",
        "0.072",
        "0.058",
        "0.103",
        "0.006986"
    ]
]
Raises:KucoinResponseException, KucoinAPIException
get_ws_endpoint(private=False)[source]

Get websocket channel details

Parameters:private (bool) – Name of symbol e.g. KCS-BTC

https://docs.kucoin.com/#websocket-feed

ws_details = client.get_ws_endpoint(private=True)
Returns:ApiResponse
{
    "code": "200000",
    "data": {
        "instanceServers": [
            {
                "pingInterval": 50000,
                "endpoint": "wss://push1-v2.kucoin.net/endpoint",
                "protocol": "websocket",
                "encrypt": true,
                "pingTimeout": 10000
            }
        ],
        "token": "vYNlCtbz4XNJ1QncwWilJnBtmmfe4geLQDUA62kKJsDChc6I4bRDQc73JfIrlFaVYIAE0Gv2--MROnLAgjVsWkcDq_MuG7qV7EktfCEIphiqnlfpQn4Ybg==.IoORVxR2LmKV7_maOR9xOg=="
    }
}
Raises:KucoinResponseException, KucoinAPIException
exceptions module
exception kucoin.exceptions.KucoinAPIException(response)[source]

Bases: exceptions.Exception

Exception class to handle general API Exceptions

code values

message format

__init__(response)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception kucoin.exceptions.KucoinRequestException(message)[source]

Bases: exceptions.Exception

__init__(message)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception kucoin.exceptions.MarketOrderException(message)[source]

Bases: exceptions.Exception

__init__(message)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception kucoin.exceptions.LimitOrderException(message)[source]

Bases: exceptions.Exception

__init__(message)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

Index