kucoin / kucoin-futures-python-sdk Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
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?
How do I close create_market_order positions with market order?
I was trying ti make a market order but it would give me error like:''Quantity can't be none''
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')
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,
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.
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?
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'
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
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
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
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"
I've been trying place a order on kucoin futures, with ta API v2 using the following url: 'https://api-futures.kucoin.com/api/v2/order'
but I just got the error 404 that means it's not found, so anyone knows witch url shoul I use to place a order ?
thanks in advance
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'}
` 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.
`from kucoin_futures.client import Market
client=Market(key=key, secret=secret, passphrase=passphrase, is_sandbox=False, url=url)
k=client.get_ticker('BTCUSDT')
print(k)`
when I run this code it gives me this error:
Exception: 500-{"code":"100000","msg":"Service not available temporarily, please try it later."}
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>()]>>
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
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?
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.
; <<>> 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
How do define Stop Loss and Take Profit in kucoin-futures-python?
I see where I can check fills and whatnot, but how can I see the actual Profit/Loss from each order?
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)
Exception: 429-{"code":"429000","msg":"Too Many Requests"}
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.