Get Margin¶
get_margin() estimates Trading API V3 funds and margin requirements using NubraTrader(nubra).
Use this page to estimate funds before placing:
- one single-instrument order
- multiple independent single-instrument orders
- one strategy order
The orders payload uses the same Trading API V3 order fields as create_order(), plus top-level requestType.
LLM guidance
Use this page when the goal is to estimate Trading API V3 funds or margin before placement. Generate the documented field names exactly as shown, including requestType, refId, deliveryType, priceType, validityType, entryPrice, isMultiLeg, unitQty, and stratTags.
Basic Usage¶
Create the Trading API V3 order payload you want to estimate, replace the payload dictionary when needed, and pass it to trader.get_margin(payload).
from nubra_python_sdk.refdata.instruments import InstrumentData
from nubra_python_sdk.marketdata.market_data import MarketData
from nubra_python_sdk.start_sdk import InitNubraSdk, NubraEnv
from nubra_python_sdk.trading.trading_data import NubraTrader
from nubra_python_sdk.trading.trading_enum import ExchangeEnum, TradingAPIVersion
nubra = InitNubraSdk(NubraEnv.UAT, env_creds=True, trading_version=TradingAPIVersion.V3)
instruments = InstrumentData(nubra)
market_data = MarketData(nubra)
trader = NubraTrader(nubra)
hdfc_futures_df = instruments.get_instruments_dataframe(exchange="NSE")
hdfc_futures = hdfc_futures_df[
(hdfc_futures_df["asset"] == "HDFCBANK")
& (hdfc_futures_df["derivative_type"] == "FUT")
].sort_values("expiry")
if hdfc_futures.empty:
raise ValueError("No active HDFCBANK futures contract found")
hdfc_fut = hdfc_futures.iloc[0]
hdfc_fut_ref_id = int(hdfc_fut["ref_id"])
hdfc_fut_lot_size = int(hdfc_fut["lot_size"])
hdfc_fut_ltp = market_data.quote(ref_id=hdfc_fut_ref_id, levels=1).orderBook.last_traded_price
payload = {
"requestType": "NEW",
"orders": [
{
"refId": hdfc_fut_ref_id,
"qty": hdfc_fut_lot_size,
"side": "BUY",
"deliveryType": "IDAY",
"priceType": "LIMIT",
"validityType": "DAY",
"isMultiLeg": False,
"executionMode": "ENTRY",
"entryPrice": hdfc_fut_ltp,
"stratTags": ["python-sdk-v3", "hdfcbank-fut-margin"],
}
]
}
funds = trader.get_margin(payload)
print(funds.totalFundsRequired)
print(funds.marginInfo.totalMargin)
Example Margin Patterns¶
These examples estimate Trading API V3 margin for payloads before sending the same shape to create_order().
from nubra_python_sdk.refdata.instruments import InstrumentData
from nubra_python_sdk.marketdata.market_data import MarketData
from nubra_python_sdk.start_sdk import InitNubraSdk, NubraEnv
from nubra_python_sdk.trading.trading_data import NubraTrader
from nubra_python_sdk.trading.trading_enum import ExchangeEnum, TradingAPIVersion
nubra = InitNubraSdk(NubraEnv.UAT, env_creds=True, trading_version=TradingAPIVersion.V3)
instruments = InstrumentData(nubra)
market_data = MarketData(nubra)
trader = NubraTrader(nubra)
hdfc_futures_df = instruments.get_instruments_dataframe(exchange="NSE")
hdfc_futures = hdfc_futures_df[
(hdfc_futures_df["asset"] == "HDFCBANK")
& (hdfc_futures_df["derivative_type"] == "FUT")
].sort_values("expiry")
if hdfc_futures.empty:
raise ValueError("No active HDFCBANK futures contract found")
hdfc_fut = hdfc_futures.iloc[0]
hdfc_fut_ref_id = int(hdfc_fut["ref_id"])
hdfc_fut_lot_size = int(hdfc_fut["lot_size"])
hdfc_fut_ltp = market_data.quote(ref_id=hdfc_fut_ref_id, levels=1).orderBook.last_traded_price
funds = trader.get_margin({
"requestType": "NEW",
"orders": [
{
"refId": hdfc_fut_ref_id,
"qty": hdfc_fut_lot_size,
"side": "BUY",
"deliveryType": "IDAY",
"priceType": "LIMIT",
"validityType": "DAY",
"isMultiLeg": False,
"executionMode": "ENTRY",
"entryPrice": hdfc_fut_ltp,
"stratTags": ["python-sdk-v3", "hdfcbank-fut-margin"],
}
]
})
print(funds.totalFundsRequired)
print(funds.marginInfo.totalMargin)
Use this pattern to estimate margin for a single HDFCBANK futures order.
from nubra_python_sdk.refdata.instruments import InstrumentData
from nubra_python_sdk.marketdata.market_data import MarketData
from nubra_python_sdk.start_sdk import InitNubraSdk, NubraEnv
from nubra_python_sdk.trading.trading_data import NubraTrader
from nubra_python_sdk.trading.trading_enum import TradingAPIVersion
nubra = InitNubraSdk(NubraEnv.UAT, env_creds=True, trading_version=TradingAPIVersion.V3)
instruments = InstrumentData(nubra)
market_data = MarketData(nubra)
trader = NubraTrader(nubra)
nifty_options_df = instruments.get_instruments_dataframe(exchange="NSE")
nifty_options = nifty_options_df[
(nifty_options_df["asset"] == "NIFTY")
& (nifty_options_df["derivative_type"] == "OPT")
].copy()
if nifty_options.empty:
raise ValueError("No active NIFTY option contracts found")
nearest_expiry = nifty_options["expiry"].sort_values().iloc[0]
nearest_expiry_options = nifty_options[nifty_options["expiry"] == nearest_expiry].copy()
ce_strikes = set(nearest_expiry_options[nearest_expiry_options["option_type"] == "CE"]["strike_price"])
pe_strikes = set(nearest_expiry_options[nearest_expiry_options["option_type"] == "PE"]["strike_price"])
common_strikes = sorted(ce_strikes & pe_strikes)
if not common_strikes:
raise ValueError(f"No matching CE/PE strikes found for NIFTY expiry {nearest_expiry}")
strategy_strike = int(common_strikes[len(common_strikes) // 2] // 100)
def get_option_contract(strike, option_type):
matches = nearest_expiry_options[
(nearest_expiry_options["strike_price"] == strike * 100)
& (nearest_expiry_options["option_type"] == option_type)
]
if matches.empty:
raise ValueError(f"No contract found for NIFTY {strike} {option_type} on expiry {nearest_expiry}")
contract = matches.iloc[0]
ref_id = int(contract["ref_id"])
quote = market_data.quote(ref_id=ref_id, levels=1)
return ref_id, quote.orderBook.last_traded_price
call_ref_id, call_ltp = get_option_contract(strategy_strike, "CE")
put_ref_id, put_ltp = get_option_contract(strategy_strike, "PE")
strategy_base_qty = 65
funds = trader.get_margin({
"requestType": "NEW",
"orders": [
{
"isMultiLeg": True,
"qty": strategy_base_qty,
"side": "BUY",
"deliveryType": "CNC",
"priceType": "LIMIT",
"validityType": "DAY",
"executionMode": "ENTRY",
"entryPrice": call_ltp + put_ltp,
"legs": [
{"refId": call_ref_id, "unitQty": 1},
{"refId": put_ref_id, "unitQty": 1}
],
"stratTags": ["python-sdk-v3", "long-straddle-margin"],
}
]
})
print(funds.totalFundsRequired)
print(funds.marginInfo.totalMargin)
Use this pattern to estimate funds for one strategy order. The example resolves the nearest active NIFTY expiry and a valid shared CE/PE strike automatically. The top-level qty is the common executable base quantity for the strategy, and each leg uses signed unitQty as its lot multiplier.
from nubra_python_sdk.refdata.instruments import InstrumentData
from nubra_python_sdk.marketdata.market_data import MarketData
from nubra_python_sdk.start_sdk import InitNubraSdk, NubraEnv
from nubra_python_sdk.trading.trading_data import NubraTrader
from nubra_python_sdk.trading.trading_enum import TradingAPIVersion
nubra = InitNubraSdk(NubraEnv.UAT, env_creds=True, trading_version=TradingAPIVersion.V3)
instruments = InstrumentData(nubra)
market_data = MarketData(nubra)
trader = NubraTrader(nubra)
nifty_options_df = instruments.get_instruments_dataframe(exchange="NSE")
nifty_options = nifty_options_df[
(nifty_options_df["asset"] == "NIFTY")
& (nifty_options_df["derivative_type"] == "OPT")
].copy()
if nifty_options.empty:
raise ValueError("No active NIFTY option contracts found")
nearest_expiry = nifty_options["expiry"].sort_values().iloc[0]
nearest_expiry_options = nifty_options[nifty_options["expiry"] == nearest_expiry].copy()
ce_strikes = sorted(nearest_expiry_options[nearest_expiry_options["option_type"] == "CE"]["strike_price"].unique())
if len(ce_strikes) < 2:
raise ValueError(f"Not enough CE strikes found for NIFTY expiry {nearest_expiry}")
spread_start = max(0, (len(ce_strikes) // 2) - 1)
short_strike = int(ce_strikes[spread_start] // 100)
long_strike = int(ce_strikes[spread_start + 1] // 100)
def get_option_contract(strike, option_type):
matches = nearest_expiry_options[
(nearest_expiry_options["strike_price"] == strike * 100)
& (nearest_expiry_options["option_type"] == option_type)
]
if matches.empty:
raise ValueError(f"No contract found for NIFTY {strike} {option_type} on expiry {nearest_expiry}")
contract = matches.iloc[0]
ref_id = int(contract["ref_id"])
quote = market_data.quote(ref_id=ref_id, levels=1)
return ref_id, quote.orderBook.last_traded_price
short_call_ref_id, short_call_ltp = get_option_contract(short_strike, "CE")
long_call_ref_id, long_call_ltp = get_option_contract(long_strike, "CE")
strategy_base_qty = 65
funds = trader.get_margin({
"requestType": "NEW",
"orders": [
{
"isMultiLeg": True,
"qty": strategy_base_qty,
"side": "BUY",
"deliveryType": "CNC",
"priceType": "LIMIT",
"validityType": "DAY",
"executionMode": "ENTRY",
"entryPrice": -short_call_ltp + long_call_ltp,
"legs": [
{"refId": short_call_ref_id, "unitQty": -1},
{"refId": long_call_ref_id, "unitQty": 1}
],
"stratTags": ["python-sdk-v3", "bear-call-spread-margin"],
}
]
})
print(funds.totalFundsRequired)
print(funds.marginInfo.totalMargin)
Use this pattern to estimate margin for one bear call spread strategy unit. The example automatically picks two adjacent CE strikes from the nearest active NIFTY expiry.
Request Contract¶
| Field | Type | Required | Meaning |
|---|---|---|---|
requestType |
str |
yes | request label sent to Trading API V3 funds-required API. Use NEW when estimating funds for a new order before placement. |
orders |
list[IntentOrderStruct] |
yes | order payloads to estimate |
orders[].refId |
int |
conditional | single-leg instrument reference ID |
orders[].qty |
int |
yes | single-order quantity or common executable strategy quantity |
orders[].side |
str |
conditional | BUY or SELL; required for single-leg orders and recommended for strategy orders |
orders[].deliveryType |
str |
yes | IDAY or CNC |
orders[].priceType |
str |
no | LIMIT or MARKET |
orders[].validityType |
str |
no | DAY, IOC, or GTE |
orders[].executionMode |
str |
no | ENTRY, EXIT, or ENTRY_AND_EXIT |
orders[].entryPrice |
int |
conditional | single-order price or strategy net price |
orders[].entryConfig |
dict |
no | entry trigger or timed-entry conditions |
orders[].exitConfig |
dict |
no | stop-loss, target, trailing, or timed exit conditions |
orders[].icebergInfo |
dict |
no | iceberg fields |
orders[].isMultiLeg |
bool |
yes | False for single-leg estimates; True for strategy order estimates |
orders[].legs |
list[dict] |
conditional | required when isMultiLeg=True |
orders[].legs[].refId |
int |
yes for leg | leg instrument reference ID |
orders[].legs[].unitQty |
int |
yes for leg | signed leg lot multiplier |
Condition Fields¶
| Field | Meaning |
|---|---|
entryConfig.entryTime |
timed entry |
entryConfig.triggers.ltp.above.value |
trigger when live price moves above the threshold |
entryConfig.triggers.ltp.below.value |
trigger when live price moves below the threshold |
entryConfig.triggers.ltp.atOrAbove.value |
trigger when live price reaches or exceeds the threshold |
entryConfig.triggers.ltp.atOrBelow.value |
trigger when live price reaches or falls below the threshold |
exitConfig.stoplossParams.stoplossTriggerPrice.value |
stop-loss trigger |
exitConfig.stoplossParams.stoplossLimitPrice.value |
stop-loss limit |
exitConfig.stoplossParams.stoplossTrailJump |
trailing-stop jump |
exitConfig.targetParams.targetProfitTriggerPrice.value |
target trigger |
exitConfig.targetParams.targetProfitLimitPrice.value |
target limit |
exitConfig.exitTime |
timed exit |
Response Contract¶
get_margin() returns FundsRequiredResp.
| Field | Type | Meaning |
|---|---|---|
code |
int |
funds-required result code |
marginInfo |
IntentMarginResp |
Trading API V3 margin information |
brokerageInfo |
IntentBrokerageResp |
brokerage and charges information |
totalFundsRequired |
int |
final funds required for the request |
willDefaultBePlacedAsAmo |
bool |
whether default placement would become AMO |
refIdAmoMap |
dict[str, bool] |
per-ref-id AMO indicator |
openOrders |
int |
open order count when returned |
icebergInfo |
IntentIcebergParams |
iceberg calculation info when returned |
marginInfo¶
| Field | Type | Meaning |
|---|---|---|
totalMargin |
int |
total margin requirement |
message |
str |
margin message |
maxAllowedQty |
int |
maximum allowed quantity |
cncSellAllowedQty |
int |
CNC sell quantity allowed |
cncSellAvailableQty |
int |
CNC sell quantity available |
edisDoneQty |
int |
EDIS completed quantity |
edisRemainingQty |
int |
EDIS remaining quantity |
brokerageInfo¶
| Field | Type | Meaning |
|---|---|---|
chargesFloat |
dict[str, float] |
individual charge components |
totalChargesFloat |
float |
total charges |
Important Rules¶
Important Rules
- Use the documented Trading API V3 payload fields for
get_margin(). - Set
requestType: "NEW"when estimating a new order before placing it. - Use
totalFundsRequiredas the top-level funds requirement and inspectmarginInfo.totalMarginfor the margin component. - Keep estimate payloads aligned with the order payloads you plan to submit with
create_order(). - Single-leg estimates require
refId,qty,side,deliveryType, andisMultiLeg: False. MARKETpayloads can be estimated too. Keep them aligned with placement by usingpriceType: "MARKET",validityType: "IOC", and noentryPrice.- Multi-leg estimates require
isMultiLeg: Trueand a non-emptylegslist. - For strategy order estimates, top-level
qtyis the common executable base quantity and each leg uses signedunitQtyas its lot multiplier. - Use environment-correct
refIdvalues when estimating margins. - Prices are typically passed in exchange-native integer units such as paise for NSE instruments.