Navigation

    SmartAPI Forum
    • Register
    • Login
    • Search
    • Categories
    • Popular
    • Groups
    • FAQs
    • API Docs
    1. Home
    2. T2453A1
    3. Posts
    T
    • Profile
    • Following 0
    • Followers 0
    • Topics 2
    • Posts 5
    • Best 0
    • Groups 0

    Posts made by T2453A1

    • Unable to fetch data using Python

      Tried the python code attached

      • one from AngelOne github
      • my own coding (not included)

      I am unable to pull all the fields -
      Angelone gives nothing
      My code gives me ltp data but then blank in the remaining

      Used quote, smartfeed instead of ltp data but just doesnt move. it logs in successfully

      import os
      import time
      import sqlite3
      import json
      from datetime import datetime, timedelta
      
      import pandas as pd
      import pyotp
      from dotenv import load_dotenv
      from SmartApi import SmartConnect
      
      # --------------------------
      # Load environment variables
      # --------------------------
      load_dotenv()
      API_KEY = os.getenv("API_KEY")
      CLIENT_ID = os.getenv("CLIENT_ID")
      PASSWORD = os.getenv("PASSWORD")
      TOTP_SECRET = os.getenv("TOTP_SECRET")
      
      # --------------------------
      # Initialize SmartAPI
      # --------------------------
      smartapi = SmartConnect(api_key=API_KEY)
      
      # --------------------------
      # Session handling
      # --------------------------
      def get_session():
          """Reuse session token if valid, else generate a new one."""
          if os.path.exists("session.json"):
              with open("session.json", "r") as f:
                  data = json.load(f)
              expiry = datetime.fromtimestamp(data.get("expiry", 0))
              if expiry > datetime.now():
                  smartapi.setAccessToken(data["jwtToken"])
                  print("✅ Using existing session token.")
                  return data
      
          # Generate new session
          print("🔑 Generating new session...")
          totp = pyotp.TOTP(TOTP_SECRET).now()
          session = smartapi.generateSession(CLIENT_ID, PASSWORD, totp)
          token_data = {
              "jwtToken": session["data"]["jwtToken"],
              "refreshToken": session["data"]["refreshToken"],
              "expiry": (datetime.now() + timedelta(hours=23)).timestamp()
          }
          with open("session.json", "w") as f:
              json.dump(token_data, f)
          smartapi.setAccessToken(token_data["jwtToken"])
          print("✅ New session saved.")
          return token_data
      
      # --------------------------
      # Database setup
      # --------------------------
      DB_PATH = "stocks.db"
      conn = sqlite3.connect(DB_PATH)
      cursor = conn.cursor()
      
      # --------------------------
      # Load symbols to fetch
      # --------------------------
      query = """
      SELECT DISTINCT symbol, token, exch_seg
      FROM equity_master
      WHERE exch_seg='NSE' AND token IS NOT NULL
      LIMIT 50
      """
      symbols_df = pd.read_sql(query, conn)
      print(f"📊 Loaded {len(symbols_df)} symbols from equity_master")
      
      # --------------------------
      # Fetch session
      # --------------------------
      tokens = get_session()
      
      # --------------------------
      # Fetch market data
      # --------------------------
      updated = []
      
      for _, row in symbols_df.iterrows():
          try:
              symbol = row["symbol"]
              token = str(row["token"])
              exchange = row["exch_seg"]
      
              # LTP / full quote
              data = smartapi.ltpData(exchange, symbol, token)
              quote = data.get("data", {})
      
              updated.append((
                  symbol,
                  exchange,
                  token,
                  quote.get("ltp"),
                  quote.get("open"),
                  quote.get("high"),
                  quote.get("low"),
                  quote.get("close"),
                  quote.get("lastTradeQty"),
                  quote.get("exchFeedTime"),
                  quote.get("exchTradeTime"),
                  quote.get("netChange"),
                  quote.get("percentChange"),
                  quote.get("avgPrice"),
                  quote.get("tradeVolume"),
                  quote.get("opnInterest"),
                  quote.get("lowerCircuit"),
                  quote.get("upperCircuit"),
                  quote.get("totBuyQuan"),
                  quote.get("totSellQuan"),
                  quote.get("weekLow52"),
                  quote.get("weekHigh52"),
                  datetime.now().strftime("%Y-%m-%d %H:%M:%S")
              ))
      
              time.sleep(0.2)
      
          except Exception as e:
              print(f"⚠️ {symbol} ({token}): {e}")
      
      # --------------------------
      # Insert / update DB
      # --------------------------
      cursor.executemany("""
      INSERT INTO market_live (
          symbol, exchange, symbolToken, ltp, open, high, low, close,
          lastTradeQty, exchFeedTime, exchTradeTime, netChange, percentChange,
          avgPrice, tradeVolume, opnInterest, lowerCircuit, upperCircuit,
          totBuyQuan, totSellQuan, weekLow52, weekHigh52, updated_at
      )
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(symbol) DO UPDATE SET
          ltp=excluded.ltp,
          open=excluded.open,
          high=excluded.high,
          low=excluded.low,
          close=excluded.close,
          lastTradeQty=excluded.lastTradeQty,
          exchFeedTime=excluded.exchFeedTime,
          exchTradeTime=excluded.exchTradeTime,
          netChange=excluded.netChange,
          percentChange=excluded.percentChange,
          avgPrice=excluded.avgPrice,
          tradeVolume=excluded.tradeVolume,
          opnInterest=excluded.opnInterest,
          lowerCircuit=excluded.lowerCircuit,
          upperCircuit=excluded.upperCircuit,
          totBuyQuan=excluded.totBuyQuan,
          totSellQuan=excluded.totSellQuan,
          weekLow52=excluded.weekLow52,
          weekHigh52=excluded.weekHigh52,
          updated_at=excluded.updated_at
      """, updated)
      
      conn.commit()
      print(f"✅ Market data updated in 'market_live' ({len(updated)} records)")
      
      # --------------------------
      # Export to Excel
      # --------------------------
      df = pd.read_sql("SELECT * FROM market_live", conn)
      df.to_excel("market_live.xlsx", index=False)
      print("📊 Exported to market_live.xlsx")
      
      conn.close()
      
      
      posted in Python SDK
      T
      T2453A1
    • RE: YOUR USER ID OR PASSWORD IS INVALID","errorcode":"AB1007

      @admin Hi how to get client id. In my profile showing NA

      posted in General Discussion
      T
      T2453A1
    • RE: How to get my Angel Broking Client ID ?

      @dileep

      Q 1. How to get my angel brooking client id?
      Q 2. In login API, We need to use same API panel password to access API or something other password?
      Q3. What is the solution of AB1007 response code?

      posted in General Discussion
      T
      T2453A1
    • How to get my Angel Broking Client ID ?

      Hi Team ,

      How to get my Angel Brooking Client ID. in my profile showing NA

      posted in General Discussion
      T
      T2453A1
    • RE: YOUR USER ID OR PASSWORD IS INVALID","errorcode":"AB1007

      @nikeshwasekar said in YOUR USER ID OR PASSWORD IS INVALID","errorcode":"AB1007:

      Migration was already done for account SCAO1296. But Im still getting
      YOUR USER ID OR PASSWORD IS INVALID","errorcode":"AB1007

      Same my side, kindly provide a solution for that.

      posted in General Discussion
      T
      T2453A1