GithubHelp home page GithubHelp logo

kucoin-futures-python-sdk's People

Contributors

1bazinga25 avatar allenye1024 avatar codewc avatar ive20 avatar jasonyao2107 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kucoin-futures-python-sdk's Issues

Implementing a stop order with closeOrder option

In the docs https://www.kucoin.com/docs/rest/futures-trading/orders/place-order appears this statement:

closeOrder | boolean | No | A mark to close the position. Set to false by default. If closeOrder is set to TRUE, the system will close the position and the position size will become 0. Side, Size and Leverage fields can be left empty and the system will determine the side and size automatically.

To achieve it I have trying this request:
{'symbol': 'XBTUSDTM', 'size': None, 'side': None, 'price': 24446.0, 'leverage': None, 'type': 'limit', 'clientOid': '0f23d4167aeb11eeadea80fa5b3993a2', 'kwargs': {'remark': '', 'stop': 'down', 'stopPriceType': 'MP', 'stopPrice': 24712.0, 'reduceOnly': False, 'closeOrder': True, 'forceHold': False, 'timeInForde': 'GTC', 'postOnly': False, 'hidden': False, 'iceberg': False, 'visibleSize': 0}}

With the output:
raise Exception("{}-{}".format(response_data.status_code, response_data.text)) Exception: 200-{"msg":"Leverage parameter invalid.","code":"100001"}

I have tried the values {}, '{}', '', 0 and 'null' too, same output. Really, I dont know more options in json to declare an empty var.
In the function create_limit_order the parameters size, side and leverage are positional so they can`t be omitted, still, I tried it without success.

Can you help me, please?

{"code":"100001","msg":"The quantity parameter cannot be empty."}

Hello this is my code I have balance and set size in def but market open didn't open and get me this error this is my code :

api_key = '###'
api_secret= '###'
api_passphrase= '###'

client = Trade(key=api_key, secret=api_secret, passphrase=api_passphrase, is_sandbox=False, url='')
order_id = client.create_market_order('ETHUSDTM', 'buy', '0.01')

entire market orderbook

Hi
is there a way to reach the entire market orderbooks with the depth of 10?
what I mean by entire market is all coins/tokens exist on the Kucoin and order books of them?

Best,

Broken sample in the readme

import asyncio
from kucoin_futures.client import WsToken
from kucoin_futures.ws_client import KucoinFuturesWsClient


async def main():
    async def deal_msg(msg):
        if msg.get('topic') == '/contractMarket/level2:XBTUSDM':
            print(f'Get XBTUSDM Ticker:{msg["data"]}')
        elif msg.get('topic') == '/contractMarket/level3:XBTUSDTM':
            print(f'Get XBTUSDTM level3:{msg["data"]}')

    # is public
    # client = WsToken()
    # is private
    client = WsToken(is_sandbox=False, url='')
    # is sandbox
    # client = WsToken(is_sandbox=True)
    ws_client = await KucoinFuturesWsClient.create(asyncio.get_running_loop(), client, deal_msg, private=False)
    await ws_client.subscribe('/contractMarket/level2:XBTUSDM')
    await ws_client.subscribe('/contractMarket/level3:XBTUSDM')
    while True:
        await asyncio.sleep(60)



if __name__ == "__main__":
    asyncio.run(main())

The sample needs to change from msg['topic'] to msg.get('topic'). It creates an error that causes the websockets to stop working.

Getting Data

Which topic should I use to get 1 min candles of BTC in Kucoin futures API?
How can I get the last price of BTC in kucoin futures API?
I've use '/market/candles:BTC-USDT_1min' for spot in python. What address is same as this for futures?

cannot import name 'KumexBaseRestApi'

Installed using pip, then ran this code:

from kucoin_futures.client import Market
client = Market(url='https://api-futures.kucoin.io')
klines = client.get_ticker("XBTUSDM")
print(klines)

Then encountered this error:

Traceback (most recent call last):
File "futures.py", line 1, in
from kucoin_futures.client import Market
File "/usr/local/lib/python3.6/dist-packages/kucoin_futures/client.py", line 4, in
from kucoin_futures.ws_token.token import GetToken
File "/usr/local/lib/python3.6/dist-packages/kucoin_futures/ws_token/token.py", line 1, in
from kucoin_futures.base_request.base_request import KumexBaseRestApi
ImportError: cannot import name 'KumexBaseRestApi'

400-{"code":"100000","msg":"JSON parse error: Cannot deserialize value of type `java.lang.Long` from String \"12.0\": not a valid `java.lang.Long` value; "}

Hi,
as soon as I use "create_limit_order" with a floating-point quantity (/order size) I get the error:
400-{"code":"100000","msg":"JSON parse error: Cannot deserialize value of type java.lang.Long from String "12.5": not a valid java.lang.Long value; "}
whereas with size 12 the order goes through.
That's an issue when trading coins with a relatively high price if you can't trade decimal positions.
Thanks for any help
Wkz

KC-API-KEY not exists

Hello community,

has anyone successfully used this lib for trading? I tried a minimal example, but i am always getting the error, that the API-KEY does not exist:

`from kucoin_futures.client import Trade

