Exit All Positionsโ
Use this API to exit all open positions in one go. You can filter by segment or tag to exit specific positions, or exit all open positions with a single request. The order_ids of the new orders created to square off will be returned in the response.
Requestโ
curl --location --request POST 'https://api.upstox.com/v2/order/positions/exit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {your_access_token}'
For additional samples in various languages, please refer to the Sample code section on this page.
Query Parametersโ
| Name | Required | Type | Description |
|---|---|---|---|
| segment | false | string | The segment associated with the positions. Possible values: NSE_EQ, BSE_EQ, NSE_FO, BSE_FO, MCX_FO, NCD_FO, BCD_FO, NSE_COM. |
| tag | false | string | The tag associated with the positions. Check the Understanding How the Order Tag Filter Works section for a detailed explanation on how filtering by order tag works. |
Order Tag Scenarioโ
An order tag is a feature that allows traders to categorize or label their orders for better tracking and management. However, it is important to note that order tags are only valid for intraday positions. They are specifically designed for trades that are opened and closed within the same trading session.
When a position is carried forward to the next trading day, the order tag associated with it becomes invalid or irrelevant. This is because carry-forwarded positions are no longer tied to the context of the original trading session where the tag was applied.
For carry-forward positions, use a general exit approach without filtering by tags.
Order Execution Sequenceโ
The system will execute all BUY positions first, followed by the execution of all SELL orders. This ensures a consistent and orderly processing of multiple order types within the same request.
Maximum Position Limitโ
When slicing is applied, we calculate the total number of resulting orders. The total number of orders in a request, including those generated by the slice, must not exceed the maximum position count specified here.
- 2XX
- 4XX
Response Bodyโ
- Success (200)
- Partial Success (207)
{
"status": "success",
"data": {
"order_ids": [
"1644490272000",
"1644490272001",
"1644490272003"
]
},
"errors": null,
"summary": {
"total": 3,
"success": 3,
"error": 0
}
}
| Name | Type | Description |
|---|---|---|
| status | string | A string indicating the outcome of the request. Possible values: success, partial_success, error.success - when all positions were exit successfully. partial_success - when some positions encountered errors. error - when all the positions encountered errors. |
| data | object | Successful response data for exit all positions request. |
| data.order_ids | array | List of reference order IDs associated with successful exit positions. |
| errors | array | An array containing the main content of the error response for partial_success and error scenarios. |
| errors[].error_code | string | A specific error code. |
| errors[].message | string | Descriptive error message. |
| errors[].property_path | string | Indicates which part of the request triggered the error. It can be null. |
| errors[].invalid_value | string | Shows the value causing the error. It can be null. |
| errors[].instrument_key | string | A Key of instrument for a specific position. |
| errors[].order_id | string | Order ID associated to specific position. It can be null. |
| summary | object | A summary of the outcomes for the batch of orders processed, detailing total orders, successful completions, and errors. |
| summary.total | integer | The total number of order present in the payload for exit positions. |
| summary.success | integer | Indicates the successful orders placed for exit positions. |
| summary.error | integer | Indicates the unsuccessful orders placed for exit positions. |
{
"status": "partial_success",
"data": {
"order_ids": [
"1644490272000",
"1644490272001",
"1644490272003"
]
},
"errors": [
{
"error_code": "UDAPI1113",
"message": "The Exit Positions API is accessible during the market hours only.",
"property_path": null,
"invalid_value": null,
"order_id": null,
"instrument_key": "NSE_EQ|INE002A01018"
},
{
"error_code": "UDAPI100500",
"message": "Something went wrong... please contact us",
"property_path": null,
"invalid_value": null,
"order_id": null,
"instrument_key": "MCX_FO|436245"
}
],
"summary": {
"total": 5,
"success": 3,
"error": 2
}
}
| Name | Type | Description |
|---|---|---|
| status | string | A string indicating the outcome of the request. Possible values: success, partial_success, error.success - when all positions were exit successfully. partial_success - when some positions encountered errors. error - when all the positions encountered errors. |
| data | object | Successful response data for exit all positions request. |
| data.order_ids | array | List of reference order IDs associated with successful exit positions. |
| errors | array | An array containing the main content of the error response for partial_success and error scenarios. |
| errors[].error_code | string | A specific error code. |
| errors[].message | string | Descriptive error message. |
| errors[].property_path | string | Indicates which part of the request triggered the error. It can be null. |
| errors[].invalid_value | string | Shows the value causing the error. It can be null. |
| errors[].instrument_key | string | A Key of instrument for a specific position. |
| errors[].order_id | string | Order ID associated to specific position. It can be null. |
| summary | object | A summary of the outcomes for the batch of orders processed, detailing total orders, successful completions, and errors. |
| summary.total | integer | The total number of order present in the payload for exit positions. |
| summary.success | integer | Indicates the successful orders placed for exit positions. |
| summary.error | integer | Indicates the unsuccessful orders placed for exit positions. |
{
"status": "error",
"data": null,
"errors": [
{
"errorCode": "UDAPI1111",
"message": "No open position available to exit",
"propertyPath": null,
"invalidValue": null,
"error_code": "UDAPI1111",
"property_path": null,
"invalid_value": null
}
]
}
{
"status": "error",
"data": null,
"errors": [
{
"error_code": "UDAPI1113",
"message": "The Exit Positions API is accessible during the market hours only.",
"property_path": null,
"invalid_value": null,
"order_id": null,
"instrument_key": "NSE_EQ|INE002A01018"
},
{
"error_code": "UDAPI100500",
"message": "Something went wrong... please contact us",
"property_path": null,
"invalid_value": null,
"order_id": null,
"instrument_key": "MCX_FO|436245"
}
],
"summary": {
"total": 2,
"success": 0,
"error": 2
}
}
| Name | Type | Description |
|---|---|---|
| status | string | A string indicating the outcome of the request. Possible values: success, partial_success, error.success - when all positions were exit successfully. partial_success - when some positions encountered errors. error - when all the positions encountered errors. |
| data | object | Successful response data for exit all positions request. |
| data.order_ids | array | List of reference order IDs associated with successful exit positions. |
| errors | array | An array containing the main content of the error response for partial_success and error scenarios. |
| errors[].error_code | string | A specific error code. |
| errors[].message | string | Descriptive error message. |
| errors[].property_path | string | Indicates which part of the request triggered the error. It can be null. |
| errors[].invalid_value | string | Shows the value causing the error. It can be null. |
| errors[].instrument_key | string | A Key of instrument for a specific position. |
| errors[].order_id | string | Order ID associated to specific position. It can be null. |
| summary | object | A summary of the outcomes for the batch of orders processed, detailing total orders, successful completions, and errors. |
| summary.total | integer | The total number of order present in the payload for exit positions. |
| summary.success | integer | Indicates the successful orders placed for exit positions. |
| summary.error | integer | Indicates the unsuccessful orders placed for exit positions. |
Error Codesโ
| Error code | Description |
|---|---|
| UDAPI1108 | Invalid segment. - Please ensure that segment provided in query param is correct. |
| UDAPI1111 | No open position available to exit. - Please ensure that there are open positions available. |
| UDAPI1112 | Available open positions should not be more than 50. - Please ensure that available positions should be within the limit. |
| UDAPI1113 | The Exit Positions API is accessible during the market hours only. - Please ensure that the market is open for trading in the specified segment. |
Auto Slicingโ
Exchanges enforce a limitation on the maximum quantity that can be placed for any scrip, known as the freeze quantity. If an order exceeds this freeze quantity, it will be rejected by the exchange. To simplify the process and prevent such rejections, we automatically slice the order into smaller parts based on the freeze quantity defined by the exchange when necessary.
For example:โ
If you want to exit position for SCRIP1 with a total quantity of 10,100, and the freeze quantity defined by the exchange is 1,000, then the system will automatically split the position into 11 smaller for execution: 10 positions of 1,000 quantity each, and 1 position of 100 quantity. This ensures that all quantities are accepted and processed by the exchange.
Understanding How the Order Tag Filter Worksโ
How Positions workโ
When you place multiple orders for the same instrument_key, your positions are aggregated based on the total quantity, not by individual orders. This means positions are not identifiable by specific order numbers.
What happens when you filter by Tag?โ
When you use the Exit Position API with a tag filter, the system identifies orders associated with that tag and calculates the total quantity for each instrument_key. It then creates a square-off order for that quantity to exit the position. Note that the square-off is performed based on quantity, not on individual orders.
Let's illustrate how this will work with an example:
- Order 1: You buy 100 shares of
ABC_CORPwith the tagStrategy_A. - Order 2: You buy 50 shares of
ABC_CORPwith the tagStrategy_B.
Your position for ABC_CORP now shows a total of 150 shares.
Now, you decide to exit positions associated with Strategy_A:
- You call the Exit All API with
tag=Strategy_A. - The system identifies that
Strategy_Ais associated withABC_CORPfor 100 shares. - A square-off order is created to sell 100 shares of
ABC_CORP.
Key Takeawayโ
When exiting positions using a tag filter, the system squares off based on total quantities per instrument, not individual orders or tags. Therefore, if you have multiple positions in the same instrument with different tags, exiting positions with a specific tag may impact your overall position in that instrument beyond the intended tag.
Sample Codeโ
Exit all the open positionsโ
- Curl
- Python
- Node.js
- Java
- PHP
- Python SDK
- Node.js SDK
- Java SDK
curl --location --request POST 'https://api.upstox.com/v2/order/positions/exit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {your_access_token}' \
import requests
url = 'https://api.upstox.com/v2/order/positions/exit'
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {your_access_token}',
}
data = {}
try:
# Send the POST request
response = requests.post(url, json=data, headers=headers)
# Print the response status code and body
print('Response Code:', response.status_code)
print('Response Body:', response.json())
except Exception as e:
# Handle exceptions
print('Error:', str(e))
const axios = require('axios');
const url = 'https://api.upstox.com/v2/order/positions/exit';
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {your_access_token}',
};
const data = {};
axios.post(url, data, { headers })
.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error.message);
});
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/order/positions/exit";
String token = "Bearer {your_access_token}";
// empty request body
String requestBody = "";
// Create the HttpClient
HttpClient httpClient = HttpClient.newHttpClient();
// Create the HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("Authorization", token)
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
try {
// Send the request and retrieve the response
HttpResponse<String> 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();
}
}
}
<?php
$url = 'https://api.upstox.com/v2/order/positions/exit';
$headers = [
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer {your_access_token}',
];
$data = [];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Response: ' . $response;
}
curl_close($ch);
?>
import upstox_client
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))
try:
api_response = api_instance.exit_positions()
print(api_response)
except ApiException as e:
print("Exception when calling OrderApi->exit all positions: %s\n" % e.body)
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();
apiInstance.exitPositions(null, (error, data, response) => {
if (error) {
console.error(error.response.text);
} else {
console.log('API called successfully. Returned data: ' + JSON.stringify(data));
}
});
import com.upstox.ApiClient;
import com.upstox.ApiException;
import com.upstox.Configuration;
import com.upstox.api.CancelOrExitMultiOrderResponse;
import com.upstox.auth.OAuth;
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();
try {
CancelOrExitMultiOrderResponse result = apiInstance.exitPositions(null,null);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrderApi#exitPositions= " + e.getResponseBody());
e.printStackTrace();
}
}
}
Exit all the open positions for a given segmentโ
- Curl
- Python
- Node.js
- Java
- PHP
- Python SDK
- Node.js SDK
- Java SDK
curl --location --request POST 'https://api.upstox.com/v2/order/positions/exit?segment=NSE_FO' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {your_access_token}' \
import requests
url = 'https://api.upstox.com/v2/order/positions/exit?segment=NSE_FO'
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {your_access_token}',
}
data = {}
try:
# Send the POST request
response = requests.post(url, json=data, headers=headers)
# Print the response status code and body
print('Response Code:', response.status_code)
print('Response Body:', response.json())
except Exception as e:
# Handle exceptions
print('Error:', str(e))
const axios = require('axios');
const url = 'https://api.upstox.com/v2/order/positions/exit?segment=NSE_FO';
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {your_access_token}',
};
const data = {};
axios.post(url, data, { headers })
.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error.message);
});
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/order/positions/exit?segment=NSE_FO";
String token = "Bearer {your_access_token}";
// empty request body
String requestBody = "";
// Create the HttpClient
HttpClient httpClient = HttpClient.newHttpClient();
// Create the HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("Authorization", token)
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
try {
// Send the request and retrieve the response
HttpResponse<String> 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();
}
}
}
<?php
$url = 'https://api.upstox.com/v2/order/positions/exit?segment=NSE_FO';
$headers = [
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer {your_access_token}',
];
$data = [];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Response: ' . $response;
}
curl_close($ch);
?>
import upstox_client
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))
param = {
'segment': "NSE_FO"
}
try:
api_response = api_instance.exit_positions(**param)
print(api_response)
except ApiException as e:
print("Exception when calling OrderApi->exit all position: %s\n" % e.body)
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();
opts = {
'segment': 'NSE_FO'
}
apiInstance.exitPositions(opts, (error, data, response) => {
if (error) {
console.error(error.response.text);
} else {
console.log('API called successfully. Returned data: ' + JSON.stringify(data));
}
});
import com.upstox.ApiClient;
import com.upstox.ApiException;
import com.upstox.Configuration;
import com.upstox.api.CancelOrExitMultiOrderResponse;
import com.upstox.auth.OAuth;
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();
try {
CancelOrExitMultiOrderResponse result = apiInstance.exitPositions(null,"NSE_FO");
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrderApi#exitPositions= " + e.getResponseBody());
e.printStackTrace();
}
}
}
Exit all the open positions for a given tagโ
- Curl
- Python
- Node.js
- Java
- PHP
- Python SDK
- Node.js SDK
- Java SDK
curl --location --request POST 'https://api.upstox.com/v2/order/positions/exit?tag=xyz' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {your_access_token}' \
import requests
url = 'https://api.upstox.com/v2/order/positions/exit?tag=xyz'
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {your_access_token}',
}
data = {}
try:
# Send the POST request
response = requests.post(url, json=data, headers=headers)
# Print the response status code and body
print('Response Code:', response.status_code)
print('Response Body:', response.json())
except Exception as e:
# Handle exceptions
print('Error:', str(e))
const axios = require('axios');
const url = 'https://api.upstox.com/v2/order/positions/exit?tag=xyz';
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {your_access_token}',
};
const data = {};
axios.post(url, data, { headers })
.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error.message);
});
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/order/positions/exit?tag=xyz";
String token = "Bearer {your_access_token}";
// empty request body
String requestBody = "";
// Create the HttpClient
HttpClient httpClient = HttpClient.newHttpClient();
// Create the HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("Authorization", token)
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
try {
// Send the request and retrieve the response
HttpResponse<String> 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();
}
}
}
<?php
$url = 'https://api.upstox.com/v2/order/positions/exit?tag=xyz';
$headers = [
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer {your_access_token}',
];
$data = [];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Response: ' . $response;
}
curl_close($ch);
?>
import upstox_client
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))
param = {
'tag': "xyz"
}
try:
api_response = api_instance.exit_positions(**param)
print(api_response)
except ApiException as e:
print("Exception when calling OrderApi->exit all position: %s\n" % e.body)
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();
opts = {
'tag': 'xyz'
}
apiInstance.exitPositions(opts, (error, data, response) => {
if (error) {
console.error(error.response.text);
} else {
console.log('API called successfully. Returned data: ' + JSON.stringify(data));
}
});
import com.upstox.ApiClient;
import com.upstox.ApiException;
import com.upstox.Configuration;
import com.upstox.api.CancelOrExitMultiOrderResponse;
import com.upstox.auth.OAuth;
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();
try {
CancelOrExitMultiOrderResponse result = apiInstance.exitPositions("xyz",null);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrderApi#exitPositions= " + e.getResponseBody());
e.printStackTrace();
}
}
}