Coder Social home page Coder Social logo

kucoin-python-sdk's Introduction

Welcome to python-kucoin-sdk

https://img.shields.io/pypi/l/python-kucoin https://img.shields.io/badge/python-3.6%2B-green .red {color:IndianRed;}

Features

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

update

  • 2024 08/19
  1. 【FIX】 Fix the issue with incorrect fields in the parameters.
  • 2024 07/25
  1. 【NEW】GET /api/v3/hf/margin/order/active/symbols: Margin.get_active_hf_order_symbols
  2. 【NEW】GET /api/v3/margin/symbols: Margin.get_cross_margin_trading_pairs_configuration
  3. 【NEW】POST /api/v3/position/update-user-leverage: Margin.modify_leverage_multiplier
  4. 【NEW】GET /api/v1/otc-loan/loan: Margin.get_information_onoff_exchange_funding_and_loans
  5. 【NEW】GET /api/v1/otc-loan/accounts: Margin.get_information_on_accounts_involved_in_off_exchange_loans
  6. 【UPDATE】POST /api/v3/margin/borrow -add isHf: Margin.margin_borrowing
  7. 【UPDATE】POST /api/v3/margin/repay -add isHf: Margin.repayment
  8. 【NEW】POST /api/v3/hf/margin/order: Margin.place_hf_order
  9. 【NEW】POST /api/v3/hf/margin/order/test: Margin.place_hf_order_test
  10. 【NEW】DELETE /api/v3/hf/margin/orders/{orderId}: Margin.cancel_hf_order_by_orderid
  11. 【NEW】DELETE /api/v3/hf/margin/orders/client-order/{clientOid}: Margin.cancel_hf_order_by_clientoid
  12. 【NEW】DELETE /api/v3/hf/margin/orders: Margin.cancel_all_hf_orders_by_symbol
  13. 【NEW】GET /api/v3/hf/margin/orders/active: Margin.get_active_hf_orders_list
  14. 【NEW】GET /api/v3/hf/margin/orders/done: Margin.get_hf_filled_list
  15. 【NEW】GET /api/v3/hf/margin/orders/{orderId}: Margin.get_hf_order_details_by_orderid
  16. 【NEW】GET /api/v3/hf/margin/orders/client-order/{clientOid}: Margin.get_hf_order_details_by_clientoid
  17. 【NEW】GET /api/v3/hf/margin/fills: Margin.get_hf_transaction_records
  18. 【NEW】GET /api/v3/currencies/{currency}: Market.get_currency_detail_v3
  • 2024 07/07
  1. [NEW] POST /api/v1/earn/orders: Earn.subscribe_to_earn_fixed_income_products
  2. [NEW] DELETE /api/v1/earn/orders: Earn.redeem_by_earn_holding_id
  3. [NEW] GET /api/v1/earn/redeem-preview: Earn.get_earn_redeem_preview_by_holding_id
  4. [NEW] GET /api/v1/earn/saving/products: Earn.get_earn_savings_products
  5. [NEW] GET /api/v1/earn/hold-assets: Earn.get_earn_fixed_income_current_holdings
  6. [NEW] GET /api/v1/earn/promotion/products: Earn.get_earn_limited_time_promotion_products
  7. [NEW] GET /api/v1/earn/kcs-staking/products: Earn.get_earn_kcs_staking_products
  8. [NEW] GET /api/v1/earn/staking/products: Earn.get_earn_staking_products
  9. [NEW] GET /api/v1/earn/eth-staking/products: Earn.get_earn_eth_staking_products
  • 2024 02/26
  1. add Api: margin.get_interest_rates: Get Interest Rates.
  • 2024 02/19
  1. trade.get_hf_filled_list: same to trade.get_hf_transaction_records Get HF Filled List
  • The trade.get_hf_transaction_records method will be removed at some time in the future
  1. trade.get_hf_completed_orders: same to trade.get_filled_hf_order Get HF Completed order list
  • The trade.get_filled_hf_order method will be removed at some time in the future
  • 2024 02/07
  1. margin.get_etf_info: Get Leveraged Token Info.
  2. margin.get_margin_account_Detail: Get Account Detail - Cross Margin.
  3. margin.get_isolated_margin_account_detail: Get Account Detail - Isolated Margin.
  4. margin.get_margin_currencies: Get Cross/Isolated Margin Risk Limit/Currency config.
  5. trade.create_oco_order: Place Order.
  6. trade.cancel_oco_order: Cancel Order by orderId.
  7. trade.cancel_oco_order_by_clientOid: Cancel Order by clientOid.
  8. trade.cancel_all_oco_orders: Cancel Multiple Orders.
  9. trade.get_oco_order_by_orderId: Get Order Info by orderId.
  10. trade.get_oco_order_by_client_oid: Get Order Info by clientOid.
  11. trade.get_oco_orders: Get Order List.
  12. trade.get_oco_order_details: Get Order Details by orderId.
  13. trade.cancel_all_hf_orders: Cancel all HF orders.
  14. customized websocket: ./kucoin/example_customized_ws_private.py | kucoin/example_customized_ws_public.py
  • sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  1. set api TCP_NODELAY:After instantiating the client, you can cancel the Nagle algorithm through client.TCP_NODELAY=1 (default is 0)
  • kucoin/example_client_TCP_NODELAY.py

