I want API for get real time sensex data

please send code in php Curl

To access real-time data, it is recommended to use the websocket method. Start by consulting the documentation at Market Data Feed | Upstox Developer API.

For a quick initiation, you can reference the example code for websocket implementation.

Python: upstox-python/examples/websocket/market_data at master · upstox/upstox-python · GitHub

PHP: upstox-php/examples/websocket/market_data at master · upstox/upstox-php · GitHub

I trust that the provided information will be helpful.

I want API for showing current Sensex value on my website .i got the API key and secret key.then i am generate the authorization code this will generate code. Then i want access token but getting Forbidden.

This Process is right or wrong.plz reply or call on 8097632010

Could you please send an exact error and error screenshot of the error you’re encountering when trying to access the API? Additionally, providing your client ID will enable me to assist you more effectively.

Also, check if this thread is useful for you.

Error =Array ( [message] => Forbidden )

This code for getting access token

<?php // Set your Upstox API credentials and other parameters $clientId = 'xxxxxxxxxxxxxxxxxx'; $clientSecret = 'xxxxxxxx'; $authorizationCode = 'xxxxxxxx'; $redirectUri = 'https://isolutionsadvisor.com/'; //$tokenEndpoint = 'https://api.upstox.com/oauth/token'; $tokenEndpoint = 'https://api.upstox.com/oauth/token'; // Prepare the data for the POST request $data = [ 'client_id' => $clientId, 'client_secret' => $clientSecret, 'code' => $authorizationCode, 'redirect_uri' => $redirectUri, 'grant_type' => 'authorization_code', ]; //print_r($data); // Set additional headers $headers = [ 'Accept: application/json', 'Content-Type: application/x-www-form-urlencoded' // Include any other necessary headers, such as x-api-key or Authorization ]; // Initialize cURL session $ch = curl_init(); // Set cURL options curl_setopt($ch, CURLOPT_URL, $tokenEndpoint); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // Set headers // Execute cURL session and get the response $response = curl_exec($ch); // Check for cURL errors if (curl_errno($ch)) { echo 'Curl error: ' . curl_error($ch); // Handle the error as needed } else { // Decode the JSON response $responseData = json_decode($response, true); // Display the response (you may want to handle it differently in a real application) print_r($responseData); } // Close cURL session curl_close($ch);

Please find the valid cURL command for generating the access token. The URL you are using, https://api.upstox.com/oauth/token, is incorrect. I have provided the correct URL in the curl call.

curl --location 'https://api.upstox.com/v2/login/authorization/token' \
--header 'accept: application/json' \
--header 'Api-Version: 2.0' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'code={your_code}' \
--data-urlencode 'client_id=your_client_id}' \
--data-urlencode 'client_secret=your_client_secret}' \
--data-urlencode 'redirect_uri=your_redirect_uri}' \
--data-urlencode 'grant_type=authorization_code'

Additionally, it’s important to remember not to disclose your secret or any other sensitive information on public forums.

got the access token.
getting error
Array ( [message] => ‘*******’ not a valid key=value pair (missing equal-sign) in Authorization header: ‘Bearer *****’. )

below code for getting live Sensex data

<?php $accessToken = '************************'; // Replace with your actual access token $apiKey = '*****************************'; // Replace with your actual API key // Upstox API endpoint for fetching market data $marketDataEndpoint = 'https://api.upstox.com/live/data/'; // Symbol for Sensex (you may need to check the correct symbol for Sensex) $symbol = 'SENSEX'; // Build the complete URL $url = $marketDataEndpoint . $symbol; // Set headers $headers = [ 'Content-Type: application/json', 'x-api-key: ' . $apiKey, 'Authorization: Bearer ' . $accessToken, ]; // Initialize cURL session $ch = curl_init(); // Set cURL options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL session and get the response $response = curl_exec($ch); // Check for cURL errors if (curl_errno($ch)) { echo 'Curl error: ' . curl_error($ch); // Handle the error as needed } else { // Decode the JSON response $responseData = json_decode($response, true); // Display the response (you may want to handle it differently in a real application) print_r($responseData); } // Close cURL session curl_close($ch); ?>

