
    8'ht                         d Z ddlmZmZ ddlmZ ddlZddlZddlZ	ddl
Z
ddlZddlZddlZddlZddlmZmZ ddlmZ  ej(                  e      Z G d de      Zy)	z
    connect.py

    API wrapper for Kite Connect REST APIs.

    :copyright: (c) 2021 by Zerodha Technology.
    :license: see LICENSE for details.
    )StringIOPY2)urljoinN   )__version__	__title__c                   t   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)Z+d*Z,d+Z-d,Z.d-Z/d.Z0i d/d0d1d0d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdCdEdFdGdHdIdJdKdLdMdHi dNdOdPdQdRdOdSdQdTdUdVdWdXdUdYdWdZdWd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdmdndndndodpdqdr
Z1	 	 	 	 	 	 	 ddtZ2du Z3dv Z4dw Z5dx Z6ddyZ7dz Z8d{ Z9dd|Z:d} Z;	 	 	 	 	 	 	 	 	 dd~Z<	 	 	 	 	 	 	 ddZ=ddZ>ddZ?d Z@d ZAd ZBd ZCd ZDd ZEd ZFd ZGd ZHddZI	 	 	 ddZJd ZKddZL	 	 	 ddZM	 	 	 	 	 ddZNd ZOd ZPd ZQddZRd ZSd ZTd ZUddZVd ZWd ZXd ZYd ZZd Z[d Z\d Z]d Z^d Z_ddZ`d Zad Zbd Zcd Zdd ZeddZfddZgddZhddZiddZjys)KiteConnectz
    The Kite Connect API wrapper class.

    In production, you may initialise a single instance of this class per `api_key`.
    zhttps://api.kite.tradez&https://kite.zerodha.com/connect/login   3MISCNCNRMLCOMARKETLIMITzSL-MSLregularcoamoicebergauctionBUYSELLDAYIOCTTLday	overnightNSEBSENFOCDSBFOMCXBCDequity	commodityCOMPLETEREJECTED	CANCELLEDztwo-legsingleactive	triggereddisabledexpired	cancelledrejecteddeleted	api.tokenz/session/tokenapi.token.invalidateapi.token.renewz/session/refresh_tokenuser.profilez/user/profileuser.marginsz/user/marginsuser.margins.segmentz/user/margins/{segment}ordersz/orderstradesz/trades
order.infoz/orders/{order_id}order.placez/orders/{variety}order.modifyz/orders/{variety}/{order_id}order.cancelorder.tradesz/orders/{order_id}/tradesportfolio.positionsz/portfolio/positionsportfolio.holdingsz/portfolio/holdingsportfolio.holdings.auctionz/portfolio/holdings/auctionsportfolio.positions.convert	mf.ordersz
/mf/ordersmf.order.infoz/mf/orders/{order_id}mf.order.placemf.order.cancelmf.sipsz/mf/sipsmf.sip.infoz/mf/sips/{sip_id}mf.sip.placemf.sip.modifymf.sip.cancelmf.holdingsz/mf/holdingsmf.instrumentsz/mf/instrumentsmarket.instruments.allz/instrumentsmarket.instrumentsz/instruments/{exchange}zmarket.marginsz/margins/{segment}market.historicalz5/instruments/historical/{instrument_token}/{interval}market.trigger_rangez-/instruments/trigger_range/{transaction_type}market.quotez/quotez/quote/ohlcz
/quote/ltpz/gtt/triggersz/gtt/triggers/{trigger_id}z/margins/ordersz/margins/basketz/charges/orders)
market.quote.ohlcmarket.quote.ltpgtt	gtt.placegtt.info
gtt.modify
gtt.deleteorder.marginsorder.margins.basketorder.contract_noteNc	                    || _         || _        d| _        || _        || _        |r|ni | _        |xs | j                  | _        |xs | j                  | _	        t        j                         | _        |r;t        j                  j                  di |}	| j                  j                  d|	       t        j                   j"                  j%                          y)a  
        Initialise a new Kite Connect client instance.

        - `api_key` is the key issued to you
        - `access_token` is the token obtained after the login flow in
            exchange for the `request_token` . Pre-login, this will default to None,
        but once you have obtained it, you should
        persist it in a database or session to pass
        to the Kite Connect class initialisation for subsequent requests.
        - `root` is the API end point root. Unless you explicitly
        want to send API requests to a non-default endpoint, this
        can be ignored.
        - `debug`, if set to True, will serialise and print requests
        and responses to stdout.
        - `timeout` is the time (seconds) for which the API client will wait for
        a request to complete before it fails. Defaults to 7 seconds
        - `proxies` to set requests proxy.
        Check [python requests documentation](http://docs.python-requests.org/en/master/user/advanced/#proxies) for usage and examples.
        - `pool` is manages request pools. It takes a dict of params accepted by HTTPAdapter as described here in [python requests documentation](http://docs.python-requests.org/en/master/api/#requests.adapters.HTTPAdapter)
        - `disable_ssl` disables the SSL verification while making a request.
        If set requests won't throw SSLError if its set to custom `root` url without SSL.
        Nzhttps:// )debugapi_keysession_expiry_hookdisable_sslaccess_tokenproxies_default_root_uriroot_default_timeouttimeoutrequestsSession
reqsessionadaptersHTTPAdaptermountpackagesurllib3disable_warnings)
selfrb   re   rh   ra   rj   rf   poolrd   
reqadapters
             O/var/www/html/trade_iq/venv/lib/python3.12/site-packages/kiteconnect/connect.py__init__zKiteConnect.__init__   s    > 
#' &(")wr2D22	7$"7"7 #**,!**66>>JOO!!*j9 	!!224    c                 >    t        |      st        d      || _        y)a>  
        Set a callback hook for session (`TokenError` -- timeout, expiry etc.) errors.

        An `access_token` (login session) can become invalid for a number of
        reasons, but it doesn't make sense for the client to
        try and catch it during every API call.

        A callback method that handles session errors
        can be set here and when the client encounters
        a token error at any point, it'll be called.

        This callback, for instance, can log the user out of the UI,
        clear session cookies, or initiate a fresh login.
        z0Invalid input type. Only functions are accepted.N)callable	TypeErrorrc   )rt   methods     rw   set_session_expiry_hookz#KiteConnect.set_session_expiry_hook   s      NOO#) ry   c                     || _         y)zBSet the `access_token` received after a successful authentication.N)re   rt   re   s     rw   set_access_tokenzKiteConnect.set_access_token   s
    (ry   c                 R    | j                   d| j                  d| j                  S )zYGet the remote login url to which a user should be redirected to initiate the login flow.z	?api_key=z&v=)_default_login_urirb   kite_header_versionrt   s    rw   	login_urlzKiteConnect.login_url   s    '+'>'>dNfNfggry   c                    t        j                  | j                  j                  d      |j                  d      z   |j                  d      z         }|j	                         }| j                  d| j                  ||d      }d|v r| j                  |d          |d   r6t        |d         dk(  r%t        j                  j                  |d         |d<   |S )a  
        Generate user session details like `access_token` etc by exchanging `request_token`.
        Access token is automatically set if the session is retrieved successfully.

        Do the token exchange with the `request_token` obtained after the login flow,
        and retrieve the `access_token` required for all subsequent requests. The
        response contains not just the `access_token`, but metadata for
        the user who has authenticated.

        - `request_token` is the token obtained from the GET paramers after a successful login redirect.
        - `api_secret` is the API api_secret issued with the API key.
        utf-8r4   )rb   request_tokenchecksumparamsre   
login_time   )hashlibsha256rb   encode	hexdigest_postr   lendateutilparserparse)rt   r   
api_secrethr   resps         rw   generate_sessionzKiteConnect.generate_session   s     NN4<<..w7-:N:Nw:WWZdZkZklsZttu;;=zz+||* /
z  T!!!$~"67#d<&8"9R"?!)!6!6tL7I!JDry   c                 b    |xs | j                   }| j                  d| j                  |d      S )z
        Kill the session by invalidating the access token.

        - `access_token` to invalidate. Default is the active `access_token`.
        r5   )rb   re   r   )re   _deleterb   r   s     rw   invalidate_access_tokenz#KiteConnect.invalidate_access_token  s9     $8t'8'8||2||(<
|  	ry   c                 <   t        j                  | j                  j                  d      |j                  d      z   |j                  d      z         }|j	                         }| j                  d| j                  ||d      }d|v r| j                  |d          |S )z
        Renew expired `refresh_token` using valid `refresh_token`.

        - `refresh_token` is the token obtained from previous successful login flow.
        - `api_secret` is the API api_secret issued with the API key.
        r   r6   )rb   refresh_tokenr   r   re   )r   r   rb   r   r   r   r   )rt   r   r   r   r   r   s         rw   renew_access_tokenzKiteConnect.renew_access_token!  s     NN4<<..w7-:N:Nw:WWZdZkZklsZttu;;=zz+||* 5
z  T!!!$~"67ry   c                 B    | j                  d| j                  |d      S )zx
        Invalidate refresh token.

        - `refresh_token` is the token which is used to renew access token.
        r5   )rb   r   r   )r   rb   )rt   r   s     rw   invalidate_refresh_tokenz$KiteConnect.invalidate_refresh_token6  s)     ||2||*<
|  	ry   c                 R    |r| j                  dd|i      S | j                  d      S )zGet account balance and cash margin details for a particular segment.

        - `segment` is the trading segment (eg: equity or commodity)
        r9   segmenturl_argsr8   _get)rt   r   s     rw   marginszKiteConnect.marginsA  s/    
 993y'>R9SS99^,,ry   c                 $    | j                  d      S )zGet user profile details.r7   r   r   s    rw   profilezKiteConnect.profileK  s    yy((ry   c                     t               }|d= t        |j                               D ]  }||   	||=  | j                  dd|i|      d   S )zPlace an order.rt   r=   varietyr   r   order_id)localslistkeysr   )rt   r   exchangetradingsymboltransaction_typequantityproduct
order_typepricevalidityvalidity_ttldisclosed_quantitytrigger_priceiceberg_legsiceberg_quantityauction_numbertagr   ks                      rw   place_orderzKiteConnect.place_orderP  sj    $ F^fkkm$ 	 Aay AY	  zz-$-w#7!'  ))35 	5ry   c
                     t               }
|
d= t        |
j                               D ]  }|
|   	|
|=  | j                  d||d|
      d   S )zModify an open order.rt   r>   r   r   r   r   )r   r   r   _put)rt   r   r   parent_order_idr   r   r   r   r   r   r   r   s               rw   modify_orderzKiteConnect.modify_orderm  sj     F^fkkm$ 	 Aay AY	  yy.58"L &  ((24 	4ry   c                 :    | j                  d||dd|i      d   S )zCancel an order.r?   r   r   r   r   r   rt   r   r   r   s       rw   cancel_orderzKiteConnect.cancel_order  s5    ||N18h%O$5#G  IISU 	Ury   c                 *    | j                  |||      S )zExit a CO order.)r   )r   r   s       rw   
exit_orderzKiteConnect.exit_order  s      (O TTry   c                 6   t        |      t        k(  r|}nt        |      t        k(  r|g}D ]R  }dD ]K  }|j                  |      st	        ||         dk(  s't
        j                  j                  ||         ||<   M T t        |      t        k(  r|d   S |S )zParse and format responses.)order_timestampexchange_timestampcreatedlast_instalmentfill_timestamp	timestamplast_trade_timer   r   )typer   dictgetr   r   r   r   )rt   data_listitemfields        rw   _format_responsezKiteConnect._format_response  s     :E$Z4FE 	ED S E88E?s4;'72'="*//"7"7U"DDKE	E  :-uQx858ry   c                 B    | j                  | j                  d            S )zGet list of orders.r:   r   r   r   s    rw   r:   zKiteConnect.orders  s    $$TYYx%899ry   c                 J    | j                  | j                  dd|i            S )zz
        Get history of individual order.

        - `order_id` is the ID of the order to retrieve order history.
        r<   r   r   r   rt   r   s     rw   order_historyzKiteConnect.order_history  s(     $$TYY|zS[F\Y%]^^ry   c                 B    | j                  | j                  d            S )z
        Retrieve the list of trades executed (all or ones under a particular order).

        An order can be executed in tranches based on market conditions.
        These trades are individually recorded under an order.
        r;   r   r   s    rw   r;   zKiteConnect.trades  s     $$TYYx%899ry   c                 J    | j                  | j                  dd|i            S )z
        Retrieve the list of trades executed for a particular order.

        - `order_id` is the ID of the order to retrieve trade history.
        r@   r   r   r   r   s     rw   order_tradeszKiteConnect.order_trades  s(     $$TYY~U]H^Y%_``ry   c                 $    | j                  d      S )zRetrieve the list of positions.rA   r   r   s    rw   	positionszKiteConnect.positions  s    yy.//ry   c                 $    | j                  d      S )z%Retrieve the list of equity holdings.rB   r   r   s    rw   holdingszKiteConnect.holdings  s    yy-..ry   c                 $    | j                  d      S )z? Retrieves list of available instruments for a auction session rC   r   r   s    rw   get_auction_instrumentsz#KiteConnect.get_auction_instruments  s    yy566ry   c                 8    | j                  d|||||||d      S )z'Modify an open position's product type.rD   )r   r   r   position_typer   old_productnew_productr   r   )rt   r   r   r   r   r   r   r   s           rw   convert_positionzKiteConnect.convert_position  s5     yy6 * 0* &&@
y  	ry   c                     |r$| j                  | j                  dd|i            S | j                  | j                  d            S )z4Get all mutual fund orders or individual order info.rF   r   r   rE   r   r   s     rw   	mf_orderszKiteConnect.mf_orders  sC    ((?jZbMc)dee((;)?@@ry   c           	      4    | j                  d|||||d      S )zPlace a mutual fund order.rG   )r   r   r   amountr   r   r   )rt   r   r   r   r   r   s         rw   place_mf_orderzKiteConnect.place_mf_order  s.     zz** 0 4
z  	ry   c                 ,    | j                  dd|i      S )zCancel a mutual fund order.rH   r   r   r   r   s     rw   cancel_mf_orderzKiteConnect.cancel_mf_order  s    ||-X8N|OOry   c                     |r$| j                  | j                  dd|i            S | j                  | j                  d            S )z9Get list of all mutual fund SIP's or individual SIP info.rJ   sip_idr   rI   r   rt   r   s     rw   mf_sipszKiteConnect.mf_sips  sC    ((=HV\K])^__((9)=>>ry   c                 8    | j                  d|||||||d      S )zPlace a mutual fund SIP.rK   )r   r   initial_amountinstalments	frequencyinstalment_dayr   r   r   )rt   r   r   r  r  r  r  r   s           rw   place_mf_sipzKiteConnect.place_mf_sip  s3     zz.*,&",2
z  	ry   c           
      :    | j                  dd|i|||||d      S )zModify a mutual fund SIP.rL   r   )r   statusr  r  r  r   r   )rt   r   r   r  r  r  r  s          rw   modify_mf_sipzKiteConnect.modify_mf_sip  s8     yy#+V"4'-'-,7*3/=!   	ry   c                 ,    | j                  dd|i      S )zCancel a mutual fund SIP.rM   r   r   r   r   s     rw   cancel_mf_sipzKiteConnect.cancel_mf_sip   s    ||Ox6H|IIry   c                 $    | j                  d      S )z!Get list of mutual fund holdings.rN   r   r   s    rw   mf_holdingszKiteConnect.mf_holdings$  s    yy''ry   c                 B    | j                  | j                  d            S )z$Get list of mutual fund instruments.rO   )_parse_mf_instrumentsr   r   s    rw   mf_instrumentszKiteConnect.mf_instruments(  s    ))$))4D*EFFry   c                     |r$| j                  | j                  dd|i            S | j                  | j                  d            S )a  
        Retrieve the list of market instruments available to trade.

        Note that the results could be large, several hundred KBs in size,
        with tens of thousands of entries in the list.

        - `exchange` is specific exchange to fetch (Optional)
        rQ   r   r   rP   )_parse_instrumentsr   )rt   r   s     rw   instrumentszKiteConnect.instruments,  sH     **4995IU_aiTj9+kll**4995M+NOOry   c                     t        |      }t        |      dkD  rt        |d         t         k(  r|d   }| j                  dd|i      }|D ci c]  }|| j	                  ||          c}S c c}w )z
        Retrieve quote for list of instruments.

        - `instruments` is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. For example NSE:INFY
        r   rT   ir   )r   r   r   r   r   )rt   r  insr   keys        rw   quotezKiteConnect.quote:  st     ; {aDQ$8D$@a.Cyyc
y;AEF#T**4955FFFs   A,c                     t        |      }t        |      dkD  rt        |d         t         k(  r|d   }| j                  dd|i      S )z
        Retrieve OHLC and market depth for list of instruments.

        - `instruments` is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. For example NSE:INFY
        r   rU   r  r   r   r   r   r   rt   r  r  s      rw   ohlczKiteConnect.ohlcI  sN     ; {aDQ$8D$@a.Cyy,c3Zy@@ry   c                     t        |      }t        |      dkD  rt        |d         t         k(  r|d   }| j                  dd|i      S )z
        Retrieve last price for list of instruments.

        - `instruments` is a list of instruments, Instrument are in the format of `exchange:tradingsymbol`. For example NSE:INFY
        r   rV   r  r   r  r  s      rw   ltpzKiteConnect.ltpW  sN     ; {aDQ$8D$@a.Cyy+S#Jy??ry   c           
      .   d}t        |      t        j                  k(  r|j                  |      n|}t        |      t        j                  k(  r|j                  |      n|}	| j                  d||d||	||rdnd|rdndd      }
| j	                  |
      S )a5  
        Retrieve historical data (candles) for an instrument.

        Although the actual response JSON from the API does not have field
        names such has 'open', 'high' etc., this function call structures
        the data into an array of objects with field names. For example:

        - `instrument_token` is the instrument identifier (retrieved from the instruments()) call.
        - `from_date` is the From date (datetime object or string in format of yyyy-mm-dd HH:MM:SS.
        - `to_date` is the To date (datetime object or string in format of yyyy-mm-dd HH:MM:SS).
        - `interval` is the candle interval (minute, day, 5 minute etc.).
        - `continuous` is a boolean flag to get continuous data for futures and options instruments.
        - `oi` is a boolean flag to get open interest.
        z%Y-%m-%d %H:%M:%SrR   )instrument_tokenintervalr   r   )fromtor   
continuousoir   )r   datetimestrftimer   _format_historical)rt   r  	from_dateto_dater   r#  r$  date_string_formatfrom_date_stringto_date_stringr   s              rw   historical_datazKiteConnect.historical_datae  s     1EI)_X`XiXiEi9--.@AoxAEgRZRcRcAc))*<=ipyy,7GU]"^%5#1)10:1(*1!   &&t,,ry   c                     g }|d   D ]a  }t         j                  j                  |d         |d   |d   |d   |d   |d   d}t        |      d	k(  r|d
   |d<   |j	                  |       c |S )Ncandlesr   r               )dateopenhighlowclosevolumer      r$  )r   r   r   r   append)rt   r   recordsdrecords        rw   r'  zKiteConnect._format_historical  s    i 	#A --ad3!!t1A$F 1v{ ttNN6"	# ry   c                     t        |      }t        |      dkD  rt        |d         t         k(  r|d   }| j                  dd|j	                         id|i      S )z5Retrieve the buy/sell trigger range for Cover Orders.r   rS   r   r  r   )r   r   r   r   lower)rt   r   r  r  s       rw   trigger_rangezKiteConnect.trigger_range  sf    ; {aDQ$8D$@a.Cyy/#57G7M7M7O"P!$c
  , 	,ry   c                 $    | j                  d      S )z(Fetch list of gtt existing in an accountrW   r   r   s    rw   get_gttszKiteConnect.get_gtts  s    yyry   c                 ,    | j                  dd|i      S )zFetch details of a GTTrY   