Quick Start

Register an account with KuCoin.

Generate an API Key and enable it.

pip install kucoin-python
#  MarketData
from kucoin.client import Market
client = Market(url='https://api.kucoin.com')
# client = Market()



# get symbol kline
klines = client.get_kline('BTC-USDT','1min')

# get symbol ticker
server_time = client.get_server_timestamp()

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

# Trade
from kucoin.client import Trade
client = Trade(key='', secret='', passphrase='', url='')



# place a limit buy order
order_id = client.create_limit_order('BTC-USDT', 'buy', '1', '8000')

# place a market buy order   Use cautiously
order_id = client.create_market_order('BTC-USDT', 'buy', size='1')

# cancel limit order
client.cancel_order('5bd6e9286d99522a52e458de')

# User
from kucoin.client import User
client = User(api_key, api_secret, api_passphrase)



address = client.get_withdrawal_quota('KCS')

Websockets

  • ./kucoin/example/example_customized_ws_private.py
  • ./kucoin/example/example_default_ws_public.py

kucoin-python-sdk's People

Contributors

1bazinga25 avatar allenye1024 avatar codewc avatar freemind001 avatar isaac-xxyyzz avatar ive20 avatar jasonyao2107 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kucoin-python-sdk's Issues

Cancel order error

Hi,
I'm trying to implement an order cancel test.
The order works fine
Trade_client = Trade(key=api_key, secret=api_secret, passphrase=api_passphrase, is_sandbox=False, url='')
order_id = Trade_client.create_market_order('NANO-USDT', 'buy', size='1')`

I wait 5 second and I make a cancel order to stop it
Trade_client.cancel_order(order_id['orderId'])
and I've an error
200-{"code":"400100","msg":"order_not_exist_or_not_allow_to_cancel"}

Could you help me.
Thanks

/api/v1/trade-fees?symbols=BTC-USDT error

When I try executing the api call /api/v1/trade-fees?symbols=BTC-USDT I receive the following error
Exception: 400-{"code":"400001","msg":"Please check the header of your request for KC-API-KEY, KC-API-SIGN, KC-API-TIMESTAMP, KC-API-PASSPHRASE"}

Take into account that I am using the library and all other functions seem to work.

get_kline function isn't returning specified dates/times

import datetime
import time

t_start = datetime.datetime(2021, 1, 1)
t_start = time.mktime(t_start.timetuple())

t_stop = datetime.datetime(2021, 2, 1)
t_stop = time.mktime(t_start.timetuple())

data = marketclient.get_kline('REQ-BTC', '1min', startAt=t_start, endAt=t_stop)

all returned data is the present day - 1500 pieces of data, whether that be 1min or 1day etc...

Private webscoket connection never connects

hi,

im using the following bit of code
async def deal_msg(msg):
print (msg)
ws_client = await KucoinWsClient.create(None, client, deal_msg, private=True)
await ws_client.subscribe('/account/balance')
while True:
await asyncio.sleep(5)

The code just goes into a loop at does nothing. I am not receiving any errors stating that the topic is bad
I can use the REST api just fine to see my account balance
I can also use the socket connection for market data with private='False'

Thanks a lot for your help

{"code":"100003","msg":"Contract parameter invalid"}

Source

from kucoin.client import Trade

api_key = 'xxxxxx'
api_secret = 'xxxxxx'
api_passphrase = 'xxxxxx'

client = Trade(key=api_key, secret=api_secret, passphrase=api_passphrase, is_sandbox=False, url='https://api-futures.kucoin.com')

order_id = client.create_limit_order('GMT-USDT', 'sell', '5', '1.01')
print(order_id)

Log

C:\Users\MAX\Documents>python trade.py
Traceback (most recent call last):
  File "C:\Users\MAX\Documents\trade.py", line 13, in <module>
    order_id = client.create_limit_order('GMT-USDT', 'sell', '5', '1.01')
  File "C:\Users\MAX\AppData\Local\Programs\Python\Python310\lib\site-packages\kucoin\trade\trade.py", line 99, in create_limit_order
    return self._request('POST', '/api/v1/orders', params=params)
  File "C:\Users\MAX\AppData\Local\Programs\Python\Python310\lib\site-packages\kucoin\base_request\base_request.py", line 99, in _request
    return self.check_response_data(response_data)
  File "C:\Users\MAX\AppData\Local\Programs\Python\Python310\lib\site-packages\kucoin\base_request\base_request.py", line 116, in check_response_data
    raise Exception("{}-{}".format(response_data.status_code, response_data.text))
Exception: 200-{"code":"100003","msg":"Contract parameter invalid"}

运行出现错误的一些说明,解决各种bug问题指示贴

截止到:2021年3月18日

首先这玩意需要翻墙,不翻墙获取不到数据。
解决好翻墙问题,配置好

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

之后,第一个demo就能够正常获取。

关于第二个demo(Websockets),使用如下代码可以正确运行:

import asyncio
from kucoin.client import WsToken
from kucoin.ws_client import KucoinWsClient

async def main():
    async def deal_msg(msg):
        if msg['topic'] == '/spotMarket/level3:BTC-USDT':
            print(msg)
        elif msg['topic'] == '/spotMarket/level3:KCS-USDT':
            print(msg)

    # is public
    client = WsToken()
    ws_client = await KucoinWsClient.create(None, client, deal_msg, private=False)

    await ws_client.subscribe('/spotMarket/level3:BTC-USDT,KCS-USDT')
    while True:
        await asyncio.sleep(5, loop=loop)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

这个案例有如下几点需要注意:
1、案例没有及时更新, /market/level3: 要改为 /spotMarket/level3:
2、要使用共有频道,其他频道存在一定的问题,比如说私有频道只能获取与自己相关的订单数据,所以如果你自己没有触发订单的话就什么数据也获取不了;使用沙盒模式由于沙盒模式成交非常的清淡,所以获取的数据很少,你要等很久才能获取一些交易订单信息。共有频道可以获取所有交易订单的实时信息,这个不存在上面的问题。

最后,感谢KuCoin官方团队成员(微信号:API_KuCoin01)给我的帮助,这才解决以上问题。

Building local orderbook

I am able to get a Rest-API snapshot of an orderbook. I built the logic to update the orderbook-snapshot from the Rest-API with updates from the Websocket-API.
But I really struggle with the calibration procedure. How can I combine the continuous data stream, from the right msg onwards, with the snapshot? I did not succeed in feeding both the msg and the orderbook in my function "update orderbook".

Thx a lot

account not exist

I am trying to do

acc = client.get_account('XXX')

where XXX is my 8 digit account UID. When i do this i get: Exception: 200-{"code":"230008","msg":"account not exist"}

Should I not be using UID for this?

Unkown error for create_market_order

this issue occurs for any size:

Code > order_id = client.create_market_order('BTC-USDT', 'buy' , size = '1')
Response > 200-{"code":"300000","msg":"Order price invalid."}

I test it with the sandbox key.
no problem with create_limit_order has been seen.

Market.get_all_tickers() mixes up the columns 'baseCurrency' and 'quoteCurrency'

Market.get_all_tickers() mixes up the columns 'baseCurrency' and 'quoteCurrency'
The proper definitions:
'quoteCurrency' is the currency being bought or sold
'baseCurrency is the currency used to represent the quoteCurrency's value.
E.g. in the pair BTC-USDT = 58000, BTC is the quote currency and the USDT is the base currency. The value of 58000 indicates the value of 1 BTC in units of USDT.
It would be difficult to fix this problem because it will break systems that use the API. Perhaps you can make it clear in the docs that this error exists?
https://docs.kucoin.com/#get-symbols-list

How to track more than 100 pairs?

I have this error when I try to track more than 100 pairs.

{'id': 'xxxx', 'type': 'error', 'code': 509, 'data': 'exceed max subscription count limitation of 100 per time'}

Can't find how to do.

ConnectWebsocket _run() never completes

I'm using python 3.8.6. Upon connecting to the websocket and subscribing, I am getting no output. It seems the problem is websocket.py. I added some print statements to ConnectWebsocket's _run() to demonstrate the issue:


async def _run(self):
        keep_alive = True
        self._last_ping = time.time()  # record last ping
        self._ws_details = None
        self._ws_details = self._client.get_ws_token(self._private)
        print('this prints')
        async with websockets.connect(self.get_ws_endpoint(), ssl=self.get_ws_encryption()) as socket:
            print('this never prints')
            self._socket = socket
            self._reconnect_num = 0
            try:
                while keep_alive:
                    if time.time() - self._last_ping > self.get_ws_pingtimeout():
                        await self.send_ping()
                    try:
                        _msg = await asyncio.wait_for(self._socket.recv(), timeout=self.get_ws_pingtimeout())
                    except asyncio.TimeoutError:
                        await self.send_ping()
                    except asyncio.CancelledError:
                        await self._socket.ping()
                    else:
                        try:
                            msg = json.loads(_msg)
                        except ValueError:
                            pass
                        else:
                            await self._callback(msg)
            except websockets.ConnectionClosed:
                print('this never prints')
                await self._reconnect()
            except Exception as e:
                print('this never prints')
                await self._reconnect()

As far as I know, self.get_ws_endpoint(), ssl=self.get_ws_encryption() both have valid return values. get_ws_endpoint() returns a URL and get_ws_encryption() returns a Boolean. I didn't check the URL though to make sure it's good.

Does anyone have a solution? Currently, I cannot receive any messages from the socket.

Thank you for the help!!

get_ticker timestamps incorrect?

Every 5 seconds I retrieve the ticker of HNT-USDT. It seems the times returned from the request are off and also jump back and forth. Here is the code:

import time
import datetime
from kucoin.client import Client

kucoin_client = Client('', '', '')

i = 0
while True:

    start = time.time()      # now in seconds

    kucoin_ticker = kucoin_client.get_ticker('IOTA-USDT')
    kucoin_time = float(kucoin_ticker['time'])

    time_system = datetime.datetime.fromtimestamp( start )
    time_ticker = datetime.datetime.fromtimestamp( kucoin_ticker['time'] / 1000 )

    print(f'time of now: {time_system}')
    print(f'time ticker: {time_ticker}')
    print()

    # break condition
    wait = 5 - (time.time() - start)  # wait 5 seconds minus execution time of iteration
    time.sleep(wait)
    i += 1
    if i >= 20:
        break

The code results in an output like so:

time of now: 2022-01-07 09:50:20
time ticker : 2022-01-07 09:50:12

time of now: 2022-01-07 09:50:25
time ticker : 2022-01-07 09:50:12

time of now: 2022-01-07 09:50:30
time ticker : 2022-01-07 09:50:12

time of now: 2022-01-07 09:50:35
time ticker : 2022-01-07 09:50:32

time of now: 2022-01-07 09:50:40
time ticker : 2022-01-07 09:50:40

time of now: 2022-01-07 09:50:45
time ticker : 2022-01-07 09:50:35

As can be seen, the "time of now" behaves as expected (increasxing by 5 seconds each), however, the ticker times jump back and forth for which I have no explanation. For assets with high volatility (e.g. BTC, ETH) this problem does not occur. I therefore suspect it's related to the last price made, still that wouldn't explain why the ticker times can jump also backwards in time when it shouldn't (see last two ticker times). Any idea / explanation why this is observed? Thanks!

market api get_aggregated_orderv3 error

When I try executing the function get_aggregated_orderv3 I receive the following error
Exception: 400-{"code":"400001","msg":"Please check the header of your request for KC-API-KEY, KC-API-SIGN, KC-API-TIMESTAMP, KC-API-PASSPHRASE"}

Take into account that I am using the library and all other functions seem to work.

Instructions for Use

I have everything setup but don't know how to run the program. Are there instructions on what to do once API is connected?

ORDER_MARKET_STOP in create_limit_order or create_market_order? And how to use?

I am trying to figure out ORDER_MARKET_STOP (or ORDER_LIMIT_STOP), but I'm not sure if I'm supposed to use in the the create_market_order or in the create_limit_order with a stop option.

I have vigorously tried with both to no success. I figure it would work in create_limit_order, I add STOP_LOSS, it asks for stop_price

I am stuck with limit orders which earmark my funds for each order and make it impossible to place multiple "stops." So I am still placing stops manually.

Thank you for your great work on this! It's a life saver.

kucoin question

is there a way to get the favorites list using the api? the list is stored remotely .it opens on phone and website. thanks

Using mod'd client.create_limit_stop_order() to post to margin account

Love the sdk and making some good progress as a noob Pythoner. I'm currently using modified client.create_limit_stop_order() in Trade.py to post stop limit orders in a margin account. So far so good BUT, the orders are going in as SPOT, not default cross.

I've never done git pull requests and not set up on GH just yet but could we get an update to Trade.py to make a new method?
client.create_limit_stop_margin_order()

with a cross, isolated and spot option selection would be very slick.

Thank you!

` def create_limit_stop_order(self, symbol, side, size, price, stopPrice, clientOid="", **kwargs):

    """ Modified limit stop order for margin """

    params = {
        'symbol': symbol,
        'side': side,
        'size': size,
        'price': price,
        'stopPrice': stopPrice,
        'type': "limit",
        'remark': 'API testing',
        'tradeType': 'MARGIN_TRADE',
        'marginMode' : 'cross'
    }

    if not clientOid:
        clientOid = self.return_unique_id

    params['clientOid'] = clientOid

    if kwargs:
        params.update(kwargs)

    return self._request('POST', '/api/v1/margin/stop-order', params=params)`

Timeout issue with `get_fill_list`

Hi,

I'm trying to get a the fills list and the following code returns HTTP timeout error. If I modify the library code and increase the timeout from 5 to 50 secs, I get a HTML dump of cloudflare page: https://pastebin.com/yQzsCNrQ

Code:

from kucoin.client import Trade
api_key = "..."
api_secret = "..."
api_passphrase = "..."
client = Trade(api_key, api_secret, api_passphrase, is_sandbox=True)
fill_list = client.get_fill_list(tradeType='TRADE') #error here

Also, running the following:

client.get_recent_fills()

returns the following error:

Exception: 401-{"code":"400003","msg":"KC-API-KEY not exists"}

How can I resolve this?

Change at websockets for python 3.10

Hi all,
i think the inital example at websockets has to be changed for Python 3.10 or there should be at least a note, so:

the following code is deprecated at works until Python 3.9:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

For Python 3.10 use instead:
loop = asyncio.run(main())

And until Python 3.9 works:
while True:
await asyncio.sleep(60, loop=loop)

For Python 3.10 use instead (just remove the loop argument):
while True:
await asyncio.sleep(60)

Can't withdraw on alternative chain

For example AVAX-C chain
kcn.api_user.apply_withdrawal(currency='AVAX', address=Address, amount=Amount, chainId='avaxc')
returns:
Exception: 200-{"code":"400100","msg":"Incorrect withdrawal address"}
I tried with 'AVAXC', 'AVAX-C' and others without success, while address is correct for AVAX-C coin...

sandbox Invalid request ip

same as in title,
added withdrawal permission in sandbox,
my ip address did not change

my request:

user_client = User(key=api_key, secret=api_secret, passphrase=api_passphrase, is_sandbox=True)
user_client.get_withdrawal_quota('BTC')

Exception: 403-{"code":"400006","msg":"Invalid request ip"}

Trade Market order fails with requests.exceptions.ReadTimeout

Trying to make an spot order in Sandbox gets mi the next error: ' requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='openapi-sandbox.kucoin.com', port=443): Read timed out'

I'm runing the script from a local env with pycharm and making a basic API request, not using websocket
i tried it with python 3.8, 3.9 and 3.10

any suggestion?

this is my basic code:

from kucoin.client import Market
from kucoin.client import Trade

client = Market(url='https://openapi-sandbox.kucoin.com')
client = Market(is_sandbox=True)

client = Trade(api_key, api_secret, api_passphrase, is_sandbox=True)
order_id = client.create_market_order('BTC-USDT', 'buy', size='1')

How to get KuCoin Trade Bot Transactions

I really need a way to pull all the trades from my trade bots. Is there a way to do this?

When I pull order history they are not included in that.

Any help would be greatly appreciated!!

Sell limit order

Hi, i was able to use variables where via prumpt you can type the coin you want to invest, purchase adn the amount, but i want to be able to use a limit sell order where i will be able to pick the amount i have purchased in the previous order, the price of the coin and then use calculate a 20% profit margin. DO you know how to do that?

client.create_market_order do nothin on sandbox

im trying to

client = Trade(key=api_key, secret=api_secret, passphrase=api_passphrase, is_sandbox=True)

print(client.create_market_order('BTC-USDT', 'buy', funds='100'))

and creates an order id , but then in the control panel of kucoin sandbox it dident buy btc

[ERROR] AttributeError: 'dict' object has no attribute 'encode'

[ERROR] AttributeError: 'dict' object has no attribute 'encode'Traceback (most recent call last):  

File "/var/task/kucoin_.py", line 32, in handler    lending_market = margin.get_lend_record()  File "/var/task/kucoin/margin/margin.py", line 384, in get_lend_record    return self._request('GET', '/api/v1/margin/lend/assets', params=params)  File "/var/task/kucoin/base_request/base_request.py", line 65, in _request    hmac.new(self.secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest()) | [ERROR] AttributeError: 'dict' object has no attribute 'encode' Traceback (most recent call last):   File "/var/task/kucoin_lambda.py", line 32, in lambda_handler     lending_market = margin.get_lend_record()   File "/var/task/kucoin/margin/margin.py", line 384, in get_lend_record     return self._request('GET', '/api/v1/margin/lend/assets', params=params)   File "/var/task/kucoin/base_request/base_request.py", line 65, in _request     hmac.new(self.secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())

Get Order Details doesn't provide price value (price comes back equal to 0)

When I try to get the order details after purchasing the price that shows there is 0. I'm wondering if this could be an API issue.

The code I used is:

from kucoin.client import Market
import keysKucoin
from kucoin.client import Trade
import json

client = Market(url='https://api.kucoin.com')

api_key = keysKucoin.APIkey
api_secret = keysKucoin.Secretkey
api_passphrase = keysKucoin.Passphrase

client = Trade(key=api_key, secret=api_secret, passphrase=api_passphrase, is_sandbox=False, url='')

order_id = client.create_market_order('NEO-USDT', 'buy', size='0.01')

order = client.get_order_details(order_id["orderId"])
print(json.dumps(order, indent=4, sort_keys=True))

and the print I get is

{
    "cancelAfter": 0,
    "cancelExist": false,
    "channel": "API",
    "clientOid": clientOid,
    "createdAt": 1619955054000,
    "dealFunds": "1.047733",
    "dealSize": "0.01",
    "fee": "0.001047733",
    "feeCurrency": "USDT",
    "funds": "0",
    "hidden": false,
    "iceberg": false,
    "id": id,
    "isActive": false,
    "opType": "DEAL",
    "postOnly": false,
    "price": "0",
    "remark": null,
    "side": "buy",
    "size": "0.01",
    "stop": "",
    "stopPrice": "0",
    "stopTriggered": false,
    "stp": "",
    "symbol": "NEO-USDT",
    "tags": null,
    "timeInForce": "GTC",
    "tradeType": "TRADE",
    "type": "market",
    "visibleSize": "0"
}

(The id and ClientOid fields are changed, I don't know if this information is dangerous to have public)

As you can see, the price in the response is 0, when it should be 104.7733

sandbox Get Withdrawal Quotas not working

same as title resource not works in sandbox

from kucoin.client import User
user_client = User(key=api_key, secret=api_secret, passphrase=api_passphrase, is_sandbox=True)
print(user_client.get_withdrawal_quota(currency='BTC'))

In [2]: response_data.text
Out[2]: '{"code":"500000","msg":"internal error"}'

from docs:

Example
GET /api/v1/withdrawals/quotas?currency=BTC

API KEY PERMISSIONS
This endpoint requires the "General" permission.

i have General permission
Screen Shot 2021-06-20 at 17 34 23

USDT from sell orders dissapear

Running a sell order in the sandbox. The USDT that should appear never do so. What is happening there?

Example:

  1. Before: 49,981 USDT, 0 BTC
  2. Buy BTC for one USDT (ID 623df0a80091a600016e893e)
  3. New Balance: 49,980 USDT, 0.0002324 BTC
  4. Sell all BTC available (ID 623df0e30091a600016e903f)
  5. Final balance: 49,980 USDT, 0 BTC

The JSON response when asking for trade details contains 'dealFunds': '0.004648' making me wonder if it means that somehow double the sell amount are fees, stagnating the USDT Balance.

create_market_order fails with "Funds increment invalid."

I've coded a bot to track cryptos and execute trades on my behalf when the time is right. However, every time it tries to perform a market order "buy" it fails with the following error.

ERROR:root:Failed to execute buy.
2022-01-19T03:56:25.573860+00:00 app[worker.1]: Traceback (most recent call last):
2022-01-19T03:56:25.573860+00:00 app[worker.1]:   File "main.py", line 47, in _execute_buy
2022-01-19T03:56:25.573861+00:00 app[worker.1]:     order_id = api.buy(crypto_pair, buy_amount)
2022-01-19T03:56:25.573861+00:00 app[worker.1]:   File "/app/lib/api.py", line 80, in buy
2022-01-19T03:56:25.573862+00:00 app[worker.1]:     response = trade_client.create_market_order(
2022-01-19T03:56:25.573864+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/kucoin/trade/trade.py", line 164, in create_market_order
2022-01-19T03:56:25.573865+00:00 app[worker.1]:     return self._request('POST', '/api/v1/orders', params=params)
2022-01-19T03:56:25.573865+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/kucoin/base_request/base_request.py", line 99, in _request
2022-01-19T03:56:25.573865+00:00 app[worker.1]:     return self.check_response_data(response_data)
2022-01-19T03:56:25.573866+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/kucoin/base_request/base_request.py", line 116, in check_response_data
2022-01-19T03:56:25.573867+00:00 app[worker.1]:     raise Exception("{}-{}".format(response_data.status_code, response_data.text))
2022-01-19T03:56:25.573867+00:00 app[worker.1]: Exception: 200-{"code":"400100","msg":"Funds increment invalid."}

Even though the API document says that the price increment is not required for marker orders: https://docs.kucoin.com/#place-a-new-order

Could anyone assist with this issue?
This is how my buying code looks using the library:

import uuid
from kucoin.client import Trade

trade_client = Trade(
    settings.API_KEY,
    settings.API_SECRET,
    settings.API_PASSPHRASE,
    is_sandbox=False,
)

def buy(symbol: strr, amount: float) -> str:
    """Buy a crypto-pair."""
    client_order_id = str(uuid.uuid4())
    response = trade_client.create_market_order(
        symbol,
        "buy",
        clientOid=client_order_id,
        type="market",
        funds=str(amount),
    )
   return response["orderId"]

Margin Orders?

Are margin orders allowed? If so, what's the syntax?
I see magin.py file but not sure how to call functions within that file.

position internal error

Getting this error on a market send request {'code': '200000', 'msg': 'position internal error'}

symbol = "1INCH/USDT"
side = "buy"
amount = 10
order_id = kt.market_order(symbol=symbol, 
                           side=side, 
                           amount=amount)

the market_order source

    def market_order(self, symbol: str, side: str, amount: float) -> str:
        """
        :param symbol: trading pare
        :param side: "buy"/"sell"
        :param amount:
        :return: order_id
        :raise: IncuficcientBallance, NetworkError
        """
        params = {
            "symbol": symbol,
            "side": side,
            "type": "market",
            "size": amount
        }

        params['clientOid'] = clientOid = self.get_unique_id()
        data_json = json.dumps(params)

        url = self.base + "/api/v1/margin/order"
        now = int(time.time() * 1000)
        str_to_sign = str(now) + 'POST' + '/api/v1/margin/order' + data_json
        signature = base64.b64encode(
            hmac.new(self.API_SECRET.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
        passphrase = base64.b64encode(hmac.new(self.API_SECRET.encode(
            'utf-8'), self.TRADING_PASSPHRASE.encode('utf-8'), hashlib.sha256).digest())
        headers = {
            "KC-API-SIGN": signature,
            "KC-API-TIMESTAMP": str(now),
            "KC-API-KEY": self.API_KEY,
            "KC-API-PASSPHRASE": passphrase,
            "KC-API-KEY-VERSION": "2",
            "Content-Type": "application/json"
        }
        try:
            response = requests.post(url, headers=headers, data=data_json)
        except NetworkError as e:
            raise Exception(e)
        if response.status_code == 200:
            return response.json()["data"]["orderOid"] # return order id on success
            return response.json()
        else:
            raise Exception(response.json()["msg"])

the return code:

```python
{'code': '200000', 'msg': 'position internal error'}