i want this data
image

please reply on query

Not getting live Sensex data.please correct

$apiKey = ‘*****************';
$accessToken = '
’; // Replace with your actual access token

// Upstox API endpoint for fetching market data
$marketDataEndpoint = ‘https://api.upstox.com/live/data/’;

// Symbol for Sensex (you may need to check the correct symbol for Sensex)
$symbol = ‘SENSEX’;

// Build the complete URL
$url = $marketDataEndpoint . $symbol;

// Set headers
$headers = [
‘Content-Type: application/json’,
'x-api-key: ’ . $apiKey,
'Authorization: Bearer ’ . $accessToken,
];

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session and get the response
$response = curl_exec($ch);

// Check for cURL errors
if (curl_errno($ch)) {
echo 'Curl error: ’ . curl_error($ch);
// Handle the error as needed
} else {
// Decode the JSON response
$responseData = json_decode($response, true);

// Display the response (you may want to handle it differently in a real application)
print_r($responseData);

}

// Close cURL session
curl_close($ch);

Please refer the v2 documentation provided at the following link:

It appears that you are currently utilizing a legacy URL in your code, which is no longer supported. I recommend acquainting yourself with the new v2 API as outlined in the documentation above. For accessing real-time data, refer specifically to the WebSocket section available at Get Market Data Feed, and you can find a sample implementation here: Sample Implementation.

i am new in for using web socket please send some steps or code for getting real time Sensex data.

In an earlier conversation, I provided details about the websocket and sample code. If you didn’t catch that, I’m reposting the information for your convenience.

You can find information about the market data feed here: Upstox Market Data Feed API Documentation.

Here’s a link to some sample implementations: Upstox API Sample Implementation.

getting this error
Fatal error : Uncaught Upstox\Client\ApiException: [401] Client error: GET https://api.upstox.com/v2/feed/market-data-feed/authorize resulted in a 401 Unauthorized response: {“status”:“error”,“errors”:[{“errorCode”:“UDAPI100050”,“message”:“Invalid token used to access API”,“propertyPath”:null, (truncated…) in C:\xampp\htdocs\Test1_API\lib\Api\WebsocketApi.php:392 Stack trace: #0 C:\xampp\htdocs\Test1_API\lib\Api\WebsocketApi.php(367): Upstox\Client\Api\WebsocketApi->getMarketDataFeedAuthorizeWithHttpInfo(‘2.0’) #1 C:\xampp\htdocs\Test1_API\websocket_client.php(38): Upstox\Client\Api\WebsocketApi->getMarketDataFeedAuthorize(‘2.0’) #2 C:\xampp\htdocs\Test1_API\websocket_client.php(55): getMarketDataFeedAuthorize(‘2.0’, Object(Upstox\Client\Configuration)) #3 C:\xampp\htdocs\Test1_API\websocket_client.php(103): fetchMarketUpdates() #4 {main} thrown in C:\xampp\htdocs\Test1_API\lib\Api\WebsocketApi.php on line 392

