Unable to exchange authorization token for localhost and upstox

  1. we are able to login to upstox using API after giving mobile number, OTP and key …then we are getting token in url but unable to exchange between server for localhost development.
    below is the code that we are using for callback.
    import axios from ‘axios’;
    export default async function handler(req, res) {
    const { code } = req.query;
    if (!code) {
    return res.status(400).json({ error: ‘Authorization code is missing’ });
    }
    const url = ‘https://api.upstox.com/v2/login/authorization/token’;
    const headers = {
    ‘accept’: ‘application/json’,
    ‘Content-Type’: ‘application/x-www-form-urlencoded’,
    };

    const data = {
    code: code,
    client_id: process.env.NEXT_PUBLIC_UPSTOX_API_KEY,
    client_secret: process.env.UPSTOX_API_SECRET,
    redirect_uri: process.env.UPSTOX_REDIRECT_URL,
    grant_type: ‘authorization_code’,
    };
    axios.post(url, new URLSearchParams(data), { headers })
    .then(response => {
    console.log(response.status);
    console.log(response.data);
    }).catch(error => {
    console.error(error.response.status);
    console.error(error.response.data);
    })};

Hi @Mukut_Mishra, could you please share the error message you’re receiving so we can look into it further?

Hi Ketan, Thanks for prompt reply.
below is the the for authorization that we are using from documentation for nodejs in nextjs application. we are getting reponse as “API resolved without sending a response for /api/callback?code=2S_jxr, this may result in stalled requests.” with my details in json format not publishing here.what is missing in below code i need your help on it so that we can move ahead for other part of code.
200
"import axios from ‘axios’;

export default async function handler(req, res){
const { code } = req.query;
const url = ‘https://api.upstox.com/v2/login/authorization/token’;
const headers = {
‘accept’: ‘application/json’,
‘Content-Type’: ‘application/x-www-form-urlencoded’,
};

const data = {
code: code,
client_id: process.env.NEXT_PUBLIC_UPSTOX_API_KEY,
client_secret: process.env.UPSTOX_API_SECRET,
redirect_uri: process.env.UPSTOX_REDIRECT_URL,
grant_type: ‘authorization_code’,
};
axios.post(url, new URLSearchParams(data), { headers })
.then(response => {
console.log(response.status);
console.log(response.data);
})
.catch(error => {
console.error(error.response.status);
console.error(error.response.data);
})};

we are also receiving access token with this… but seems this is not sufficient.