trigger_idr   r   rt   rE  s     rw   get_gttzKiteConnect.get_gtt  s    yy|Z.HyIIry   c                    t        |      t        k7  rt        j                  d      || j                  k(  r#t        |      dk7  rt        j                  d      || j                  k(  r#t        |      dk7  rt        j                  d      ||||d}g }|D ]l  }	dD ]+  }
|
|	vst        j                  dj                  |
	             |j                  |||	d
   t        |	d         |	d   |	d   t        |	d         d       n ||fS )zGet GTT payloadz!invalid type for `trigger_values`r   z2invalid `trigger_values` for single leg order typer0  z+invalid `trigger_values` for OCO order type)r   r   trigger_values
last_price)r   r   r   r   r   z`{req}` missing inside orders)reqr   r   r   r   r   )r   r   r   r   r   r   r   )r   r   exInputExceptionGTT_TYPE_SINGLEr   GTT_TYPE_OCOformatr;  intfloat)rt   trigger_typer   r   rI  rJ  r:   	condition
gtt_ordersorK  s              rw   _get_gtt_payloadzKiteConnect._get_gtt_payload  s4   4'##$GHH4///C4G14L##$XYYT...3~3F!3K##$QRR !*,$	
	 
 	AY ]a<++,K,R,RWZ,R,[\\] $!.$%&8$9*.oY<qz* 	 *$$ry   c                     || j                   | j                  fv sJ | j                  ||||||      \  }}| j                  dt	        j
                  |      t	        j
                  |      |d      S )aF  
        Place GTT order

        - `trigger_type` The type of GTT order(single/two-leg).
        - `tradingsymbol` Trading symbol of the instrument.
        - `exchange` Name of the exchange.
        - `trigger_values` Trigger values (json array).
        - `last_price` Last price of the instrument at the time of order placement.
        - `orders` JSON order array containing following fields
            - `transaction_type` BUY or SELL
            - `quantity` Quantity to transact
            - `price` The min or max price to execute the order at (for LIMIT orders)
        rX   rT  r:   r   r   )rO  rN  rW  r   jsondumps)	rt   rS  r   r   rI  rJ  r:   rT  rU  s	            rw   	place_gttzKiteConnect.place_gtt  s~    "  1 143G3GHHHH $ 5 5lMS[]kmwy  !A	:zz+I.jj, /"z # 	#ry   c                     | j                  ||||||      \  }}	| j                  dd|it        j                  |      t        j                  |	      |d      S )aG  
        Modify GTT order

        - `trigger_type` The type of GTT order(single/two-leg).
        - `tradingsymbol` Trading symbol of the instrument.
        - `exchange` Name of the exchange.
        - `trigger_values` Trigger values (json array).
        - `last_price` Last price of the instrument at the time of order placement.
        - `orders` JSON order array containing following fields
            - `transaction_type` BUY or SELL
            - `quantity` Quantity to transact
            - `price` The min or max price to execute the order at (for LIMIT orders)
        rZ   rE  rY  r   )rW  r   rZ  r[  )