<?php require_once(__DIR__ . '/vendor/autoload.php'); use GuzzleHttp\Client; use WebSocket\Client as WebSocketClient; use Upstox\Client\Configuration; use Upstox\Client\Api\WebsocketApi; use Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse; /** * Function to decode Protobuf messages. * * @param string $buffer The protobuf message as a string. * @return FeedResponse The decoded FeedResponse object. */ function decodeProtobuf($buffer) { $feedResponse = new FeedResponse(); $feedResponse->mergeFromString($buffer); return $feedResponse; } /** * Function to get market data feed authorization. * * @param string $apiVersion The API version. * @param Configuration $configuration The configuration object. * @return array The API response. */ function getMarketDataFeedAuthorize($apiVersion, $configuration) { $apiInstance = new WebsocketApi( new Client(), $configuration ); $apiResponse = $apiInstance->getMarketDataFeedAuthorize($apiVersion); return $apiResponse; } /** * Function to fetch market updates. */ function fetchMarketUpdates() { $apiVersion = '2.0'; $accessToken = '**********************************'; // Configure with your access token $configuration = Configuration::getDefaultConfiguration(); $configuration->setAccessToken($accessToken); // Get the authorized URL for the WebSocket connection $response = getMarketDataFeedAuthorize($apiVersion, $configuration); // Create a WebSocket client instance with the authorized URL and disable SSL verification $client = new WebSocketClient($response['data']['authorized_redirect_uri'], [ 'timeout' => 10, 'context' => stream_context_create([ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false ] ]) ]); echo "Connection successful!\n"; $client->setTimeout(1); // Wait for 1 second // Message payload to send to the server $data = [ "guid" => "someguid", "method" => "sub", "data" => [ "mode" => "full", "instrumentKeys" => ["NSE_INDEX|Nifty Bank", "NSE_INDEX|Nifty 50"] ] ]; // Send the data as binary $client->binary(json_encode($data)); // Continuously receive updates until an error occurs while (true) { try { // Receive and decode the incoming message $message = $client->receive(); $decodedData = decodeProtobuf($message); // Convert the decoded data to JSON and print it var_dump($decodedData->serializeToJsonString()); } catch (\Exception $e) { // Print the error message and exit the loop if an error occurs echo "Error: {$e->getMessage()}\n"; break; } } } // Start fetching market updates fetchMarketUpdates();

Please Solve Query.

Fatal error : Uncaught Upstox\Client\ApiException: [401] Client error: GET https://api.upstox.com/v2/feed/market-data-feed/authorize resulted in a 401 Unauthorized response: {“status”:“error”,“errors”:[{“errorCode”:“UDAPI100050”,“message”:“Invalid token used to access API”,“propertyPath”:null, (truncated…) in C:\xampp\htdocs\Test1_API\lib\Api\WebsocketApi.php:392 Stack trace: #0 C:\xampp\htdocs\Test1_API\lib\Api\WebsocketApi.php(367): Upstox\Client\Api\WebsocketApi->getMarketDataFeedAuthorizeWithHttpInfo(‘2.0’) #1 C:\xampp\htdocs\Test1_API\websocket_client.php(38): Upstox\Client\Api\WebsocketApi->getMarketDataFeedAuthorize(‘2.0’) #2 C:\xampp\htdocs\Test1_API\websocket_client.php(55): getMarketDataFeedAuthorize(‘2.0’, Object(Upstox\Client\Configuration)) #3 C:\xampp\htdocs\Test1_API\websocket_client.php(103): fetchMarketUpdates() #4 {main} thrown in C:\xampp\htdocs\Test1_API\lib\Api\WebsocketApi.php on line 392

Pleae ensure that you are using the correct access token. A 401 error code usually indicates an invalid or expired access token.

getting this error
Connection successful!
Fatal error : Uncaught Error: Class “Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse” not found in C:\xampp\htdocs\upstox-php-master\examples\websocket\market_data\websocket_client.php:19 Stack trace: #0 C:\xampp\htdocs\upstox-php-master\examples\websocket\market_data\websocket_client.php(90): decodeProtobuf(‘\x12\xC6\x02\n\x14NSE_INDEX|…’) #1 C:\xampp\htdocs\upstox-php-master\examples\websocket\market_data\websocket_client.php(103): fetchMarketUpdates() #2 {main} thrown in C:\xampp\htdocs\upstox-php-master\examples\websocket\market_data\websocket_client.php on line 19

<?php require_once ('C:/xampp/htdocs/upstox-php-master/vendor/autoload.php'); use GuzzleHttp\Client; use WebSocket\Client as WebSocketClient; use Upstox\Client\Configuration; use Upstox\Client\Api\WebsocketApi; use Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse; use GPBMetadata\MarketFeeder; //require_once('C:\xampp\htdocs\upstox-php-master\examples\websocket\market_data\protobuf\Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse.php'); /** * Function to decode Protobuf messages. * * @param string $buffer The protobuf message as a string. * @return FeedResponse The decoded FeedResponse object. */ function decodeProtobuf($buffer) { $feedResponse = new FeedResponse(); $feedResponse->mergeFromString($buffer); return $feedResponse; } /** * Function to get market data feed authorization. * * @param string $apiVersion The API version. * @param Configuration $configuration The configuration object. * @return array The API response. */ function getMarketDataFeedAuthorize($apiVersion, $configuration) { $apiInstance = new WebsocketApi( new Client(), $configuration ); $apiResponse = $apiInstance->getMarketDataFeedAuthorize($apiVersion); return $apiResponse; } /** * Function to fetch market updates. */ function fetchMarketUpdates() { $apiVersion = '2.0'; $accessToken = '*******************************'; // Configure with your access token $configuration = Configuration::getDefaultConfiguration(); $configuration->setAccessToken($accessToken); // Get the authorized URL for the WebSocket connection $response = getMarketDataFeedAuthorize($apiVersion, $configuration); // Create a WebSocket client instance with the authorized URL and disable SSL verification $client = new WebSocketClient($response['data']['authorized_redirect_uri'], [ 'timeout' => 10, 'context' => stream_context_create([ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false ] ]) ]); echo "Connection successful!\n"; $client->setTimeout(1); // Wait for 1 second // Message payload to send to the server $data = [ "guid" => "someguid", "method" => "sub", "data" => [ "mode" => "full", "instrumentKeys" => ["NSE_INDEX|Nifty Bank", "NSE_INDEX|Nifty 50"] ] ]; // Send the data as binary $client->binary(json_encode($data)); // Continuously receive updates until an error occurs while (true) { try { // Receive and decode the incoming message $message = $client->receive(); $decodedData = decodeProtobuf($message); // Convert the decoded data to JSON and print it var_dump($decodedData->serializeToJsonString()); } catch (\Exception $e) { // Print the error message and exit the loop if an error occurs echo "Error: {$e->getMessage()}\n"; break; } } } // Start fetching market updates fetchMarketUpdates();

Uncaught Error: Class “Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse” not found in C:\xampp\htdocs\new_change\examples\websocket\market_data\websocket_client.php:20 Stack trace: #0 C:\xampp\htdocs\new_change\examples\websocket\market_data\websocket_client.php(91): decodeProtobuf(‘\x12\xC6\x02\n\x14NSE_INDEX|…’) #1 C:\xampp\htdocs\new_change\examples\websocket\market_data\websocket_client.php(104): fetchMarketUpdates() #2 {main} thrown in C:\xampp\htdocs\new_change\examples\websocket\market_data\websocket_client.php on line 20

i want to show sensex real time data plz correct this code

<?php require_once ('C:/xampp/htdocs/upstox-php-master/vendor/autoload.php'); use GuzzleHttp\Client; use WebSocket\Client as WebSocketClient; use Upstox\Client\Configuration; use Upstox\Client\Api\WebsocketApi; use Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse; use GPBMetadata\MarketFeeder; //require_once('C:\xampp\htdocs\upstox-php-master\examples\websocket\market_data\protobuf\Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse.php'); /** * Function to decode Protobuf messages. * * @param string $buffer The protobuf message as a string. * @return FeedResponse The decoded FeedResponse object. */ function decodeProtobuf($buffer) { $feedResponse = new FeedResponse(); $feedResponse->mergeFromString($buffer); return $feedResponse; } /** * Function to get market data feed authorization. * * @param string $apiVersion The API version. * @param Configuration $configuration The configuration object. * @return array The API response. */ function getMarketDataFeedAuthorize($apiVersion, $configuration) { $apiInstance = new WebsocketApi( new Client(), $configuration ); $apiResponse = $apiInstance->getMarketDataFeedAuthorize($apiVersion); return $apiResponse; } /** * Function to fetch market updates. */ function fetchMarketUpdates() { $apiVersion = '2.0'; $accessToken = '********************************'; // Configure with your access token $configuration = Configuration::getDefaultConfiguration(); $configuration->setAccessToken($accessToken); // Get the authorized URL for the WebSocket connection $response = getMarketDataFeedAuthorize($apiVersion, $configuration); // Create a WebSocket client instance with the authorized URL and disable SSL verification $client = new WebSocketClient($response['data']['authorized_redirect_uri'], [ 'timeout' => 10, 'context' => stream_context_create([ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false ] ]) ]); echo "Connection successful!\n"; $client->setTimeout(1); // Wait for 1 second // Message payload to send to the server $data = [ "guid" => "someguid", "method" => "sub", "data" => [ "mode" => "full", "instrumentKeys" => ["NSE_INDEX|SENSEX"] ] ]; // Send the data as binary $client->binary(json_encode($data)); // Continuously receive updates until an error occurs while (true) { try { // Receive and decode the incoming message $message = $client->receive(); $decodedData = decodeProtobuf($message); // Convert the decoded data to JSON and print it var_dump($decodedData->serializeToJsonString()); } catch (\Exception $e) { // Print the error message and exit the loop if an error occurs echo "Error: {$e->getMessage()}\n"; break; } } } // Start fetching market updates fetchMarketUpdates();

i want to show sensex real time data plz correct this code

<?php require_once ('C:/xampp/htdocs/upstox-php-master/vendor/autoload.php'); use GuzzleHttp\Client; use WebSocket\Client as WebSocketClient; use Upstox\Client\Configuration; use Upstox\Client\Api\WebsocketApi; use Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse; use GPBMetadata\MarketFeeder; //require_once('C:\xampp\htdocs\upstox-php-master\examples\websocket\market_data\protobuf\Com\Upstox\Marketdatafeeder\Rpc\Proto\FeedResponse.php'); /** * Function to decode Protobuf messages. * * @param string $buffer The protobuf message as a string. * @return FeedResponse The decoded FeedResponse object. */ function decodeProtobuf($buffer) { $feedResponse = new FeedResponse(); $feedResponse->mergeFromString($buffer); return $feedResponse; } /** * Function to get market data feed authorization. * * @param string $apiVersion The API version. * @param Configuration $configuration The configuration object. * @return array The API response. */ function getMarketDataFeedAuthorize($apiVersion, $configuration) { $apiInstance = new WebsocketApi( new Client(), $configuration ); $apiResponse = $apiInstance->getMarketDataFeedAuthorize($apiVersion); return $apiResponse; } /** * Function to fetch market updates. */ function fetchMarketUpdates() { $apiVersion = '2.0'; $accessToken = '********************************'; // Configure with your access token $configuration = Configuration::getDefaultConfiguration(); $configuration->setAccessToken($accessToken); // Get the authorized URL for the WebSocket connection $response = getMarketDataFeedAuthorize($apiVersion, $configuration); // Create a WebSocket client instance with the authorized URL and disable SSL verification $client = new WebSocketClient($response['data']['authorized_redirect_uri'], [ 'timeout' => 10, 'context' => stream_context_create([ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false ] ]) ]); echo "Connection successful!\n"; $client->setTimeout(1); // Wait for 1 second // Message payload to send to the server $data = [ "guid" => "someguid", "method" => "sub", "data" => [ "mode" => "full", "instrumentKeys" => ["NSE_INDEX|SENSEX"] ] ]; // Send the data as binary $client->binary(json_encode($data)); // Continuously receive updates until an error occurs while (true) { try { // Receive and decode the incoming message $message = $client->receive(); $decodedData = decodeProtobuf($message); // Convert the decoded data to JSON and print it var_dump($decodedData->serializeToJsonString()); } catch (\Exception $e) { // Print the error message and exit the loop if an error occurs echo "Error: {$e->getMessage()}\n"; break; } } } // Start fetching market updates fetchMarketUpdates();