need to fetch "buy_quantity" from position

palani_kmp
Hi,

I would like to extract my current intraday "buy_quantity" from my positions into some variable as mentioned API doc(attached image file), and I used below code but I got error message(attached image file) "list indices must be integers, not str".

Anyone can help me to fix this? Thanks in advance.




import requests,time,json,sys
def main():
holding1 = requests.get("https://api.kite.trade/portfolio/positions/?api_key='my api key'&access_token='my access token'")
holdjson =holding1.json()
hold1 = holdjson['data']['net']['buy_quantity']
print(hold1)


while True:
main()
time.sleep(5)
  • sujith
    Hi @palani_kmp,
    holdjson['data']['net'] is a JSON array and you seem to be trying to access buy a quantity of array instead of buy quantity of array item.
    It should be something like this holdjson['data']['net'][0][buy_qunatity]
  • palani_kmp
    Hi Sujith,

    Thanks for your help.I have tried as mentioned below, but I am getting "IndexError: list index out of range" .Can you please help me as I am trying this for past 3 days?

    hold1 = holdjson['data']['net'][0][buy_quantity]
  • sujith
    You need to check if the list has elements or not before using it.
  • palani_kmp
    Do you mean any available "buy_quantity" on my position??, currently no buy quantity on my position
  • sujith
    You can only fetch buy_quantity if there is at least one position.
  • palani_kmp
    Sujith,

    My main idea behind to fetch "buy_quantity" is to initiate some action when buy_quantity=0.
    but my code return error whenever buy_quantity is come to zero.

    is there anyway to get intraday positions details (buy/or sell quantity)?

    My code logic as below:

    import requests,time,json,sys
    def main():
    holding1 = requests.get("https://api.kite.trade/portfolio/positions/?api_key="my api key'&access_token='my token'")
    holdjson =holding1.json()
    hold1 = holdjson['data']['net'][0][buy_quantity]

    if hold1 == 0:

    #need to some action


    while True:
    main()
    time.sleep(5)
  • sujith
    Hi,
    You do get the list of intraday and carry forwarded positions in the net field of that json.
    You can check out documentation.
    There should be at least one position to check for buy_quantity.
  • palani_kmp
    Thanks for your solution.its working now..
This discussion has been closed.