rt   rE  rS  r   r   rI  rJ  r:   rT  rU  s
             rw   
modify_gttzKiteConnect.modify_gtt  sj      !% 5 5lMS[]kmwy  !A	:yy#/"<*.**Y*?'+zz*'=%1!3  4 	4ry   c                 ,    | j                  dd|i      S )zDelete a GTT order.r[   rE  r   r   rF  s     rw   
delete_gttzKiteConnect.delete_gtt  s    ||LL*3M|NNry   c                 *    | j                  d|d      S )z
        Calculate margins for requested order list considering the existing positions and open orders

        - `params` is list of orders to retrive margins detail
        r\   Tr   is_jsonr   rt   r   s     rw   order_marginszKiteConnect.order_margins  s     zz/&$zGGry   c                 2    | j                  d|d||d      S )aM  
        Calculate total margins required for basket of orders including margin benefits

        - `params` is list of orders to fetch basket margin
        - `consider_positions` is a boolean to consider users positions
        - `mode` is margin response mode type. compact - Compact mode will only give the total margins
        r]   T)consider_positionsmode)r   rc  query_paramsr   )rt   r   rg  rh  s       rw   basket_order_marginsz KiteConnect.basket_order_margins	  s.     zz0!'"&>PZ^'_  a 	ary   c                 *    | j                  d|d      S )z
        Calculates detailed charges order-wise for the order book
        - `params` is list of orders to fetch charges detail
        r^   Trb  r   rd  s     rw   get_virtual_contract_notez%KiteConnect.get_virtual_contract_note  s#    
 zz/!'"&  ( 	(ry   c                 l    t        j                  dt               t        j                  |t               y)z! Add deprecation warning message alwaysN)warningssimplefilterDeprecationWarningwarn)rt   messages     rw   _warnzKiteConnect._warn  s"    h(:;g12ry   c                    |}t         s1t        |      t        k(  r|j                  d      j	                         }g }t        j                  t        |            }|D ]  }t        |d         |d<   t        |d         |d<   t        |d         |d<   t        |d         |d<   t        |d         |d<   t        |d         dk(  r3t        j                  j                  |d         j                         |d<   |j                  |        |S )	Nr   r  rJ  strike	tick_sizelot_sizeexpiry
   )r   r   bytesdecodestripcsv