I think this is a n internal error on your end is that correct??

ImportError: cannot import name 'Trade' from 'kucoin.client'

from kucoin.client import Trade

C:\Users\MAX\Documents>python trade.py

Traceback (most recent call last):
  File "C:\Users\MAX\Documents\trade.py", line 1, in <module>
    from kucoin.client import Trade
ImportError: cannot import name 'Trade' from 'kucoin.client' (C:\Users\MAX\AppData\Local\Programs\Python\Python310\lib\site-packages\kucoin\client.py)

Inner Trasfer from MAIN to TRADE account

I gave transfer privileges to my API, but I still can't transfer from the main account to the trading account,
Do you know how I can do it?

I use the following code but I don't know what is wrong with it
user.inner_transfer( currency='BNB', from_payer='MAIN', to_payee='TRADE', amount= '0.1' , clientOid='whatever' )

Error:
Exception: 200-{"code":"400100","msg":"from not in the given range"}

trade.get_order_details intermittently returns 0 for dealfunds and dealsize

trade.get_order_details intermittently returns 0 for dealfunds and dealsize instead of float values for market buy/sell orders.
This only seems to happen when dealfunds and dealsize are less than 0.

Example below:
{'id': '61e10013f782bf0001719a84', 'symbol': 'SHIB-USDT', 'opType': 'DEAL', 'type': 'market', 'side': 'buy', 'price': '0', 'size': '1427461.315', 'funds': '0', 'dealFunds': '0', 'dealSize': '0', 'fee': '0', 'feeCurrency': 'USDT', 'stp': '', 'stop': '', 'stopTriggered': False, 'stopPrice': '0', 'timeInForce': 'GTC', 'postOnly': False, 'hidden': False, 'iceberg': False, 'visibleSize': '0', 'cancelAfter': 0, 'channel': 'API', 'clientOid': 'b255fb2e-6caf-42b0-bf91-393d567d053b', 'remark': None, 'tags': None, 'isActive': True, 'cancelExist': False, 'createdAt': 1642135571449, 'tradeType': 'TRADE'}

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.