### Get Margin Details (Node.js SDK) Source: https://upstox.com/developer/api-documentation/example-code/margins/margin-details Example using the Upstox Node.js SDK to fetch margin details. Demonstrates initializing the SDK client and setting up the request parameters. ```javascript let UpstoxClient = require('upstox-js-sdk'); let defaultClient = UpstoxClient.ApiClient.instance; var OAUTH2 = defaultClient.authentications['OAUTH2']; OAUTH2.accessToken = "{your_access_token}"; let apiInstance = new UpstoxClient.ChargeApi(); let instruments =[new UpstoxClient.Instrument("NSE_EQ|INE669E01016",1,"D","BUY")]; // Note: The original snippet was incomplete. A full example would include: // let marginBody = new UpstoxClient.MarginRequest(instruments); // apiInstance.postMargin(marginBody, (error, data, response) => { // if (error) { // console.error(error); // return; // } // console.log('API response:', data); // }); ``` -------------------------------- ### Get Funds and Margin (Java SDK) Source: https://upstox.com/developer/api-documentation/example-code/user/get-fund-and-margin Provides an example of using the Upstox Java SDK to retrieve user funds and margin for the equity segment. Covers SDK initialization and API method invocation. ```java import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.GetUserFundMarginResponse; import com.upstox.auth.*; import io.swagger.client.api.UserApi; public class Main { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); UserApi apiInstance = new UserApi(); String apiVersion = "2.0"; // String | API Version Header String segment = "SEC"; // String | try { GetUserFundMarginResponse result = apiInstance.getUserFundMargin(apiVersion, segment); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#getUserFundMargin"); e.printStackTrace(); } } } ``` -------------------------------- ### Get Funds and Margin (SDK Usage) Source: https://upstox.com/developer/api-documentation/example-code/user/get-fund-and-margin Illustrates how to retrieve user funds and margin details using the official Upstox SDKs for Python, Node.js, and Java. These examples abstract away direct HTTP calls, simplifying integration. ```python-sdk import upstox_client from upstox_client.rest import ApiException configuration = upstox_client.Configuration() configuration.access_token = '{your_access_token}' api_version = '2.0' api_instance = upstox_client.UserApi(upstox_client.ApiClient(configuration)) try: # Get User Fund And Margin api_response = api_instance.get_user_fund_margin(api_version) print(api_response) except ApiException as e: print("Exception when calling UserApi->get_user_fund_margin: %s\n" % e) ``` ```nodejs-sdk let UpstoxClient = require('upstox-js-sdk'); let defaultClient = UpstoxClient.ApiClient.instance; var OAUTH2 = defaultClient.authentications['OAUTH2']; OAUTH2.accessToken = "{your_access_token}"; let apiInstance = new UpstoxClient.UserApi(); let apiVersion = "2.0"; apiInstance.getUserFundMargin(apiVersion, null, (error, data, response) => { if (error) { console.error(error); } else { console.log('API called successfully. Returned data: ' + JSON.stringify(data)); } }); ``` ```java-sdk import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.GetUserFundMarginResponse; import com.upstox.auth.*; import io.swagger.client.api.UserApi; public class Main { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); UserApi apiInstance = new UserApi(); String apiVersion = "2.0"; // String | API Version Header String segment = ""; try { GetUserFundMarginResponse result = apiInstance.getUserFundMargin(apiVersion, segment); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#getUserFundMargin"); e.printStackTrace(); } } } ``` -------------------------------- ### Get User MTF Positions - Node.js (Axios) Source: https://upstox.com/developer/api-documentation/example-code/portfolio/get-mtf-positions Fetches user MTF positions via the Upstox API using the Node.js 'axios' library. This example demonstrates making an authenticated GET request. Ensure 'axios' is installed (`npm install axios`). ```javascript const axios = require('axios'); const url = 'https://api.upstox.com/v3/portfolio/mtf-positions'; const headers = { 'Accept': 'application/json', 'Authorization': 'Bearer {your_access_token}' }; axios.get(url, { headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); ``` -------------------------------- ### Place Order using Upstox SDKs Source: https://upstox.com/developer/api-documentation/example-code/orders/place-order Demonstrates placing an order using the Upstox client libraries. It covers initialization, authentication, request body creation, and API call execution for Python, JavaScript, and Java. ```Python from upstox_client.rest import ApiException import upstox_client configuration = upstox_client.Configuration() configuration.access_token = '{your_access_token}' api_instance = upstox_client.OrderApi(upstox_client.ApiClient(configuration)) # Example: Place a market order body = upstox_client.PlaceOrderRequest( quantity=1, product=upstox_client.PlaceOrderRequest.ProductEnum.D, # D for Delivery validity=upstox_client.PlaceOrderRequest.ValidityEnum.DAY, # DAY for Day order price=0.0, # Price is 0 for MARKET orders tag="string", instrument_token="NSE_EQ|INE528G01035", order_type=upstox_client.PlaceOrderRequest.OrderTypeEnum.MARKET, # MARKET order transaction_type=upstox_client.PlaceOrderRequest.TransactionTypeEnum.BUY, # BUY or SELL disclosed_quantity=0, trigger_price=0.0, is_amo=True # True for AMO, False otherwise ) api_version = '2.0' try: api_response = api_instance.place_order(body, api_version) print(api_response) except ApiException as e: print(f"Exception when calling OrderApi->place_order: {e}\n") ``` ```JavaScript let UpstoxClient = require('upstox-js-sdk'); let defaultClient = UpstoxClient.ApiClient.instance; var OAUTH2 = defaultClient.authentications['OAUTH2']; OAUTH2.accessToken = "{your_access_token}"; let apiInstance = new UpstoxClient.OrderApi(); // Example: Place a market order let body = new UpstoxClient.PlaceOrderRequest( 1, // Quantity UpstoxClient.PlaceOrderRequest.ProductEnum.D, // Product Type (D for Delivery) UpstoxClient.PlaceOrderRequest.ValidityEnum.DAY, // Validity (DAY for Day order) 0.0, // Price (0 for MARKET orders) "NSE_EQ|INE528G01035", // Instrument Token UpstoxClient.PlaceOrderRequest.OrderTypeEnum.MARKET, // Order Type (MARKET) UpstoxClient.PlaceOrderRequest.TransactionTypeEnum.BUY, // Transaction Type (BUY or SELL) 0, // Disclosed Quantity 0.0, // Trigger Price true // AMO (After Market Order) flag ); let apiVersion = "2.0"; apiInstance.placeOrder(body, apiVersion, (error, data, response) => { if (error) { console.error(error.response.text); } else { console.log('API called successfully. Returned data: ' + JSON.stringify(data)); } }); ``` ```Java import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.PlaceOrderRequest; import com.upstox.api.PlaceOrderResponse; import com.upstox.auth.*; import io.swagger.client.api.OrderApi; public class Main { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); // Configure API key authorization: OAUTH2 OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); OrderApi apiInstance = new OrderApi(); PlaceOrderRequest body = new PlaceOrderRequest(); // Example: Place a market order body.setQuantity(1); body.setProduct(PlaceOrderRequest.ProductEnum.D); // D for Delivery body.setValidity(PlaceOrderRequest.ValidityEnum.DAY); // DAY for Day order body.setPrice(0F); // Price is 0 for MARKET orders body.setTag("string"); body.setInstrumentToken("NSE_EQ|INE669E01016"); body.orderType(PlaceOrderRequest.OrderTypeEnum.MARKET); // MARKET order body.setTransactionType(PlaceOrderRequest.TransactionTypeEnum.BUY); // BUY or SELL body.setDisclosedQuantity(0); body.setTriggerPrice(0F); body.setIsAmo(true); // True for AMO, False otherwise String apiVersion = "2.0"; // String | API Version Header try { PlaceOrderResponse result = apiInstance.placeOrder(body, apiVersion); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling OrderApi#placeOrder "); e.printStackTrace(); } } } ``` -------------------------------- ### Upstox Java SDK: Get OHLC Market Quotes Source: https://upstox.com/developer/api-documentation/example-code/market-quote/ohlc-quotes-v3 Demonstrates fetching OHLC market data using the Upstox Java SDK. Requires the SDK setup and an access token. The example shows how to configure the client and make the API call. ```java import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.MarketQuoteV3Api; import com.upstox.model.GetMarketQuoteOHLCResponseV3; import com.upstox.auth.*; public class Main { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); // The rest of the Java SDK code would follow here to call the API. // Example: // MarketQuoteV3Api apiInstance = new MarketQuoteV3Api(defaultClient); // try { // GetMarketQuoteOHLCResponseV3 result = apiInstance.getMarketQuoteOHLC("1d", "NSE_EQ|INE669E01016,NSE_EQ|INE848E01016"); // System.out.println(result); // } catch (ApiException e) { // System.err.println("Exception when calling MarketQuoteV3Api#getMarketQuoteOHLC"); // System.err.println("Status code: " + e.getCode()); // System.err.println("Body: " + e.getResponseBody()); // e.printStackTrace(); // } } } ``` -------------------------------- ### Place Order with Upstox Client Source: https://upstox.com/developer/api-documentation/example-code/orders/place-order Demonstrates placing an order using the Upstox client library. It covers setting up the API client, authenticating with an access token, constructing the order request body, and making the API call to place the order. Error handling for API exceptions is also included. ```python import upstox_client from upstox_client.rest import ApiException # Configuration configuration = upstox_client.Configuration() configuration.access_token = '{your_access_token}' # Initialize API instance api_instance = upstox_client.OrderApi(upstox_client.ApiClient(configuration)) # Create order request body # Parameters: quantity, product, validity, price, tag, instrument_token, order_type, transaction_type, disclosed_quantity, trigger_price, is_amo body = upstox_client.PlaceOrderRequest(1, "I", "DAY", 0.0, "string", "NSE_EQ|INE528G01035", "MARKET", "BUY", 0, 0.0, False) api_version = '2.0' # Place the order try: api_response = api_instance.place_order(body, api_version) print(api_response) except ApiException as e: print("Exception when calling OrderApi->place_order: %s\n" % e) ``` ```javascript let UpstoxClient = require('upstox-js-sdk'); let defaultClient = UpstoxClient.ApiClient.instance; var OAUTH2 = defaultClient.authentications['OAUTH2']; OAUTH2.accessToken = "{your_access_token}"; let apiInstance = new UpstoxClient.OrderApi(); // Create order request body // Parameters: quantity, product, validity, instrument_token, order_type, transaction_type, disclosed_quantity, price, is_amo let body = new UpstoxClient.PlaceOrderRequest(1, UpstoxClient.PlaceOrderRequest.ProductEnum.I, UpstoxClient.PlaceOrderRequest.ValidityEnum.DAY, "NSE_EQ|INE528G01035",UpstoxClient.PlaceOrderRequest.OrderTypeEnum.MARKET,UpstoxClient.PlaceOrderRequest.TransactionTypeEnum.BUY, 0, 0.0, false); let apiVersion = "2.0"; // Place the order apiInstance.placeOrder(body, apiVersion, (error, data, response) => { if (error) { console.error(error.response.text); } else { console.log('API called successfully. Returned data: ' + data); } }); ``` ```java import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.PlaceOrderRequest; import com.upstox.api.PlaceOrderResponse; import com.upstox.auth.*; import io.swagger.client.api.OrderApi; public class Main { public static void main(String[] args) { // Initialize API client ApiClient defaultClient = Configuration.getDefaultApiClient(); // Authenticate OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); OrderApi apiInstance = new OrderApi(); // Create order request body PlaceOrderRequest body = new PlaceOrderRequest(); body.setQuantity(1); body.setProduct(PlaceOrderRequest.ProductEnum.I); body.setValidity(PlaceOrderRequest.ValidityEnum.DAY); body.setPrice(0F); body.setTag("string"); body.setInstrumentToken("NSE_EQ|INE528G01035"); body.orderType(PlaceOrderRequest.OrderTypeEnum.MARKET); body.setTransactionType(PlaceOrderRequest.TransactionTypeEnum.BUY); body.setDisclosedQuantity(0); body.setTriggerPrice(0F); body.setIsAmo(false); String apiVersion = "2.0"; // API Version Header // Place the order try { PlaceOrderResponse result = apiInstance.placeOrder(body, apiVersion); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling OrderApi#placeOrder "); e.printStackTrace(); } } } ``` -------------------------------- ### Websocket Implementation Samples Source: https://upstox.com/developer/api-documentation/sample-implementation Access sample code for streaming market data and order updates via Websocket. These examples are hosted on GitHub and are available for multiple programming languages. ```Python https://github.com/upstox/upstox-python/tree/master/examples/websocket ``` ```PHP https://github.com/upstox/upstox-php/tree/master/examples/websocket ``` ```NodeJS https://github.com/upstox/upstox-nodejs/tree/master/examples/websocket ``` ```Java https://github.com/upstox/upstox-java/tree/master/examples/websocket ``` ```React https://github.com/upstox/upstox-nodejs/tree/master/examples/websocket/react_websocket ``` -------------------------------- ### Get User Positions - Multi-Language Examples Source: https://upstox.com/developer/api-documentation/example-code/portfolio/get-positions Examples demonstrating how to fetch user positions using the Upstox API in various programming languages and SDKs. All examples use the same API endpoint and require an access token for authentication. ```curl curl --location 'https://api.upstox.com/v2/portfolio/short-term-positions' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer {your_access_token}' ``` ```python import requests url = 'https://api.upstox.com/v2/portfolio/short-term-positions' headers = { 'Accept': 'application/json', 'Authorization': 'Bearer {your_access_token}' } response = requests.get(url, headers=headers) print(response.json()) ``` ```javascript const axios = require('axios'); const url = 'https://api.upstox.com/v2/portfolio/short-term-positions'; const headers = { 'Accept': 'application/json', 'Authorization': 'Bearer {your_access_token}' }; axios.get(url, { headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); ``` ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class Main { public static void main(String[] args) { String url = "https://api.upstox.com/v2/portfolio/short-term-positions"; String acceptHeader = "application/json"; String authorizationHeader = "Bearer {your_access_token}"; HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Accept", acceptHeader) .header("Authorization", authorizationHeader) .build(); try { HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } catch (Exception e) { e.printStackTrace(); } } } ``` ```php ``` ```python-sdk import upstox_client from upstox_client.rest import ApiException configuration = upstox_client.Configuration() configuration.access_token = '{your_access_token}' api_version = '2.0' api_instance = upstox_client.PortfolioApi(upstox_client.ApiClient(configuration)) try: api_response = api_instance.get_positions(api_version) print(api_response) except ApiException as e: print("Exception when calling ChargeApi->get_brokerage: %s\n" % e) ``` ```javascript-sdk let UpstoxClient = require('upstox-js-sdk'); let defaultClient = UpstoxClient.ApiClient.instance; var OAUTH2 = defaultClient.authentications['OAUTH2']; OAUTH2.accessToken = "{your_access_token}"; let apiInstance = new UpstoxClient.PortfolioApi(); let apiVersion = "2.0"; apiInstance.getPositions(apiVersion,(error,data,response)=>{ if(error) { console.log(error); } else{ console.log("API called= " + JSON.stringify(data)) } }) ``` ```java-sdk import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.GetPositionResponse; import com.upstox.auth.*; import io.swagger.client.api.PortfolioApi; public class Main { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); PortfolioApi apiInstance = new PortfolioApi(); String apiVersion = "2.0"; // String | API Version Header try { GetPositionResponse result = apiInstance.getPositions(apiVersion); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PortfolioApi#getPositions"); e.printStackTrace(); } } } ``` -------------------------------- ### Get Trades for Order using Upstox Java SDK Source: https://upstox.com/developer/api-documentation/example-code/orders/get-order-trades Provides an example of using the Upstox Java SDK to retrieve trade data for a given order ID. It covers authentication setup and calling the SDK's order API. ```java import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.GetTradeResponse; import com.upstox.auth.*; import io.swagger.client.api.OrderApi; public class Main { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); OrderApi apiInstance = new OrderApi(); String apiVersion = "2.0"; String orderId = "240125010587640"; try { GetTradeResponse result = apiInstance.getTradesByOrder(orderId, apiVersion); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling OrderApi#getTradesByOrder"); e.printStackTrace(); } } } ``` -------------------------------- ### Upstox SDK and Example Code Source: https://upstox.com/developer/api-documentation/orders Information on the Upstox Software Development Kit (SDK) and links to example code snippets to help developers integrate with the APIs quickly. ```APIDOC Upstox SDK and Example Code: SDK: Description: Information about available SDKs for various programming languages to simplify API integration. Example Code: Description: Provides practical code examples demonstrating how to use different Upstox API functionalities. ``` -------------------------------- ### Get User MTF Positions - Python (Requests) Source: https://upstox.com/developer/api-documentation/example-code/portfolio/get-mtf-positions Retrieves user MTF positions using the Python 'requests' library. This method makes a direct HTTP GET call to the Upstox API endpoint. Ensure the 'requests' library is installed (`pip install requests`). ```python import requests url = 'https://api.upstox.com/v3/portfolio/mtf-positions' headers = { 'Accept': 'application/json', 'Authorization': 'Bearer {your_access_token}' } response = requests.get(url, headers=headers) print(response.json()) ``` -------------------------------- ### Place Order using Upstox API Source: https://upstox.com/developer/api-documentation/example-code/orders/place-order Demonstrates how to place an order using the Upstox API. This includes setting up the client, authentication with an access token, defining order parameters, and making the API call. Handles potential API exceptions. ```python import upstox_client from upstox_client.rest import ApiException # Configure the Upstox client with your access token configuration = upstox_client.Configuration() configuration.access_token = '{your_access_token}' # Initialize the Order API instance api_instance = upstox_client.OrderApi(upstox_client.ApiClient(configuration)) # Define the order request body # Parameters: quantity, product, validity, price, tag, instrument_token, order_type, transaction_type, disclosed_quantity, trigger_price, is_amo body = upstox_client.PlaceOrderRequest(1, "D", "DAY", 20, "string", "NSE_EQ|INE528G01035", "SL", "BUY", 0, 19.5, False) # Specify the API version api_version = '2.0' # Attempt to place the order and print the response or error try: api_response = api_instance.place_order(body, api_version) print(api_response) except ApiException as e: print("Exception when calling OrderApi->place_order: %s\n" % e) ``` ```javascript let UpstoxClient = require('upstox-js-sdk'); let defaultClient = UpstoxClient.ApiClient.instance; var OAUTH2 = defaultClient.authentications['OAUTH2']; OAUTH2.accessToken = "{your_access_token}"; let apiInstance = new UpstoxClient.OrderApi(); // Define the order request body // Parameters: quantity, product, validity, price, instrument_token, order_type, transaction_type, disclosed_quantity, trigger_price, is_amo let body = new UpstoxClient.PlaceOrderRequest(1, UpstoxClient.PlaceOrderRequest.ProductEnum.D, UpstoxClient.PlaceOrderRequest.ValidityEnum.DAY, 20.0, "NSE_EQ|INE528G01035",UpstoxClient.PlaceOrderRequest.OrderTypeEnum.SL,UpstoxClient.PlaceOrderRequest.TransactionTypeEnum.BUY, 0, 19.5, false); // Specify the API version let apiVersion = "2.0"; // Attempt to place the order using a callback apiInstance.placeOrder(body, apiVersion, (error, data, response) => { if (error) { console.error(error.response.text); } else { console.log('API called successfully. Returned data: ' + data); } }); ``` ```java import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.PlaceOrderRequest; import com.upstox.api.PlaceOrderResponse; import com.upstox.auth.*; import io.swagger.client.api.OrderApi; public class Main { public static void main(String[] args) { // Get the default API client ApiClient defaultClient = Configuration.getDefaultApiClient(); // Authenticate using OAuth2 with your access token OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); // Initialize the Order API instance OrderApi apiInstance = new OrderApi(); // Define the order request body PlaceOrderRequest body = new PlaceOrderRequest(); body.setQuantity(1); body.setProduct(PlaceOrderRequest.ProductEnum.D); body.setValidity(PlaceOrderRequest.ValidityEnum.DAY); body.setPrice(14F); body.setTag("string"); body.setInstrumentToken("NSE_EQ|INE669E01016"); body.orderType(PlaceOrderRequest.OrderTypeEnum.SL); body.setTransactionType(PlaceOrderRequest.TransactionTypeEnum.BUY); body.setDisclosedQuantity(0); body.setTriggerPrice(13.1F); body.setIsAmo(false); // Specify the API version String apiVersion = "2.0"; // String | API Version Header // Attempt to place the order and print the response or error try { PlaceOrderResponse result = apiInstance.placeOrder(body, apiVersion); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling OrderApi#placeOrder "); e.printStackTrace(); } } } ``` -------------------------------- ### Get GTT Order Details (Java HttpClient) Source: https://upstox.com/developer/api-documentation/example-code/gtt-orders/get-gtt-order-details Provides an example of how to get GTT order details using Java's built-in HttpClient. It constructs an HTTP GET request with appropriate headers. ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class Main { public static void main(String[] args) { String url = "https://api.upstox.com/v3/order/gtt?gtt_order_id=GTT-C25280200071351"; String token = "Bearer {your_access_token}"; // Create the HttpClient HttpClient httpClient = HttpClient.newHttpClient(); // Create the HttpRequest HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Accept", "application/json") .header("Authorization", token) .GET() .build(); try { // Send the request and retrieve the response HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); // Print the response status code and body System.out.println("Response Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); } catch (Exception e) { // Handle exceptions e.printStackTrace(); } } } ``` -------------------------------- ### Get Trade Charges (Python SDK) Source: https://upstox.com/developer/api-documentation/example-code/trade-profit-and-loss/get-trade-charges Example of initializing and configuring the Upstox Python SDK to prepare for fetching trade charges. It shows setting the access token and creating an API client instance for the TradeProfitAndLossApi. Note: The snippet is incomplete and does not show the actual API call. ```python import upstox_client from upstox_client.rest import ApiException configuration = upstox_client.Configuration() configuration.access_token = '{your_access_token}' api_instance = upstox_client.TradeProfitAndLossApi(upstox_client.ApiClient(configuration)) segment = 'EQ' financial_year = '2324' # str | Financial year for which data has been requested. Concatenation of last 2 digits of from year and to year Sample:for 2021-2022, financial_year will be 2122 api_version = '2.0' # str | API Version Header from_date = '02-04-2023' # str | Date from which data needs to be fetched. from_date and to_date should fall under the same financial year as mentioned in financial_year attribute. Date in dd-mm-yyyy format (optional) ``` -------------------------------- ### Place Order with Upstox Client Source: https://upstox.com/developer/api-documentation/example-code/orders/place-order Demonstrates how to place a trading order using the Upstox client library. It covers authentication with an access token and making a call to the Order API to place a specific order type. Examples are provided for Python, JavaScript, and Java. ```python from upstox_client.rest import ApiException configuration = upstox_client.Configuration() configuration.access_token = '{your_access_token}' api_instance = upstox_client.OrderApi(upstox_client.ApiClient(configuration)) body = upstox_client.PlaceOrderRequest(1, "D", "DAY", 0.0, "string", "NSE_EQ|INE528G01035", "SL-M", "BUY", 0, 21.5, False) api_version = '2.0' try: api_response = api_instance.place_order(body, api_version) print(api_response) except ApiException as e: print("Exception when calling OrderApi->place_order: %s\n" % e) ``` ```javascript let UpstoxClient = require('upstox-js-sdk'); let defaultClient = UpstoxClient.ApiClient.instance; var OAUTH2 = defaultClient.authentications['OAUTH2']; OAUTH2.accessToken = "{your_access_token}"; let apiInstance = new UpstoxClient.OrderApi(); let body = new UpstoxClient.PlaceOrderRequest(1, UpstoxClient.PlaceOrderRequest.ProductEnum.D, UpstoxClient.PlaceOrderRequest.ValidityEnum.DAY, 0.0, "NSE_EQ|INE528G01035",UpstoxClient.PlaceOrderRequest.OrderTypeEnum.SL_M,UpstoxClient.PlaceOrderRequest.TransactionTypeEnum.BUY, 0, 24.5, false); let apiVersion = "2.0"; apiInstance.placeOrder(body, apiVersion, (error, data, response) => { if (error) { console.error(error.response.text); } else { console.log('API called successfully. Returned data: ' + data); } }); ``` ```java import com.upstox.ApiClient; import com.upstox.ApiException; import com.upstox.Configuration; import com.upstox.api.PlaceOrderRequest; import com.upstox.api.PlaceOrderResponse; import com.upstox.auth.*; import io.swagger.client.api.OrderApi; public class Main { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2"); OAUTH2.setAccessToken("{your_access_token}"); OrderApi apiInstance = new OrderApi(); PlaceOrderRequest body = new PlaceOrderRequest(); body.setQuantity(1); body.setProduct(PlaceOrderRequest.ProductEnum.D); body.setValidity(PlaceOrderRequest.ValidityEnum.DAY); body.setPrice(0F); body.setTag("string"); body.setInstrumentToken("NSE_EQ|INE669E01016"); body.orderType(PlaceOrderRequest.OrderTypeEnum.SL_M); body.setTransactionType(PlaceOrderRequest.TransactionTypeEnum.BUY); body.setDisclosedQuantity(0); body.setTriggerPrice(15.1F); body.setIsAmo(false); String apiVersion = "2.0"; // String | API Version Header try { PlaceOrderResponse result = apiInstance.placeOrder(body, apiVersion); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling OrderApi#placeOrder "); e.printStackTrace(); } } } ``` -------------------------------- ### Get Expiries - Code Examples Source: https://upstox.com/developer/api-documentation/example-code/expired-instruments/get-expiries Provides code examples for fetching expiry dates using various programming languages and SDKs. These examples demonstrate how to make the API request, including setting up headers and handling responses. ```curl curl --location 'https://api.upstox.com/v2/expired-instruments/expiries?instrument_key=NSE_INDEX%7CNifty%2050' \ --header 'Authorization: Bearer {your_access_token}' \ --header 'Accept: application/json' ``` ```Python import requests url = 'https://api.upstox.com/v2/expired-instruments/expiries?instrument_key=NSE_INDEX%7CNifty%2050' headers = { 'Authorization': 'Bearer {your_access_token}', 'Accept': 'application/json' } response = requests.get(url, headers=headers) print(response.json()) ``` ```Node.js const axios = require('axios'); const url = 'https://api.upstox.com/v2/expired-instruments/expiries?instrument_key=NSE_INDEX%7CNifty%2050'; const headers = { 'Authorization': 'Bearer {your_access_token}', 'Accept': 'application/json' }; axios.get(url, { headers: headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error('Error fetching expiries:', error); }); ``` ```Java import okhttp3.*; import java.io.IOException; public class UpstoxApi { public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.upstox.com/v2/expired-instruments/expiries?instrument_key=NSE_INDEX%7CNifty%2050") .get() .addHeader("Authorization", "Bearer {your_access_token}") .addHeader("Accept", "application/json") .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { System.out.println(response.body().string()); } else { System.err.println("Error: " + response.code() + " - " + response.message()); } } } } ``` ```PHP ```