J11. Zerodha Kite Connect API में Access Token Reuse कैसे करें?

 

Zerodha Kite Connect API में Access Token Reuse कैसे करें? Python Tutorial

Introduction

अगर आप Zerodha Kite Connect API के साथ Algo Trading, Futures Scanner या Trading Dashboard बना रहे हैं, तो हर बार Python Script चलाने पर Login Process दोहराना असुविधाजनक हो सकता है।

Kite Connect का Access Token अपनी Validity के दौरान दोबारा इस्तेमाल किया जा सकता है। इसलिए आप Token को सुरक्षित तरीके से Store करके अगली बार Script चलाते समय उसे Load करने का प्रयास कर सकते हैं।

इस Tutorial में हम सीखेंगे:

  • Existing Access Token को Reuse कैसे करें।
  • Access Token को Local File में कैसे Save करें।
  • Token Invalid होने पर क्या करें।
  • Zerodha Profile और Margin Data कैसे प्राप्त करें।
  • API Session से Logout कैसे करें।

1. Kite Connect Client Initialize करें

सबसे पहले Python में Kite Connect Library Import करें और API Key की मदद से Client Object बनाएँ।

अगर Library Install नहीं है, तो Terminal में यह Command चलाएँ:

python -m pip install kiteconnect pandas

अब Python Code लिखें:

from kiteconnect import KiteConnect

api_key = "YOUR_API_KEY"
api_secret = "YOUR_API_SECRET"

kite = KiteConnect(api_key=api_key)

यहाँ:

  • api_key आपके Application की पहचान के लिए इस्तेमाल होती है।
  • api_secret नए Authentication Session के लिए आवश्यक होता है।
  • kite API Client Object है, जिसके माध्यम से आप उपलब्ध API Methods का इस्तेमाल कर सकते हैं।

Security Tip: API Secret और Access Token को Public GitHub Repository या Blogger Post में कभी शेयर न करें।

2. Access Token को Local File में Save करें

Authentication पूरा होने के बाद प्राप्त Access Token को एक Local File में Store किया जा सकता है।

उदाहरण के लिए, File का नाम access_token.txt रख सकते हैं।

Token Save करने का Example:

from pathlib import Path

token_file = Path("access_token.txt")

access_token = "YOUR_ACCESS_TOKEN"

token_file.write_text(
    access_token,
    encoding="utf-8"
)

print("Access token saved.")

इस Example में YOUR_ACCESS_TOKEN को Authentication Process से प्राप्त वास्तविक Token से बदलना होगा।

यह Code Token को File में Save करता है। लेकिन वास्तविक Project में इस File को सुरक्षित रखना आवश्यक है। इसे Public Repository में Commit न करें और जहाँ संभव हो, Environment Variables या Secure Secret Storage का इस्तेमाल करें।

3. Existing Access Token को Reuse करें

अब हम ऐसा Function बनाएँगे जो पहले Saved Access Token को Load करे और फिर API Call से उसकी Validity Check करने का प्रयास करे।

from pathlib import Path
from kiteconnect import KiteConnect
from kiteconnect.exceptions import TokenException

api_key = "YOUR_API_KEY"
token_file = Path("access_token.txt")

kite = KiteConnect(api_key=api_key)

def load_access_token():
    if not token_file.exists():
        return False

    token = token_file.read_text(
        encoding="utf-8"
    ).strip()

    if not token:
        return False

    kite.set_access_token(token)

    try:
        kite.profile()
        print("Existing access token is valid.")
        return True

    except TokenException:
        print("Saved token is invalid or expired.")
        return False

if load_access_token():
    print("Ready to use Kite Connect API.")
else:
    print("Fresh authentication is required.")

यह Code कैसे काम करता है?

  1. सबसे पहले access_token.txt File की उपलब्धता Check होती है।
  2. File से Token Read किया जाता है।
  3. Token को Kite Connect Client में Set किया जाता है।
  4. kite.profile() से Authenticated API Request की जाती है।
  5. यदि Token Valid है, तो Script आगे काम कर सकती है।
  6. यदि Token Invalid है, तो Fresh Authentication की आवश्यकता होगी।

ध्यान दें कि यह Example Invalid Token को Handle करने के लिए TokenException का इस्तेमाल करता है। Production Application में Network Errors और अन्य API Exceptions को भी अलग से Handle करना चाहिए।

4. Token Invalid होने पर Fresh Login करें

यदि Saved Token Expired या Invalid हो गया है, तो नया Authentication Session Generate करना होगा।

Fresh Login Process में सामान्यतः ये Steps शामिल होते हैं:

  1. Login URL Generate करना।
  2. Browser में Zerodha Login और आवश्यक Verification पूरा करना।
  3. Redirect URL से नया Request Token प्राप्त करना।
  4. API Key और API Secret की मदद से नया Access Token Generate करना।
  5. नए Token को सुरक्षित तरीके से Store करना।

Access Token को Reuse करने का उद्देश्य अनावश्यक Login Process से बचना है, न कि Authentication Requirements को Bypass करना।

महत्वपूर्ण: Access Token की Validity सीमित होती है। सामान्यतः अगले दिन नया Token Generate करना पड़ता है। वर्तमान Authentication Rules के लिए Official Documentation देखें।