DictReaderr   rQ  rR  r   r   r   r   r4  r;  rt   r   r=  r<  readerrows         rw   r  zKiteConnect._parse_instruments$  s    tAw%'G$**,A, 	 C&)#.@*A&BC"# %c,&7 8C!#h-0CM$S%56C!#j/2C
O 3x=!R' ( 5 5c(m D I I KHNN3	  ry   c                    |}t         s1t        |      t        k(  r|j                  d      j	                         }g }t        j                  t        |            }|D ]  }t        |d         |d<   t        |d         |d<   t        |d         |d<   t        |d         |d<   t        |d         |d<   t        t        |d               |d<   t        t        |d               |d<   t        |d	         |d	<   t        |d
         dk(  r3t        j                  j                  |d
         j                         |d
<   |j!                  |        |S )Nr   minimum_purchase_amountpurchase_amount_multiplier"minimum_additional_purchase_amountminimum_redemption_quantityredemption_quantity_multiplierpurchase_allowedredemption_allowedrJ  last_price_daterz  )r   r   r{  r|  r}  r~  r  r   rR  boolrQ  r   r   r   r   r4  r;  r  s         rw   r  z!KiteConnect._parse_mf_instruments=  s[   tAw%'G$**,A, 	 C-237P3Q-RC)*05c:V6W0XC,-8=cBf>g8hC4516s;X7Y1ZC-.49#>^:_4`C01&*3s3E/F+G&HC"#(,S5I1J-K(LC$% %c,&7 8C 3()*b0)1)>)>sCT?U)V)[)[)]%&NN3	   ry   c                 >    t         dz   j                         t        z   S )Nz-python/)r   
capitalizer   r   s    rw   _user_agentzKiteConnect._user_agentX  s    J&224{BBry   c                 .    | j                  |d|||      S )z Alias for sending a GET request.GETr   r   rc  _requestrt   router   r   rc  s        rw   r   zKiteConnect._get[  s    }}UEHVU\}]]ry   c                 0    | j                  |d||||      S )z!Alias for sending a POST request.POSTr   r   rc  ri  r  rt   r  r   r   rc  ri  s         rw   r   zKiteConnect._post_  s    }}UFXfV]lx}yyry   c                 0    | j                  |d||||      S )z Alias for sending a PUT request.PUTr  r  r  s         rw   r   zKiteConnect._putc  s    }}UEHVU\kw}xxry   c                 .    | j                  |d|||      S )z#Alias for sending a DELETE request.DELETEr  r  r  s        rw   r   zKiteConnect._deleteg  s    }}UHxX_}``ry   c                    |r  | j                   |   j                  di |}n| j                   |   }t        | j                  |      }| j                  | j                         d}	| j                  r<| j                  r0| j                  dz   | j                  z   }
dj                  |
      |	d<   | j                  r(t        j                  dj                  ||||	             |dv r|}	 | j                  j                  |||dv r|r|nd	|dv r|s|nd	||	| j                   d
