Kite API to sell options instrument erring out

Swarochisha
Swarochisha edited February 2020 in Python client
Good morning.
I have the below code thats getting triggered from my Python module. However, its erring out without providing any details. Could you please help ? The below SELL trade is sent to square off an opening position I already have at that moment.

Error Message:
ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (None)
Code extract:
def place_options_trade_order(instrument,buy_sell_flag,quantity):


if (buy_sell_flag=="BUY"):
transaction_type = kite.TRANSACTION_TYPE_BUY
else:
transaction_type = kite.TRANSACTION_TYPE_SELL

try:
order_id = kite.place_order(variety=kite.VARIETY_REGULAR,tradingsymbol=instrument,
exchange=kite.EXCHANGE_NSE,
transaction_type=transaction_type,
quantity=quantity,
order_type=kite.ORDER_TYPE_MARKET,
product=kite.PRODUCT_NRML)

logging.info("Order placed. ID is: {}".format(order_id))
except Exception as e:
logging.info("Order placement failed: {}".format(e)) #e.message
return order_id

place_options_trade(11881986,"SELL",75)# 11881986 is for NIFTY20FEB11800PE
  • Swarochisha
    Hi,
    Anyone, who could look into my problem ?

    Thanks a lot.
  • rakeshr
    @Swarochisha
    All order params seems to be correct.
    Are you calling place_options_trade method inside on_ticks method?
  • Swarochisha
    Yes. I am calling another method to decide to exit the order,from within on_ticks. Based a yes/no from this method,I call the place_options_trade method,where I just fire the order.
  • rakeshr
    @Swarochisha
    You need to pass tick to a different thread for yes/no method return call, without blocking the main on_tick thread.
    You can have look to this thread for a multi-threading example.
  • Swarochisha
    @rakeshr

    Thanks for this link.
    I implemented the multi-threading in my logic. This should help me capture the ticks without missing any as I was blocking it from my module to execute strategy.

    However, I do not think my original problem has anything to do with multi-threading.
    Here are the 3 different combinations I tried from then till now:
    1) I changed exchange=kite.EXCHANGE_NSE to exchange=kite.EXCHANGE_NFO
    2) I used exchange_token instead of the instrument_token.
    3) I reverted to instrument_token while retaining exchange=kite.EXCHANGE_NFO.

    None of the above combinations above made any difference. I still get the message'Invalid Instrument'

    Please suggest.
  • sujith
    Then it might be the tradingsymbol that is wrong. Are you sure you are sending the valid tradingsymbol?
  • Swarochisha
    @sujith
    Yes.I am sending the correct trading symbol. As I mentioned above,I tried sending both instrument_token as well as exchange_token. Niether worked.

    Looks like instrument_token is the correct one to send anyway. This is confirmed as I take an export of the active position from the Pi Console "Admin Position" tab onto an excel. The instrument_token is the one listed over there, and not the exchange token.
  • sujith
    Can you paste the complete log of request and response here?
  • Swarochisha
    The below is my position data from yesterday:
    {'net': [{'tradingsymbol': 'NIFTY20FEB11700PE', 'exchange': 'NFO', 'instrument_token': 11880450, 'product': 'NRML', 'quantity': 75, 'overnight_quantity': 75, 'multiplier': 1, 'average_price': 35.45, 'close_price': 24.4, 'last_price': 21.45, 'value': -2658.75, 'pnl': -1050, 'm2m': -221.25, 'unrealised': -1050, 'realised': 0, 'buy_quantity': 75, 'buy_price': 35.45, 'buy_value': 2658.75, 'buy_m2m': 1830, 'sell_quantity': 0, 'sell_price': 0, 'sell_value': 0, 'sell_m2m': 0, 'day_buy_quantity': 0, 'day_buy_price': 0, 'day_buy_value': 0, 'day_sell_quantity': 0, 'day_sell_price': 0, 'day_sell_value': 0}], 'day': []}

    The below is the log of the error:
    DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.kite.trade
    DEBUG:urllib3.connectionpool:https://api.kite.trade:443 "POST /orders/regular HTTP/1.1" 400 95
    INFO:root:Order placement failed: Instrument is invalid.
    Unhandled Error
    Traceback (most recent call last):
    File "..\Python\Python36-32\lib\site-packages\twisted\python\log.py", line 103, in callWithLogger
    return callWithContext({"system": lp}, func, *args, **kw)
    File "..\Python\Python36-32\lib\site-packages\twisted\python\log.py", line 86, in callWithContext
    return context.call({ILogContext: newCtx}, func, *args, **kw)
    File "..\Python\Python36-32\lib\site-packages\twisted\python\context.py", line 122, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
    File "..\Python\Python36-32\lib\site-packages\twisted\python\context.py", line 85, in callWithContext
    return func(*args,**kw)
    --- ---
    File "..\Python\Python36-32\lib\site-packages\twisted\internet\selectreactor.py", line 149, in _doReadOrWrite
    why = getattr(selectable, method)()
    File "..\Python\Python36-32\lib\site-packages\twisted\internet\tcp.py", line 243, in doRead
    return self._dataReceived(data)
    File "..\Python\Python36-32\lib\site-packages\twisted\internet\tcp.py", line 249, in _dataReceived
    rval = self.protocol.dataReceived(data)
    File "..\Python\Python36-32\lib\site-packages\twisted\protocols\tls.py", line 330, in dataReceived
    self._flushReceiveBIO()
    File "..\Python\Python36-32\lib\site-packages\twisted\protocols\tls.py", line 295, in _flushReceiveBIO
    ProtocolWrapper.dataReceived(self, bytes)
    File "..\Python\Python36-32\lib\site-packages\twisted\protocols\policies.py", line 120, in dataReceived
    self.wrappedProtocol.dataReceived(data)
    File "..\Python\Python36-32\lib\site-packages\autobahn\twisted\websocket.py", line 291, in dataReceived
    self._dataReceived(data)
    File "..\Python\Python36-32\lib\site-packages\autobahn\websocket\protocol.py", line 1213, in _dataReceived
    self.consumeData()
    File "..\Python\Python36-32\lib\site-packages\autobahn\websocket\protocol.py", line 1225, in consumeData
    while self.processData() and self.state != WebSocketProtocol.STATE_CLOSED:
    File "..\Python\Python36-32\lib\site-packages\autobahn\websocket\protocol.py", line 1591, in processData
    fr = self.onFrameEnd()
    File "..\Python\Python36-32\lib\site-packages\autobahn\websocket\protocol.py", line 1713, in onFrameEnd
    self._onMessageEnd()
    File "..\Python\Python36-32\lib\site-packages\autobahn\twisted\websocket.py", line 319, in _onMessageEnd
    self.onMessageEnd()
    File "..\Python\Python36-32\lib\site-packages\autobahn\websocket\protocol.py", line 634, in onMessageEnd
    self._onMessage(payload, self.message_is_binary)
    File "..\Python\Python36-32\lib\site-packages\autobahn\twisted\websocket.py", line 322, in _onMessage
    self.onMessage(payload, isBinary)
    File "..\Python\Python36-32\lib\site-packages\kiteconnect-3.8.0-py3.6.egg\kiteconnect\ticker.py", line 71, in onMessage

    File "..\Python\Python36-32\lib\site-packages\kiteconnect-3.8.0-py3.6.egg\kiteconnect\ticker.py", line 677, in _on_message

    File "..\Python\Python36-32\algo\algoTradingKiteConnect Daily.py", line 409, in on_ticks
    on_ticks_thread(ws,ticks)
    File "..\Python\Python36-32\algo\algoTradingKiteConnect Daily.py", line 360, in on_ticks_thread
    take_options_trade(option_triplet_ticks["instrument"]["instrument_token"],options_trade_dict["PE"],option_triplet_ticks["instrument"]["last_price"],active_trade_key_limits["stoploss"], True,"SELL",75)
    File "..\Python\Python36-32\algo\algoTradingKiteConnect Daily.py", line 274, in take_options_trade
    place_options_trade_order(tradeable_instrument,buy_sell_flag,quantity)
    File "..\Python\Python36-32\algo\algoTradingKiteConnect Daily.py", line 250, in place_options_trade_order
    return order_id
    builtins.UnboundLocalError: local variable 'order_id' referenced before assignment

    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)
    Inside the error block
    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)
    Inside on close
    connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)



    The below is the definition of the dictionary:

    options_trade_dict = {"instrument":256265,"CE":11879426,"PE":11880450,"exchange_CE":46404,"exchange_PE":46408,"lotsize":75}



  • sujith
    {"instrument":256265,"CE":11879426,"PE":11880450,"exchange_CE":46404,"exchange_PE":46408,"lotsize":75}
    You seem to be sending a NIFTY 50 instrument token for a tradingsymbol value. You need to send tradingsymbol like NIFTY20FEB11700PE while placing an order.
  • Swarochisha
    Yeah !!!

    Thanks a lot for this. My code is fine now. I am able to place orders. Totally 8 trading sessions went off trying to figure this out, as I do not know of any other way to run the code and get a feedback.

    Is there a sandbox where I can run my python based strategies off-the market hours?

    Have a great day.
  • sujith
    We don't have a sandbox environment as of now.
  • Swarochisha
    Thanks @sujith and @rakeshr for the help.
This discussion has been closed.