Not able to place order

anilraj75
Please help me to solve the below error,
The code is running ok while fetching ticks but while placing the order the below error is coming, please help me to rectify it



DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.kite.trade:443
DEBUG:urllib3.connectionpool:https://api.kite.trade:443 "POST /orders/regular HTTP/1.1" 400 109
Unhandled Error
Traceback (most recent call last):
File "C:\python\Python37\lib\site-packages\twisted\python\log.py", line 103, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "C:\python\Python37\lib\site-packages\twisted\python\log.py", line 86, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "C:\python\Python37\lib\site-packages\twisted\python\context.py", line 122, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "C:\python\Python37\lib\site-packages\twisted\python\context.py", line 85, in callWithContext
return func(*args,**kw)
--- ---
File "C:\python\Python37\lib\site-packages\twisted\internet\selectreactor.py", line 149, in _doReadOrWrite
why = getattr(selectable, method)()
File "C:\python\Python37\lib\site-packages\twisted\internet\tcp.py", line 243, in doRead
return self._dataReceived(data)
File "C:\python\Python37\lib\site-packages\twisted\internet\tcp.py", line 249, in _dataReceived
rval = self.protocol.dataReceived(data)
File "C:\python\Python37\lib\site-packages\twisted\protocols\tls.py", line 330, in dataReceived
self._flushReceiveBIO()
File "C:\python\Python37\lib\site-packages\twisted\protocols\tls.py", line 295, in _flushReceiveBIO
ProtocolWrapper.dataReceived(self, bytes)
File "C:\python\Python37\lib\site-packages\twisted\protocols\policies.py", line 120, in dataReceived
self.wrappedProtocol.dataReceived(data)
File "C:\python\Python37\lib\site-packages\autobahn\twisted\websocket.py", line 291, in dataReceived
self._dataReceived(data)
File "C:\python\Python37\lib\site-packages\autobahn\websocket\protocol.py", line 1213, in _dataReceived
self.consumeData()
File "C:\python\Python37\lib\site-packages\autobahn\websocket\protocol.py", line 1225, in consumeData
while self.processData() and self.state != WebSocketProtocol.STATE_CLOSED:
File "C:\python\Python37\lib\site-packages\autobahn\websocket\protocol.py", line 1591, in processData
fr = self.onFrameEnd()
File "C:\python\Python37\lib\site-packages\autobahn\websocket\protocol.py", line 1713, in onFrameEnd
self._onMessageEnd()
File "C:\python\Python37\lib\site-packages\autobahn\twisted\websocket.py", line 319, in _onMessageEnd
self.onMessageEnd()
File "C:\python\Python37\lib\site-packages\autobahn\websocket\protocol.py", line 634, in onMessageEnd
self._onMessage(payload, self.message_is_binary)
File "C:\python\Python37\lib\site-packages\autobahn\twisted\websocket.py", line 322, in _onMessage
self.onMessage(payload, isBinary)
File "C:\python\Python37\lib\site-packages\kiteconnect\ticker.py", line 71, in onMessage
self.factory.on_message(self, payload, is_binary)
File "C:\python\Python37\lib\site-packages\kiteconnect\ticker.py", line 673, in _on_message
self.on_ticks(self, self._parse_binary(payload))
File "C:\Users\servi\Desktop\TRADE\ALGOTRADE\multi", line 63, in on_ticks
helper_method(ws, ticks)
File "C:\Users\servi\Desktop\TRADE\ALGOTRADE\multi", line 85, in helper_method
kite.place_order(variety=kite.VARIETY_REGULAR,tradingsymbol=name, exchange=kite.EXCHANGE_NSE, transaction_type=kite.TRANSACTION_TYPE_SELL, quantity=10, order_type=kite.ORDER_TYPE_MARKET, product=kite.PRODUCT_MIS,validity=kite.VALIDITY_DAY)
File "C:\python\Python37\lib\site-packages\kiteconnect\connect.py", line 357, in place_order
params=params)["order_id"]
File "C:\python\Python37\lib\site-packages\kiteconnect\connect.py", line 841, in _post
return self._request(route, "POST", url_args=url_args, params=params, is_json=is_json, query_params=query_params)
File "C:\python\Python37\lib\site-packages\kiteconnect\connect.py", line 913, in _request
raise exp(data["message"], code=r.status_code)
kiteconnect.exceptions.InputException: Invalid `api_key` or `access_token`.

ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)
ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)

  • anilraj75
    anilraj75 edited January 8
    code:
    #!python
    from kiteconnect import KiteTicker
    from kiteconnect import KiteConnect
    from threading import Thread
    from pprint import pprint
    import flask
    from flask import Flask, jsonify
    import pandas as pd
    import datetime
    import pdb
    import logging
    import time
    import logging

    logging.basicConfig(level=logging.DEBUG)

    # Initialise
    api_k = '536akjflkajsfdlkajcfm3v807'
    api_s = 'ri63u5vxvmfaadskfjalksxrips9m46mh'
    access_token = '1IbYsafsj5QeqBgfa3ebb9wBS9asdflkaK'
    kws = KiteTicker(api_k,access_token)
    kite = KiteConnect(api_key =api_k)


    instrument_token = [8042241, 5436929]
    trd_portfolio = {}

    def on_connect(ws, response):
    ws.subscribe(instrument_token)
    ws.set_mode(ws.MODE_QUOTE, instrument_token)

    def on_ticks(ws, ticks):
    logging.debug("Ticks: {}".format(ticks))

    kws.on_connect = on_connect
    kws.connect(threaded =True)

    while True:


    # Perform required data operation using tick data
    def on_ticks(ws, ticks):
    helper_method(ws, ticks)


    def helper_method(ws, ticks):
    for single_company in ticks:
    inst_single_company = single_company['instrument_token']
    name = trd_portfolio[inst_single_company]['name']
    highh = single_company['ohlc']['high']
    openn = single_company['ohlc']['open']
    loww = single_company['ohlc']['low']
    closee = single_company['ohlc']['close']
    ltp = single_company['last_price']
    trd_portfolio[inst_single_company]['open'] = openn
    trd_portfolio[inst_single_company]['high'] = highh
    trd_portfolio[inst_single_company]['low'] = loww
    trd_portfolio[inst_single_company]['close'] = closee
    #print(openn,closee,name)

    if (openn > 1.01 * closee) and (ltp < closee) and ("sold" not in trd_portfolio[inst_single_company].values()):
    print('sell', name)
    trd_portfolio[inst_single_company]['status'] = "sold"
    # global kite
    kite.place_order(variety=kite.VARIETY_REGULAR,tradingsymbol=name, exchange=kite.EXCHANGE_NSE, transaction_type=kite.TRANSACTION_TYPE_SELL, quantity=10, order_type=kite.ORDER_TYPE_MARKET, product=kite.PRODUCT_MIS,validity=kite.VALIDITY_DAY)
    #logging.info("Order placed. ID is: {}".format(order_id))
    #def place_order("tradingsymbol = name","exchange = NSE", "transaction_type=BUY","order_type=MARKET","quantity = 10","product = MIS","order_type = MARKET","validity=DAY")

    if (openn < 0.99 * closee) and (ltp > closee) and ("bought" not in trd_portfolio[inst_single_company].values()):
    print ('buy', name)
    trd_portfolio[inst_single_company]['status'] = "bought"
    kws.on_ticks = on_ticks



  • sujith
    Please don't post app, session or client specific keys on the public threads.

    There are two things in logs one is you are not passing valid api key or access token.
    Another one is you are blocking the main thread which is receiving ticks.

    You can check out FAQ to know more about websocket error.
  • anilraj75
    Thanks will try
  • anilraj75
    @sujith Thanks for the help it's working.
    Is topt mandatory for placing through API
  • rakeshr
    Is topt mandatory for placing through API
    Yes. Go through this thread to know more.
  • AnastasiaSin
    Thanks for sharing, it's helpful!
Sign In or Register to comment.