Navigation

    SmartAPI Forum
    • Register
    • Login
    • Search
    • Categories
    • Popular
    • Groups
    • FAQs
    • API Docs
    1. Home
    2. lamontn651910
    3. Posts
    L
    • Profile
    • Following
    • Followers
    • Topics
    • Posts
    • Best
    • Groups

    Posts made by lamontn651910

    • RE: Re: How to fetch nifty spot data using ltpData()

      @piyushpk Try using the symboltoken as 26009 and tradingsymbol as BANKNIFTY. Except Nifty and BankNIFTY you cannot get the ltp from getLTP endpoint. Please do tell me if you are able to get other than these two.

      posted in Python SDK
      L
      lamontn651910
    • RE: error in fatching live data using websocket in reactJS

      @mani-upa11 It seems that this is an older way, right now websocketV2 is used.

      posted in Bugs
      L
      lamontn651910
    • RE: error in fatching live data using websocket in reactJS

      @surendaracg Try using the below nodejs code it works perfectly

      const express = require('express');
      const WebSocket = require('ws');
      //require("dotenv").config();
      const config = require('./config');
      const app = express();
      const port = 3000;
      
      // WebSocket URL
      const url = 'ws://smartapisocket.angelone.in/smart-stream';
      
      // Authentication headers
      const headers = {
        'Authorization': 'Bearer '+config.jwtToken,
        'x-api-key': config.apiKey,
        'x-client-code': config.clientCode,
        'x-feed-token': config.feedToken,
      };
      
      
      // Create a WebSocket instance
      const socket = new WebSocket(url, { headers });
      
      // Map to store tokenID to tokenName mapping
      const tokenMapping = {
          '99919000':'SENSEX',
          '26000': 'NIFTY 50',
          '99926009': 'NIFTY BANK',
          '99926017': 'INDIA VIX',
          '99926013':'NIFTY NEXT 50',
          /*'99926011',: 'NIFTY MIDCAP 100',
          '99926032',: 'NIFTY SMALLCAP 100',
          '99926037',:'NIFTY FINANCIAL SERVICES',
          '99926012',:'NIFTY 100',
          '99926033',:'NIFTY 200',
          '99926004',:'NIFTY 500',
          '99926011','NIFTY MIDCAP 100',
          */
          '2885': 'RELIANCE',
          '3045': 'SBIN',
          '3432':'TATACONSUM',
          '11723':'JSWSTEEL',
          '3499':'TATASTEEL',
          '11630':'NTPC',
          '14977':'POWERGRID',
          '10604':'BHARTIARTL',
          '16675':'BAJAFINSV',
          '317':'BAJFINANCE',
          '1348':'HEROMOTOCO',
          '5258':'INDUSINDBK',
          '1333':'HDFCBANK',
          '1922':'KOTAKBANK',
          '11536':'TCS',
          '1594':'INFY',
          '1363':'HINDALCO',
          '17388':'ADANIPOWER',
          '236':'ASIANPAINT',
          '3506':'TITAN',
          '25780':'APLAPOLLO',
          '17963':'NESTLEIND',
          '1660':'ITC',
          '2475':'ONGC',
          '3351':'SUNPHARMA',
          '1232':'GRASIM',
          '10940':'DIVISLAB',
          '881':'DRREDDY',
          '7229':'HCLTECH',
          '3787':'WIPRO',
          '547':'BRITANNIA',
          '694':'CIPLA',
          '910':'EICHERMOT',
          '10999':'MARUTI',
          '14937':'MAHINDCIE',
          '21676':'HINDMOTORS',
          '526':'BPCL',
          '20374':'COALINDIA',
          '13538':'TECHM',
          '1394':'HINDUNILVR',
          '3563':'ADANIGREEN',
          '25':'ADANIENT',
          '5097':'ZOMATO',
          '2664':'PIDILITIND',
          '9819':'HAVELLS',
          '772':'DABUR',
          '3103':'SHREECEM',
          '13611':'IRCTC',
          '9480':'LICI',
          '4204':'MOTHERSON',
          '305':'BAJAJHLDNG',
          '2181':'BOSCHLTD',
      };
      
      const tokenIDArray = Object.keys(tokenMapping);
      
      // Store the received data in an array
      //let receivedData = [];
      
      // Handle WebSocket connection open
      socket.on('open', () => {
        //console.log('WebSocket connected');
      
         // Send a subscription request
         const subscriptionRequest = {
          //correlationID: '',
          action: 1,
          params: {
            mode: 2,
            tokenList: [
              {
                exchangeType: 1,
                tokens: tokenIDArray,
              },
              {
                exchangeType: 3,
                tokens: ['99919000'],
              },
            ],
          },
        };
      
        socket.send(JSON.stringify(subscriptionRequest));
      });
      
      // Store the latest data for each instrument
      const latestData = {};
      
      // Handle received messages from the WebSocket
      socket.on('message', (message) => {
        const data = new Uint8Array(message);
      
        // Check if the message is a heartbeat response
        if (data.length === 4 && data[0] === 112 && data[1] === 111 && data[2] === 110 && data[3] === 103) {
          // Ignore heartbeat response
          return;
        }
      
        // Parse the received binary data based on the provided response contract
      
        // Extract the Last Traded Price (LTP) and Token ID from the received data
        const ltpBytes = data.slice(43, 47);
        const closePriceBytes = data.slice(115, 122);
        const tokenIDBytes = data.slice(2, 27);
        const ltpValue = ltpBytes.reduce((value, byte, index) => value + byte * Math.pow(256, index), 0);
        const closePrice = closePriceBytes.reduce((value, byte, index) => value + byte * Math.pow(256, index), 0);
        const ltp = ltpValue / 100;
        const yesterdayPrice = closePrice / 100;
        const priceChange = parseFloat((ltp-yesterdayPrice).toFixed(2));
        const percentChange = parseFloat(((priceChange/ltp)*100).toFixed(2));
      
      //  const decoder = new TextDecoder('utf-8');
        const tokenID = new TextDecoder().decode(tokenIDBytes).replace(/\u0000/g, '');//To decode from Bytes and remove the null characters at the end of tokenID
        const tokenName = tokenMapping[tokenID];//retrieves token name for the corresponding tokenID from the tokenMapping
        // Create a JSON object with tokenID and ltp
        const jsonData = {
          tokenName: tokenName,
          ltp: ltp,
          yesterdayPrice:yesterdayPrice,
          change:priceChange,
          percentChange:percentChange,
        };
      
        // Store the latest data for the instrument
        latestData[tokenID] = jsonData;
        //console.log(latestData)
        // Display the JSON object
         console.log(jsonData);
      });
      
      // Handle WebSocket connection close
      socket.on('close', () => {
        console.log('WebSocket connection closed');
      });
      
      // Send heartbeat message every 30 seconds to keep the connection alive
      setInterval(() => {
        if (socket.readyState === WebSocket.OPEN) {
          socket.send('ping');
        }
      }, 1000);
      
      // Enable CORS
      app.use((req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
        next();
      });
      
      // a GET endpoint to retrieve the latest data for all instruments
      app.get('/api/prices', (req, res) => {
          res.json(latestData);
        });
      // a GET endpoint to retrieve the latest tokenMapping for the instruments
        app.get('/api/mappings', (req, res) => {
          res.json(tokenMapping);
        });
      // Start the Express server
      app.listen(port, () => {
        console.log(`Server listening on port ${port}`);
      });
      
      posted in Bugs
      L
      lamontn651910
    • RE: I got binary response from websocket. How to convert from binary to JSON?

      @muthukumardab
      Try the below code

      //Working Code which fetches prices of reliance, sbi, and nifty
      
      const WebSocket = require('ws');
      
      // WebSocket URL
      const url = 'ws://smartapisocket.angelone.in/smart-stream';
      
      // Authentication headers
      const headers = {
        'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VybmFtZSI6IlA1Mjk3NzQiLCJyb2xlcyI6MCwidXNlcnR5cGUiOiJVU0VSIiwiaWF0IjoxNjg2NzE2ODYwLCJleHAiOjE2ODY4MDMyNjB9.WmoIdanOGGXox-We42Bre-qSK6yyZQlcci4h3JnLxc8Dt7WgmJZa7IzergbdB2VWPviVg7uKWAi-rOr0H5ijQw',
        'x-api-key': 'erZDHFHD',
        'x-client-code': 'P529774',
        'x-feed-token': 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VybmFtZSI6IlA1Mjk3NzQiLCJpYXQiOjE2ODY3MTY4NjAsImV4cCI6MTY4NjgwMzI2MH0.fWOQ57fcTGqzuVlktvzFYVe7ztZrt8TFIkrLXvX-Z2HqOtR3cSxsDRW9uv8a9YSCKxt348gAmSondkaHmGaBBA'
      };
      
      // Create a WebSocket instance
      const socket = new WebSocket(url, { headers });
      
      // Handle WebSocket connection open
      socket.on('open', () => {
        console.log('WebSocket connected');
      
        // Send a subscription request
        const subscriptionRequest = {
          //correlationID: '',
          action: 1,
          params: {
            mode: 1,
            tokenList: [
              {
                exchangeType: 1,
                tokens: ['26000','2885','3045','99926009','99926011']
      
                /*
                NIFTY-50: 26000
                RELIANCE-EQ: 2885
                SBIN-EQ: 3045
                NIFTY BANK:99926009
                NIFTY MIDCAP 100:99926011
                SENSEX: 99919000
      
                */
      
              },
             /* {
                exchangeType: 5,
                tokens: ['234230', '234235', '234219']
              }*/
            ]
          }
        };
      
        socket.send(JSON.stringify(subscriptionRequest));
      });
      
      // Handle received messages from the WebSocket
      socket.on('message', (message) => {
        // Parse the received binary data based on the provided response contract
      
        // Example: Extract the Last Traded Price (LTP) from the received data
        const data = new Uint8Array(message);
        const ltpBytes = data.slice(43, 47);
        const ltpValue = ltpBytes.reduce((value, byte, index) => value + byte * Math.pow(256, index), 0);
        const ltp = ltpValue / 100;
      
        console.log('Received LTP:', ltp);
      });
      
      // Handle WebSocket connection close
      socket.on('close', () => {
        console.log('WebSocket connection closed');
      });
      
      // Send heartbeat message every 30 seconds to keep the connection alive
      setInterval(() => {
        if (socket.readyState === WebSocket.OPEN) {
          socket.send('ping');
        }
      }, 30000);
      
      
      

      P.S. I also had one question which I am not able to find answer to, how to get the price for SENSEX I am not able to find the correct token for it. Please do tell if you know how to get the ltp for sensex.

      posted in Bugs
      L
      lamontn651910
    • The Below JS Code Works

      Re: WebSocket 2.0 Streaming is not Receiving the Live Price Feed

      //Working Code which fetches prices of reliance, sbi, and nifty
      
      const WebSocket = require('ws');
      
      // WebSocket URL
      const url = 'ws://smartapisocket.angelone.in/smart-stream';
      
      // Authentication headers
      const headers = {
        'Authorization': 'Bearer JWT_TOKEN',
        'x-api-key': 'erZDHFHD',
        'x-client-code': 'P529774',
        'x-feed-token': 'FEED_TOKEN'
      };
      
      // Create a WebSocket instance
      const socket = new WebSocket(url, { headers });
      
      // Handle WebSocket connection open
      socket.on('open', () => {
        console.log('WebSocket connected');
      
        // Send a subscription request
        const subscriptionRequest = {
          //correlationID: '',
          action: 1,
          params: {
            mode: 1,
            tokenList: [
              {
                exchangeType: 1,
                tokens: ['26000','2885','3045','99926009','99926011']
      
                /*
                NIFTY-50: 26000
                RELIANCE-EQ: 2885
                SBIN-EQ: 3045
                NIFTY BANK:99926009
                NIFTY MIDCAP 100:99926011
                SENSEX: 99919000
      
                */
      
              },
             /* {
                exchangeType: 5,
                tokens: ['234230', '234235', '234219']
              }*/
            ]
          }
        };
      
        socket.send(JSON.stringify(subscriptionRequest));
      });
      
      // Handle received messages from the WebSocket
      socket.on('message', (message) => {
        // Parse the received binary data based on the provided response contract
      
        // Example: Extract the Last Traded Price (LTP) from the received data
        const data = new Uint8Array(message);
        const ltpBytes = data.slice(43, 47);
        const ltpValue = ltpBytes.reduce((value, byte, index) => value + byte * Math.pow(256, index), 0);
        const ltp = ltpValue / 100;
      
        console.log('Received LTP:', ltp);
      });
      
      // Handle WebSocket connection close
      socket.on('close', () => {
        console.log('WebSocket connection closed');
      });
      
      // Send heartbeat message every 30 seconds to keep the connection alive
      setInterval(() => {
        if (socket.readyState === WebSocket.OPEN) {
          socket.send('ping');
        }
      }, 30000);
      
      
      
      posted in General Discussion
      L
      lamontn651910
    • RE: How to get the live data from market feed for different stocks ?

      @admin I also used the wss url but it still showed error.

      posted in Bugs
      L
      lamontn651910
    • RE: How to get the live data from market feed for different stocks ?

      @admin There is no clear mention on how to connect to the websocket.

      posted in Bugs
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin I have filled the form and it has been 4 working days. But still the account is not migrated.

      posted in Bugs
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin please tell the migration status of P529774

      posted in Bugs
      L
      lamontn651910
    • RE: can't login , Getting "USER IS BLOCKED FOR TRADING" error

      @pankaj8932

      You will need to fill this form to migrate your account. Check others post you might get some clue
      https://docs.google.com/forms/d/e/1FAIpQLSdgpCiDhSBa_bsKsec002e9unbeQkipOLFAKW7DzPvmiowsaw/viewform

      posted in NodeJS SDK
      L
      lamontn651910
    • RE: can't login , Getting "USER IS BLOCKED FOR TRADING" error

      @pankaj8932 you got to migrate your account

      posted in NodeJS SDK
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin please get the account migrated soon.

      posted in Bugs
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin I have registered and this is my client ID P529774.

      posted in Bugs
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin ok

      posted in Bugs
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin i do not have client ID i registered for api using email pattanijeet@gmail.com

      posted in Bugs
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin can you please tell the migration status of my account?

      posted in Bugs
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin please migrate my account

      posted in Bugs
      L
      lamontn651910
    • RE: cannot login even after adding correct password and api key

      @admin what is to be added in the client id. I have registered without adding a client id.

      posted in Bugs
      L
      lamontn651910
    • cannot login even after adding correct password and api key
      var axios = require('axios');
      var data = JSON.stringify({
          "clientcode": "jeet.pattani111293@marwadiuniversity.ac.in",
          "password": "Info@money1411"
      });
      
      var config = {
          method: 'post',
          url: 'https://apiconnect.angelbroking.com//rest/auth/angelbroking/user/v1/loginByPassword',
      
          headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'X-UserType': 'USER',
              'X-SourceID': 'WEB',
              'X-ClientLocalIP': '192.168.124.209',
              'X-ClientPublicIP': '1.38.93.108',
              'X-MACAddress': 'D8-C0-A6-FE-48-4D',
              'X-PrivateKey': '54xZjFDm'
          },
          data: data
      };
      
      axios(config)
          .then(function(response) {
              console.log(JSON.stringify(response.data));
          })
          .catch(function(error) {
              console.log(error);
          });
      

      I have added the email address in the client code and the password and I have also added the correct API key

      Though I get this error

      {"status":false,"message":"YOUR USER ID OR PASSWORD IS INVALID","errorcode":"AB1007","data":null}

      what is supposed to be entered in the fields of client code , password

      please help I am stuck.

      posted in Bugs
      L
      lamontn651910