POST/us/charges/margin
Margin Calculator
API to calculate how much money you need for up to 20 US stocks orders, and whether your US wallet has enough balance to place them all. This is only a check: no orders are placed. All amounts are in USD.
- For a
BUYorder, the required margin is the trade value plus brokerage and GST. - For a
SELLorder, the required margin is0. - A
MARKETorder is valued at the last traded price.
US stocks are bought with full cash. The required margin is always the full trade value plus charges.
Request
curl --location --request POST 'https://api.upstox.com/v2/us/charges/margin' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {your_access_token}' \
--data '{
"instruments": [
{
"instrument_key": "US_EQ|AAPL",
"transaction_type": "BUY",
"order_type": "LIMIT",
"quantity": 1,
"price": 180
},
{
"instrument_key": "US_EQ|MSFT",
"transaction_type": "BUY",
"order_type": "MARKET",
"quantity": 0.5
}
]
}'
For samples in other languages, see the Sample Code section on this page.
Request Body
| Name | Required | Type | Description |
|---|---|---|---|
| instruments | Required | object[] | Orders to check, up to 20. Each entry has the same fields as the Estimate Order Charges request body. |
| instruments[].instrument_key | Required | string | US instrument key from the US instruments file, for example US_EQ|AAPL. |
| instruments[].transaction_type | Required | string | Possible values: BUY, SELL. |
| instruments[].order_type | Required | string | Possible values: MARKET, LIMIT. |
| instruments[].quantity | Required | number | Number of shares, up to 9 decimal places. Fractions are allowed only for stocks with fractionable: true. Maximum 999999. |
| instruments[].price | Optional | number | Limit price in USD. Required for a LIMIT order. Optional for a MARKET order, which is valued at the last traded price; price is used only when the last traded price is unavailable. Up to 2 decimal places at or above $1, and up to 4 below $1. |
Responses
- 200
- 4XX
Response Body
{
"status": "success",
"data": {
"margins": [
{
"instrument_key": "US_EQ|AAPL",
"transaction_type": "BUY",
"trade_value": 180,
"brokerage": 0.45,
"gst": 0.08,
"required_margin": 180.53
},
{
"instrument_key": "US_EQ|MSFT",
"transaction_type": "BUY",
"trade_value": 210.5,
"brokerage": 0.53,
"gst": 0.1,
"required_margin": 211.13
}
],
"required_margin": 391.66,
"available_to_invest": 909.45,
"shortfall": 0,
"sufficient": true
}
}
| Name | Type | Description |
|---|---|---|
| status | string | Outcome of the request. Typically success. |
| data | object | Required margin for the orders and whether the wallet covers them. |
| data.margins | object[] | One entry per order, in request order. |
| data.margins[].instrument_key | string | US instrument key of the order. |
| data.margins[].transaction_type | string | Possible values: BUY, SELL. |
| data.margins[].trade_value | number | Quantity × limit price, or quantity × last traded price for a MARKET order. |
| data.margins[].brokerage | number | Upstox brokerage. |
| data.margins[].gst | number | GST on brokerage. |
| data.margins[].required_margin | number | For a BUY: trade value + brokerage + GST. For a SELL: 0. |
| data.required_margin | number | Sum of the required margin across all orders. |
| data.available_to_invest | number | Buying power in the US wallet. Same as available_to_trade in the Get Funds response. |
| data.shortfall | number | required_margin minus available_to_invest. Never below 0. |
| data.sufficient | boolean | true when available_to_invest covers required_margin. |
Error codes
| Error code | Description |
|---|---|
| UDAPI1315 | Provide at least one order - The instruments array is empty. |
| UDAPI1102 | The instrument limit has been exceeded - A margin request accepts up to 20 orders. |
| UDAPI1026 | Instrument key is required - Provide instrument_key. |
| UDAPI1009 | TransactionType is required - Provide transaction_type. |
| UDAPI1057 | The 'transaction_type' is invalid - Only BUY and SELL are accepted. |
| UDAPI1004 | Valid order type is required - Provide order_type. |
| UDAPI1056 | The 'order_type' is invalid - Only MARKET and LIMIT are accepted. |
| UDAPI1313 | Quantity is required. |
| UDAPI1300 | Invalid US instrument - The instrument_key is not in the US instruments file. |
| UDAPI1301 | This US stock is not tradable - The stock is listed but not currently tradable. |
| UDAPI1303 | Quantity must be greater than 0 with at most 9 decimal places. |
| UDAPI1304 | Fractional quantity is not allowed for this stock - The stock has fractionable: false. Send a whole-share quantity. |
| UDAPI1311 | Order size cannot exceed 999,999 - Applies to both quantity and amount. |
| UDAPI1307 | Price must be greater than 0 for a limit order. |
| UDAPI1314 | Price must be greater than 0. |
| UDAPI1309 | Price allows 2 decimal places at or above $1 and 4 below $1. |
| UDAPI1310 | Order value must be at least $1. |
| UDAPI1316 | US stocks is not activated for this account - Returned with HTTP 403. |
| UDAPI1317 | US stocks order service is unavailable. Please try again later. - Returned with HTTP 423. |
| UDAPI1318 | US stocks trading is in its daily maintenance window. Please try again later. - Returned with HTTP 423. |
| UDAPI100500 | US order was rejected - The US broker rejected the request. The error message carries the broker's reason. |
| UDAPI1320 | US stocks funds service is unavailable. Please try again later. - Returned with HTTP 423. |
| UDAPI1321 | Last traded price is unavailable for this US stock. Send a price or try again later. - Returned with HTTP 423. |
Sample Code
Calculate margin for a basket of orders
- Python
- Node.js
- Java
- PHP
- Python SDK
- Node.js SDK
- Java SDK
- PHP SDK
- .NET SDK
import requests
url = 'https://api.upstox.com/v2/us/charges/margin'
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {your_access_token}',
}
data = {
'instruments': [
{
'instrument_key': 'US_EQ|AAPL',
'transaction_type': 'BUY',
'order_type': 'LIMIT',
'quantity': 1,
'price': 180
},
{
'instrument_key': 'US_EQ|MSFT',
'transaction_type': 'BUY',
'order_type': 'MARKET',
'quantity': 0.5
}
]
}
response = requests.post(url, json=data, headers=headers)
print(response.status_code)
print(response.json())
const axios = require('axios');
const url = 'https://api.upstox.com/v2/us/charges/margin';
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer {your_access_token}',
};
const data = {
"instruments": [
{
"instrument_key": "US_EQ|AAPL",
"transaction_type": "BUY",
"order_type": "LIMIT",
"quantity": 1,
"price": 180
},
{
"instrument_key": "US_EQ|MSFT",
"transaction_type": "BUY",
"order_type": "MARKET",
"quantity": 0.5
}
]
};
axios.post(url, data, { headers })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error.response ? error.response.data : 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) throws Exception {
String body = """
{
"instruments": [
{
"instrument_key": "US_EQ|AAPL",
"transaction_type": "BUY",
"order_type": "LIMIT",
"quantity": 1,
"price": 180
},
{
"instrument_key": "US_EQ|MSFT",
"transaction_type": "BUY",
"order_type": "MARKET",
"quantity": 0.5
}
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.upstox.com/v2/us/charges/margin"))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("Authorization", "Bearer {your_access_token}")
.method("POST", HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}
<?php
$url = 'https://api.upstox.com/v2/us/charges/margin';
$headers = [
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer {your_access_token}',
];
$data = [
'instruments' => [
[
'instrument_key' => 'US_EQ|AAPL',
'transaction_type' => 'BUY',
'order_type' => 'LIMIT',
'quantity' => 1,
'price' => 180
],
[
'instrument_key' => 'US_EQ|MSFT',
'transaction_type' => 'BUY',
'order_type' => 'MARKET',
'quantity' => 0.5
]
]
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
echo $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.UsStocksChargesApi(upstox_client.ApiClient(configuration))
body = upstox_client.UsMarginRequest(instruments=[
upstox_client.UsOrderEstimateRequest(
instrument_key='US_EQ|AAPL',
transaction_type='BUY',
order_type='LIMIT',
quantity=1,
price=180.0
),
upstox_client.UsOrderEstimateRequest(
instrument_key='US_EQ|MSFT',
transaction_type='BUY',
order_type='MARKET',
quantity=0.5
),
])
try:
api_response = api_instance.calculate_us_margin(body)
print(api_response)
except ApiException as e:
print("Exception when calling UsStocksChargesApi->calculate_us_margin: %s\n" % e)
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.USStocksChargesApi();
let order1 = new UpstoxClient.UsOrderEstimateRequest(1, "US_EQ|AAPL", "BUY", "LIMIT");
order1.price = 180.0;
let order2 = new UpstoxClient.UsOrderEstimateRequest(0.5, "US_EQ|MSFT", "BUY", "MARKET");
let body = new UpstoxClient.UsMarginRequest([order1, order2]);
apiInstance.calculateUsMargin(body, (error, data, response) => {
if (error) {
console.error(error);
} 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.UsMarginRequest;
import com.upstox.api.UsMarginResponse;
import com.upstox.api.UsOrderEstimateRequest;
import com.upstox.auth.OAuth;
import io.swagger.client.api.UsStocksChargesApi;
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2");
OAUTH2.setAccessToken("{your_access_token}");
UsStocksChargesApi apiInstance = new UsStocksChargesApi();
UsOrderEstimateRequest order1 = new UsOrderEstimateRequest();
order1.setInstrumentKey("US_EQ|AAPL");
order1.setQuantity(new BigDecimal("1"));
order1.setPrice(new BigDecimal("180.0"));
order1.setOrderType(UsOrderEstimateRequest.OrderTypeEnum.LIMIT);
order1.setTransactionType(UsOrderEstimateRequest.TransactionTypeEnum.BUY);
UsOrderEstimateRequest order2 = new UsOrderEstimateRequest();
order2.setInstrumentKey("US_EQ|MSFT");
order2.setQuantity(new BigDecimal("0.5"));
order2.setOrderType(UsOrderEstimateRequest.OrderTypeEnum.MARKET);
order2.setTransactionType(UsOrderEstimateRequest.TransactionTypeEnum.BUY);
UsMarginRequest body = new UsMarginRequest();
body.addInstrumentsItem(order1);
body.addInstrumentsItem(order2);
try {
UsMarginResponse result = apiInstance.calculateUsMargin(body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsStocksChargesApi#calculateUsMargin");
e.printStackTrace();
}
}
}
<?php
$config = (new Upstox\Client\Configuration())
->setAccessToken('{your_access_token}');
$apiInstance = new Upstox\Client\Api\USStocksChargesApi(
new GuzzleHttp\Client(),
$config
);
$order1 = new Upstox\Client\Model\UsOrderEstimateRequest();
$order1->setInstrumentKey('US_EQ|AAPL');
$order1->setQuantity(1);
$order1->setPrice(180.0);
$order1->setTransactionType('BUY');
$order1->setOrderType('LIMIT');
$order2 = new Upstox\Client\Model\UsOrderEstimateRequest();
$order2->setInstrumentKey('US_EQ|MSFT');
$order2->setQuantity(0.5);
$order2->setTransactionType('BUY');
$order2->setOrderType('MARKET');
$body = new Upstox\Client\Model\UsMarginRequest();
$body->setInstruments([$order1, $order2]);
try {
$result = $apiInstance->calculateUsMargin($body);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling USStocksChargesApi->calculateUsMargin: ' . $e->getMessage();
}
using UpstoxClient.Api;
using UpstoxClient.Client;
using UpstoxClient.Extensions;
using UpstoxClient.Model;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
var host = Host.CreateDefaultBuilder()
.ConfigureApi((context, services, options) =>
{
options.AddTokens(new OAuthToken("{your_access_token}"));
}).Build();
await host.StartAsync();
var apiInstance = host.Services.GetRequiredService<IUSStocksChargesApi>();
try
{
var instruments = new List<UsOrderEstimateRequest>
{
new UsOrderEstimateRequest(
quantity: 1m,
price: 180.0m,
instrumentKey: "US_EQ|AAPL",
transactionType: UsOrderEstimateRequest.TransactionTypeEnum.BUY,
orderType: UsOrderEstimateRequest.OrderTypeEnum.LIMIT),
new UsOrderEstimateRequest(
quantity: 0.5m,
instrumentKey: "US_EQ|MSFT",
transactionType: UsOrderEstimateRequest.TransactionTypeEnum.BUY,
orderType: UsOrderEstimateRequest.OrderTypeEnum.MARKET)
};
var response = await apiInstance.CalculateUsMarginAsync(new UsMarginRequest(instruments));
Console.WriteLine(response.RawContent);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
await host.StopAsync();