| j                  | j                  
      }| j                  r:t        j                  dj                  |j                   |j"                               d|j$                  d   v r	 |j'                         }|j/                  d      dk(  s|j/                  d      rx| j0                  r'|j                   dk(  r|d   dk(  r| j1                          t3        t*        |j/                  d      t*        j4                        } ||d   |j                         |d   S d|j$                  d   v r|j"                  S t+        j,                  dj                  |j$                  d   |j"                              # t        $ r}|d	}~ww xY w# t(        $ r0 t+        j,                  dj                  |j"                              w xY w)zMake an HTTP request.)zX-Kite-Versionz
User-Agent:ztoken {}Authorizationz*Request: {method} {url} {params} {headers})r}   urlr   headers)r  r  )r  r  NT)rZ  r   r   r  verifyallow_redirectsrj   rf   zResponse: {code} {content})codecontentrZ  zcontent-typezDCouldn't parse the JSON response received from the server: {content})r  r  error
error_typei  TokenExceptionrs  )r  r   r~  z@Unknown Content-Type ({content_type}) with response: ({content}))content_typer  r`   )_routesrP  r   rh   r   r  rb   re   ra   logrm   requestrd   rj   rf   	Exceptionstatus_coder  r  rZ  
ValueErrorrL  DataExceptionr   rc   getattrGeneralException)rt   r  r}   r   r   rc  ri  urir  r  auth_headerrer   exps                  rw   r  zKiteConnect._requestk  s    ,$,,u%,,8x8C,,u%Cdii% #66**,

 <<D--,,,t/@/@@K'1'8'8'EGO$::IIBIIQW]`io  zAI  B  C &&!L	''(+8>/8QV]Vdh8>/8QZaVhl/;07373C3C/C8<0404 ( 	>A ::II299q}}VWV_V_9`a QYY~..(vvx xx!W,0F++0DlI[_oIo,,. b$((<"8":M:MN$y/>><aii//99""#e#l#lYY~6		 $m $# $ $9  	G	  (&&'m't'tII (u (' ( ((s%   (AJ  J3  	J0)J++J039K,)NNFNNNF)N)	NNNNNNNNN)NNNNNNN)NNN)NNNNN)FF)TN)NNF)NNFN)k__name__
__module____qualname____doc__rg   r   ri   r   PRODUCT_MISPRODUCT_CNCPRODUCT_NRML
PRODUCT_COORDER_TYPE_MARKETORDER_TYPE_LIMITORDER_TYPE_SLMORDER_TYPE_SLVARIETY_REGULAR
VARIETY_COVARIETY_AMOVARIETY_ICEBERGVARIETY_AUCTIONTRANSACTION_TYPE_BUYTRANSACTION_TYPE_SELLVALIDITY_DAYVALIDITY_IOCVALIDITY_TTLPOSITION_TYPE_DAYPOSITION_TYPE_OVERNIGHTEXCHANGE_NSEEXCHANGE_BSEEXCHANGE_NFOEXCHANGE_CDSEXCHANGE_BFOEXCHANGE_MCXEXCHANGE_BCDMARGIN_EQUITYMARGIN_COMMODITYSTATUS_COMPLETESTATUS_REJECTEDSTATUS_CANCELLEDrO  rN  GTT_STATUS_ACTIVEGTT_STATUS_TRIGGEREDGTT_STATUS_DISABLEDGTT_STATUS_EXPIREDGTT_STATUS_CANCELLEDGTT_STATUS_REJECTEDGTT_STATUS_DELETEDr  rx   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r:   r   r;   r   r   r   r   r   r   r   r   r   r  r  r
  r  r  r  r  r  r  r-  r'  rA  rC  rG  rW  r\  r^  r`  re  rj  rl  rt  r  r  r  r   r   r   r   r  r`   ry   rw   r
   r
      s    1A  KKLJ !NM  OJKOO !" LLL ) LLLLLLL M" !O O" LO !&$"&$":%: 0: 	3: 		:
 	: 	 9: 	): 	): 	*: 	*: 	6: 	6: 	3:" 	5#:$ 	3%:& 	%&D':( 	&'=):. 	\/:0 	01:2 	,3:4 	25:8 	:9:: 	*;:< 	
=:> 	,?:@ 	,A:D 	~E:F 	+G:J 	!.K:L 	7M:N 	.O:P 	TQ:R 	 OS:V 	W:X +( $022 + 10s:G| #"15f*()h<
*	-) !!%'+"&!%%)#'!5@ &*" $#'"(,4,UU9":_:a0/7&A !%"P? %)$(* "!"& $%)$J(GPGA@->"
, J %D#242OHa(3
26C^zyaF$ry   r
   )r  sixr   r   six.moves.urllib.parser   r~  rZ  dateutil.parserr   r   loggingr%  rk   ro  r   r   kiteconnect.exceptions
exceptionsrL  	getLoggerr  r  objectr
   r`   ry   rw   <module>r     sP     * 
        / #g!V$& V$ry   