Hi @Ketan i have change the method to get live data… now using web socket but it is failing.can u pls help to check and correct the code.

  // Set up WebSocket connection
  const ws = new WebSocket('wss://api.upstox.com/v2/feed/market-data-feed');

  ws.onopen = () => {
    const guid = process.env.SESSION_SECRET; // Use SESSION_SECRET as GUID
    const request = {
      guid,
      method: 'sub',
      data: {
        mode: 'full',
        instrumentKeys: symbols,
      },
    };

    ws.send(JSON.stringify(request));
  };

  ws.onmessage = (event) => {
    const response = JSON.parse(event.data);

for symbols.
const symbols = [
“NSE_INDEX|Nifty 50”,
“NSE_INDEX|Nifty Fin Service”,
“NSE_INDEX|Nifty Bank”,
“NSE_INDEX|Nifty Midcap 50”
];

Hi @Mukut_Mishra,

As stated in the documentation, you need to enable redirects when using the /feed/market-data-feed endpoint.

If redirects are not enabled, you should call /feed/market-data-feed/authorize, which will return a WebSocket (wss) URL in the JSON response. For more details, please check the Get Market Data Feed Authorize section.

Additionally, you can refer to the React Example for implementation guidance.

To simplify working with websockets, we offer streamer functionalities in various languages:

Thank you

I tried to use let UpstoxClient = require(“upstox-js-sdk”);
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications[“OAUTH2”];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamer([“MCX_FO|426268”, “MCX_FO|427608”], “full”);
streamer.connect();

streamer.on(“message”, (data) => {
const feed = data.toString(“utf-8”);
console.log(feed);
});

but getting error like
:warning: ./pages/dashboard/index.js
Attempted import error: ‘upstox-js-sdk’ does not contain a default export (imported as ‘UpstoxClient’).

./pages/dashboard/index.js
Attempted import error: ‘upstox-js-sdk’ does not contain a default export (imported as ‘UpstoxClient’).
GET /dashboard 200 in 1251ms
:warning: Fast Refresh had to perform a full reload. Read more: Fast Refresh had to perform full reload | Next.js
GET /_next/static/webpack/e807feaa6d247c7a.webpack.hot-update.json 404 in 714ms
GET /dashboard 200 in 27ms

here is my full code.
// dashboard/dashboard.js
import { useState, useEffect } from ‘react’;
import * as UpstoxClient from ‘upstox-js-sdk’; // Use named imports
import { getCookie } from ‘cookies-next’;

const Dashboard = () => {
const [marketData, setMarketData] = useState();
const [error, setError] = useState(null);
const [nextRefresh, setNextRefresh] = useState(new Date());

// Replace with your desired instruments
//const instrumentKeys = [“MCX_FO|426268”, “MCX_FO|427608”];
const instrumentKeys = [“NSE_INDEX|Nifty 50”, “NSE_INDEX|Nifty Fin Service”, “NSE_INDEX|Nifty Bank”, “NSE_INDEX|Nifty Midcap 50”];

useEffect(() => {
// Setting up Upstox client
const defaultClient = UpstoxClient.ApiClient.instance;
const OAUTH2 = defaultClient.authentications[“OAUTH2”];

// Getting the access token from cookies
const accessToken = getCookie('upstox_access_token');

if (!accessToken) {
  setError('Access token not available. Please log in.');
  return;
}

OAUTH2.accessToken = accessToken; // Set access token

// Create Market Data Streamer
const streamer = new UpstoxClient.MarketDataStreamer(instrumentKeys, "full");

// Function to handle incoming messages
streamer.on("message", (data) => {
  const feed = JSON.parse(data.toString("utf-8"));
  console.log(feed); // Log the incoming feed

  // Format the feed data
  const updatedData = feed.data.map((item) => ({
    index: item.instrument_key.split('|')[1], // Extracting the index name
    strikePrice: item.last_price,
    lastPrice: item.last_price,
    volume: item.volume,
    netChange: item.net_change,
    timestamp: item.timestamp,
  }));

  // Set market data and calculate support/resistance
  setMarketData(updatedData);
  setNextRefresh(new Date(new Date().getTime() + 120000)); // Set next refresh time
});

// Connecting to the streamer
streamer.connect();

// Handle WebSocket errors
streamer.on("error", (err) => {
  console.error("WebSocket error:", err);
  setError('WebSocket error occurred, trying to reconnect...');
});

// Cleanup on component unmount
return () => {
  streamer.disconnect(); // Disconnect when the component unmounts
};

}, );

// Calculate support and resistance based on strike prices
const calculateSupportResistance = (data) => {
const support = Math.min(…data.map(d => d.strikePrice));
const resistance = Math.max(…data.map(d => d.strikePrice));
return { support, resistance };
};

const { support, resistance } = calculateSupportResistance(marketData);

// Predict whether to buy a Call or Put based on volume and net change
const predictBuy = (data) => {
if (data.volume > 10000 && data.netChange < -10) {
return ‘BUY PUT’;
} else if (data.volume > 10000 && data.netChange > 10) {
return ‘BUY CALL’;
}
return ‘HOLD’;
};

const getRowClass = (netChange) => {
if (netChange > 0) return ‘bg-green-100’;
if (netChange < 0) return ‘bg-red-100’;
return ‘bg-yellow-100’;
};

return (


NSE Market Dashboard


{error &&

{error}

}

Next refresh at:


Support Level: {support}


Resistance Level: {resistance}
















{marketData.map((data, index) => (
<tr key={index} className={${getRowClass(data.netChange)} border-t hover:bg-gray-100}>







))}

Index Strike Price Last Price Volume Net Change Prediction
{data.index} {data.strikePrice} {data.lastPrice} {data.volume} {data.netChange} {predictBuy(data)}



);
};

export default Dashboard;