api_key = 'xxxxxxx'
api_secret = 'xxxxxxx'
api_passphrase = 'xxxxxxx'
url='https://api-futures.kucoin.com'

client = Trade(key=api_key, secret=api_secret, passphrase=api_passphrase, is_sandbox=False, url=url)
order_id = client.create_limit_order('XBTUSDM', 'buy', '1', '30', '8600')`

Can anyone assit?

Regards
Alex

create_market_order negative response.

Hi All,
Unfortunately, I always got this error, I can put limit order, But I can not create_market_order

order_id = client.create_market_order('XBTUSDM', 'buy', '1', size='60')

200-{"code":"300013","msg":"Unable to proceed the operation, theres no contra order in order book."}

Best Regards,
Mostafa

Exception: 200-{"code":"100004","msg":"Order is in not cancelable state"}

How To Fix?

Traceback (most recent call last):
File "C:\Users\sptpc\PycharmProjects\pythonProject2\Kucoin\kucoin-futures-main\ext1.py", line 30, in
o12=tradee.cancel_order(orderId=obb);print(o12)
File "C:\Users\sptpc\PycharmProjects\pythonProject2\Kucoin\kucoin-futures-main\kucoin_futures\trade\trade.py", line 411, in cancel_order
return self._request('DELETE', f'/api/v1/orders/{orderId}')
File "C:\Users\sptpc\PycharmProjects\pythonProject2\Kucoin\kucoin-futures-main\kucoin_futures\base_request\base_request.py", line 95, in _request
return self.check_response_data(response_data)
File "C:\Users\sptpc\PycharmProjects\pythonProject2\Kucoin\kucoin-futures-main\kucoin_futures\base_request\base_request.py", line 112, in check_response_data
raise Exception("{}-{}".format(response_data.status_code, response_data.text))
Exception: 200-{"code":"100004","msg":"Order is in not cancelable state"

Sandbox Can't find contract

I tried running the following code but can't get it to work. Note I am testing in sandbox component. (is_sandbox=True). this works when I am not using the sandbox....

import asyncio
from kucoin_futures.client import WsToken
from kucoin_futures.ws_client import KucoinFuturesWsClient


async def main():
    async def deal_msg(msg):
        print(msg)
        if msg['topic'] == '/contractMarket/level2:XBTUSDM':
            print(f'Get XBTUSDM Ticker:{msg["data"]}')
        elif msg['topic'] == '/contractMarket/level3:XBTUSDTM':
            print(f'Get XBTUSDTM level3:{msg["data"]}')

    # is public
    # client = WsToken()
    # is private
    #client = WsToken(key='', secret='', passphrase='', is_sandbox=True, url='')
    # is sandbox
    client = WsToken(is_sandbox=True)
    ws_client = await KucoinFuturesWsClient.create(loop, client, deal_msg, private=False)
    await ws_client.subscribe('/contractMarket/tickerV2:XBTUSDTM')
    #await ws_client.subscribe('/contractMarket/level3:XBTUSDM')
    while True:
        await asyncio.sleep(60, loop=loop)


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

Getting the following error:

{'code': 404, 'data': 'topic /contractMarket/tickerV2:XBTUSDTM is not found', 'id': '1620356359200', 'type': 'error'}

I get the following error: Error in placing position: 200-{"msg":"error.getOrder.orderIdLength","code":"100001"}

` order_details = trade_client.get_order_details(order_id)
print(f"Response for order placement at market price: {order_details}")

    orderStatus = order_details['status']
    bPLst.append(order_details['price'])
    price = order_details['dealSize']
    current_cost = order_details['dealValue']
    if orderStatus == "done" and check_current_positions() == 1:
        print(f"Order Status at mark price: {orderStatus}")
        return price, order_id, current_cost, 0, bitcoin_size`

Where trade_client is Trade from kucoin_futures. This leads to the return statement returning a None type.

1011 Timeout Error

Screen Shot 2022-07-24 at 8 37 55 AM
Error breaks connection of websocket and takes a few seconds to come back. Not sure what is causing this. It also only seems to be happening with public websocket clients.

Windows Server 2019 standart Edition

getting this error on vanilla Windows Server 2019:
<Task finished name='Task-7' coro=<ConnectWebsocket._run() done, defined at C:\Python38\lib\site-packages\kucoin_futures\websocket\websocket.py:33> exception=SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1124)')> got an exception [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1124)
pending <Task pending name='Task-6' coro=<ConnectWebsocket._recover_topic_req_msg() running at C:\Python38\lib\site-packages\kucoin_futures\websocket\websocket.py:127> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000001EE328283D0>()]>>

Which topic / price to monitor for stoploss on futures?

I am developing a stop-loss script for futures and i'm not sure which topic and price would suit best to monitor (trading wise):

{
    "subject": "tickerV2",
    "topic": "/contractMarket/tickerV2:XBTUSDM",
    "data": {
      "symbol": "XBTUSDM",              
      "bestBidSize": 795,              
      "bestBidPrice": 3200.00,          <-- Watch this incase position is SELL?
      "bestAskPrice": 3600.00,         <-- Watch this incase position is BUY?
      "bestAskSize": 284,               
      "ts": 1553846081210004941         
   }
  }       

Or use:

  { 
    "topic": "/contract/instrument:XBTUSDM",
    "subject": "mark.index.price",
    "data": {
        "granularity": 1000,           
        "indexPrice": 4000.23,            
        "markPrice": 4010.52,           <==== Watch This price (though sometimes the actual market price is higher)
        "timestamp": 1551770400000
    }
  }

Thanks

Reduce position has no effect or transaction - but it does return transaction ID

I am trying to reduce the size of an open position and using the reduceOnly=true
reduceOrder = trade.create_limit_order(side=side, symbol=pair, price=msg["data"]["bestBidPrice"], size=size, lever=lever,reduceOnly=True)

it returns transaction ID but noting actually happends to the position, and i cant find this transaction on the the website.
On web a similar action triggers an order with this parameter:

closeOnly: true
closeOrder: false

Its not accepting it in the API. I guess the equivalent of closeOnly in API is the reduceOnly.

What am i missing? how to partly close the position?

API Returns Balance insufficient on createOrder

I'm trying to create an order for DOTUSDM & XBTUSDM on live futures API but i keep getting:

"200-{"code":"300003","msg":"Balance insufficient. The order would cost 9.7006407156."}

USDT Balance is sufficient and i am able to see it using the API. Order is way less than balance.

sandbox URL does not exist

; <<>> DiG 9.10.6 <<>> api-sandbox-futures.kucoin.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 51516
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;api-sandbox-futures.kucoin.com. IN A

Order Creation Failing

i am getting this error when running this code
client.create_market_order("XBTUSDM","buy",'1','0.001')
error
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='api-sandbox-futures.kucoin.com', port=443): Read timed out. (read timeout=5)

websocket connection closed

websocket is not reliable and sometimes when an exception happens it does not restart. traceback of the exception that is happening from time to time is as follows:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 750, in transfer_data
    message = await self.read_message()
  File "/usr/local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 819, in read_message
    frame = await self.read_data_frame(max_size=self.max_size)
  File "/usr/local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 895, in read_data_frame
    frame = await self.read_frame(max_size)
  File "/usr/local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 971, in read_frame
    frame = await Frame.read(
  File "/usr/local/lib/python3.9/site-packages/websockets/legacy/framing.py", line 55, in read
    data = await reader(2)
  File "/usr/local/lib/python3.9/asyncio/streams.py", line 721, in readexactly
    raise exceptions.IncompleteReadError(incomplete, n)
asyncio.exceptions.IncompleteReadError: 0 bytes read on a total of 2 expected bytes

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/kucoin_futures/websocket/websocket.py", line 43, in _run
    _msg = await asyncio.wait_for(self._socket.recv(), timeout=self.get_ws_pingtimeout())
  File "/usr/local/lib/python3.9/asyncio/tasks.py", line 481, in wait_for
    return fut.result()
  File "/usr/local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 421, in recv
    await self.ensure_open()
  File "/usr/local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 726, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: code = 1006 (connection closed abnormally [internal]), no reason

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/kucoin_futures/websocket/websocket.py", line 56, in _run
    await self._reconnect()
  File "/usr/local/lib/python3.9/asyncio/tasks.py", line 654, in sleep
    return await future
asyncio.exceptions.CancelledError

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.