5. Zerodha Account Profile प्राप्त करें

जब Valid Access Token Client में Set हो जाए, तो आप Profile Information प्राप्त कर सकते हैं।

profile = kite.profile()

print(profile)

इस Method से उपलब्ध Account Profile Details प्राप्त होती हैं, जिनमें User ID, User Name, Email और Account से संबंधित अन्य जानकारी शामिल हो सकती है।

Profile Data में निजी जानकारी हो सकती है, इसलिए इसे Public Logs या Screenshots में शेयर न करें।

6. Funds और Margin Data प्राप्त करें

Kite Connect API में kite.margins() Method का इस्तेमाल करके उपलब्ध Margin Information प्राप्त की जा सकती है।

Example:

import pandas as pd

margins = kite.margins()

equity_data = margins.get("equity", {})

if equity_data:
    df = pd.json_normalize(equity_data)

    print(df.T)
else:
    print("Equity margin data is unavailable.")

इस Code में क्या हो रहा है?

  • kite.margins() Margin Information प्राप्त करता है।
  • margins.get("equity", {}) Equity Segment का Data निकालता है।
  • pd.json_normalize() Nested JSON Data को Tabular Format में बदलता है।
  • df.T Data को Transpose करके पढ़ने योग्य Format में दिखाता है।

ध्यान दें कि Margin Data Account और API Response के अनुसार बदल सकता है। उपलब्ध Funds को वास्तविक Trading Risk या Guaranteed Buying Power न मानें; Order से पहले Current Margin Requirements की जाँच करें।

7. Kite Connect API से Logout कैसे करें?

काम पूरा होने के बाद Logout करना उपयोगी हो सकता है, खासकर जब Application Shared Computer या किसी अन्य जोखिम वाले Environment में चल रहा हो।

Python में Logout के लिए:

kite.invalidate_access_token()

print("Access token invalidated.")

यह Method वर्तमान Access Token को Invalidate करने के लिए इस्तेमाल होता है। इसके बाद उस Token से आगे API Requests सफल नहीं होंगी और दोबारा उपयोग के लिए Fresh Authentication आवश्यक होगा।

यदि आप Token को Local File में भी Store करते हैं, तो Logout के बाद उस File को हटाने पर विचार करें, ताकि Script गलती से Invalid Token दोबारा Load न करे।

from pathlib import Path

token_file = Path("access_token.txt")

if token_file.exists():
    token_file.unlink()

print("Local token file removed.")

महत्वपूर्ण: Logout करने से पहले सुनिश्चित करें कि कोई अन्य Script उसी Token का उपयोग नहीं कर रही है। Token Invalidate होने पर उन Scripts की API Requests भी प्रभावित हो सकती हैं।

8. Production Application के लिए Best Practices

अपने Python Trading Project में Access Token Management को Reliable बनाने के लिए इन बातों का ध्यान रखें:

  • Token को सुरक्षित Storage में रखें।
  • Token को Public GitHub Repository में Commit न करें।
  • Token Invalid होने पर Fresh Authentication का रास्ता उपलब्ध रखें।
  • Network Errors और API Exceptions को Handle करें।
  • Profile और Margin Data में निजी जानकारी सुरक्षित रखें।
  • Logout के बाद Local Token File की स्थिति को सही तरीके से Manage करें।
  • Live Trading से पहले Authentication और Order Management का परीक्षण करें।

Conclusion

इस Tutorial में आपने सीखा कि Zerodha Kite Connect API में Existing Access Token को कैसे Reuse करें, Token को Local File में कैसे Store करें, Profile और Margin Data कैसे प्राप्त करें तथा Logout कैसे करें।

इन Techniques की मदद से आप अपने Python Trading Application में Authentication Workflow को अधिक व्यवस्थित बना सकते हैं।

Next Tutorial: Zerodha Kite Connect API से Instrument List डाउनलोड करना और Live Market Quotes प्राप्त करना।

Frequently Asked Questions (FAQs)

1. क्या Access Token को हर बार Generate करना जरूरी है?

नहीं। यदि Token Valid है, तो उसकी Validity के दौरान उसे दोबारा इस्तेमाल किया जा सकता है।

2. क्या Access Token को Text File में Save कर सकते हैं?

हाँ, लेकिन File को सुरक्षित रखना चाहिए और उसे Public Repository में Upload नहीं करना चाहिए। अधिक सुरक्षित Applications में Environment Variables या Secure Secret Storage बेहतर विकल्प हो सकते हैं।

3. kite.profile() का क्या उपयोग है?

यह Authenticated API Request के माध्यम से Account Profile Information प्राप्त करता है।

4. kite.margins() क्या करता है?

यह उपलब्ध Margin Information प्राप्त करता है, जिसका इस्तेमाल Trading Application में Account Funds और Margin Data देखने के लिए किया जा सकता है।

5. kite.invalidate_access_token() का क्या उपयोग है?

यह वर्तमान Access Token को Invalidate करता है। इसके बाद उस Token से API Requests करने के लिए Fresh Authentication की आवश्यकता होगी।



Post a Comment

Previous Post Next Post