Any API Call in Python to find Margin Required?

Hi Fyers team

How do we find the span margin required to take a position using python? The docs show an example using curl. Is there any api call available from python to get the span margin required?

Thank you

Hi @ramksree-q9d

There is no directly API call to find the margin but we are providing a Rest-API for it
Follow for more : https://myapi.fyers.in/docs#tag/Margin-Calculator/paths/~1MarginCalculator/post

You can hit this request in Python and can find the required margin.
Hope it will help thanks

is python code available? only curl is given in docs.

Only CURL is for span margin.

@abhishek.m4daofcr
You can use Requests module in Python to integrate REST API calls with SDK.
For margin required, there is no direct method in Fyers Python SDK.

Thanks @nsuyash11-m18 for explaining.

Hi Fyers Team,
I am running following code of python and Getting Error.

headers={“Content-Type”: “application/json”, “Authorization”:“UC0KMO****-102:eyJ0eX*****”}

payload=json.dumps({

       "symbol": "NSE:BANKNIFTY2420745000CE",

       "qty": 15,

       "side": -1,

       "type": 2,

       "productType": "CNC",

       "limitPrice": 0.0,

       "stopLoss": 0.0

     })

response = requests.post(“https://api.fyers.in/api/v2/span_margin”, headers=headers, data=payload)

Hey @CkOdBHURzB

The product type has to be ‘MARGIN’ for any FNO contracts

Hi Abhishek & Fyers Team
Thanks but
Still the same error, I am getting.

Hi @CkOdBHURzB,
We need to enclose the input as an array of objects with parameter named “data”.
So, your input payload for the POST request should be as follows -

payload = json.dumps({
    "data": [
        {
            "symbol": "NSE:BANKNIFTY2420745000CE",
            "qty": 15,
            "side": -1,
            "type": 2,
            "productType": "MARGIN",
            "limitPrice": 0.0,
            "stopLoss": 0.0,
        }
    ]
})

This is working fine at my end.

Thank you @nsuyash11-m18
It worked.
Thanks a lot​:+1:

Glad to know that it worked. Just to add, this input structure is designed in array format so that we can add multiple FnO legs/spreads to calculate effective SPAN Margin required.

import requests

from fy_auto_login_v3 import fyers_obj as fyers

Set the API endpoint URL

url = ‘https://api.fyers.in/api/v2/span_margin’

Set the authorization header and content type

headers = {

'Authorization': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGkuZnllcnMuaW4iLCJpYXQiOjE3MTQzNjQwMDcsImV4cCI6MTcxNDQzNzAyNywibmJmIjoxNzE0MzY0MDA3LCJhdWQiOlsieDowIiwieDoxIiwieDoyIiwiZDoxIiwiZDoyIiwieDoxIiwieDowIl0sInN1YiI6ImFjY2Vzc190b2tlbiIsImF0X2hhc2giOiJnQUFBQUFCbUx4NW5PUlczZGVVLUx3R3ZweUgzVEZPNGZ0Wi1HQ19UbllFTE5OeHF4TER2aHBUdDlGY3RaX3hiYUJaZ05mekJsNU5yUWlQdDdhczNtd3FqbWVNNGVzRm1YSzE2UmpURjRWWWhld1VUaHR1R0NDTT0iLCJkaXNwbGF5X25hbWUiOiJQUkFTSEFOVCBKQUlOIiwib21zIjoiSzEiLCJoc21fa2V5IjoiNDE4ZGFjZDIwODM2ZGJlZGJjYjBkZmVlMjJiZjg1OWRmNDA3MjUxOWU0MWY1ZTg3ZDZmNzJjOTYiLCJmeV9pZCI6IkRQMDE1NzgiLCJhcHBUeXBlIjoxMDAsInBvYV9mbGFnIjoiWSJ9.5LLsy208fH1IE8Rc2d-KR5X4tS0WjC-_HtHj0cr8cps',  # Replace with your actual token

'Content-Type': 'application/json'

}

The data to be sent in the POST request (ensure proper formatting)

data = {

"data": [

    {

        "symbol": "NSE:HDFC-EQ",

        "qty": 50,

        "side": 1,

        "type": 2,

        "productType": "INTRADAY",

        "limitPrice": 0.0,

        "stopLoss": 0.0

    },

    {

        "symbol": "NSE:SBIN-EQ",

        "qty": 50,

        "side": -1,

        "type": 2,

        "productType": "INTRADAY",

        "limitPrice": 0.0,

        "stopLoss": 0.0

    }

]

}

Send the POST request

response = requests.post(url, headers=headers, json=data)

Check the response status code

if response.status_code == 200:

print("Request was successful")

else:

print("Failed to send request. Status code:", response.status_code)

Print the response content for verification

print(response.json())

I’ve created a request script but its not working…
getting below error:

Failed to send request. Status code: 400
{‘s’: ‘error’, ‘code’: -209, ‘message’: ‘Please provide the validation parameter’}

I dont think fyers is ever going to resolve this… they are such a bad company to do buisness.. !!

Please pass the APPID-100: Then add the access token to it

Error: 400 - {“s”: “error”, “code”: -50, “message”: “Please provide valid symbols”

        call = "BUY"

        lot_size = 1

        user = self.stand_in_angel_queue()

        #url = "[https://api.fyers.in/api/v2/marketdata/margin_calculator](https://api.fyers.in/api/v2/marketdata/margin_calculator)"

        url = "[https://api.fyers.in/api/v2/span_margin](https://api.fyers.in/api/v2/span_margin)"

        # Prepare the request headers (with access token)

        headers = {

            "Authorization": f"WHDWPWMYF5-100:{global_[variable.smart](http://variable.smart)_api_object_list[user]["accessToken"]}",

            "Content-Type": "application/json"

        }

        data = {

            "data": [

                {

                    "symbol": "NSE:HDFC-EQ",

                    "qty": 50,

                    "side": 1,

                    "type": 2,

                    "productType": "INTRADAY",

                    "limitPrice": 0.0,

                    "stopLoss": 0.0

                }

            ]

        }

        print(f"url {url}")

        print(f"headers {headers}")

        print(f"margin_request {data}")

        #response = [requests.post](http://requests.post)(url, headers=headers, data=json.dumps(margin_request))

        response = [requests.post](http://requests.post)(url, headers=headers, json=data)

url https://api.fyers.in/api/v2/span_margin

headers {‘Authorization’: ‘WHDWPWMYF5-100:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGkuZnllcnMuaW4iLCJpYXQiOjE3MjgxMTg3MjUsImV4cCI6MTcyODE3NDY0NSwibmJmIjoxNzI4MTE4NzI1LCJhdWQiOlsieDowIiwieDoxIiwieDoyIiwiZDoxIiwiZDoyIiwieDoxIiwieDowIl0sInN1YiI6ImFjY2Vzc190b2tlbiIsImF0X2hhc2giOiJnQUFBQUFCbkFQX0ZFTE1CbWRHeVMzcWJHVzNETWd6RHh0VnlaWTdLQktEYS1VdXR0blByTUk0cDdzanZZYWN0Mkk2eXJDUFIxaW5SV0NoSVNMRUUzalZISnpzVE1pWE4xcm5lcEt4QVpyNWhFdlhVdy1EdUdZUT0iLCJkaXNwbGF5X25hbWUiOiJLQU5IVSBDSEFSQU5BIE1BSEFSQU5BIiwib21zIjoiSzEiLCJoc21fa2V5IjoiMDc3ZWFkOGYyOTc3NzRkZjI0OWE2Njc5MTI0MzEzYTZjNDIwMzEyMjJjMzg1NjUxOGRhMmExYmIiLCJmeV9pZCI6IllLMTE5OTgiLCJhcHBUeXBlIjoxMDAsInBvYV9mbGFnIjoiTiJ9.UQtl6tjvS_yBL-A5ErC8GU4MQ9OXjRIFD26cbBGsMZM’, ‘Content-Type’: ‘application/json’}

margin_request {‘data’: [{‘symbol’: ‘NSE:HDFC-EQ’, ‘qty’: 50, ‘side’: 1, ‘type’: 2, ‘productType’: ‘INTRADAY’, ‘limitPrice’: 0.0, ‘stopLoss’: 0.0}]}

Error: 400 - {“s”: “error”, “code”: -50, “message”: “Please provide valid symbols”}

can some one help me

For margin calculation, I use the data from the below link.

https://public.fyers.in/website/margin-calculator/equity/eq_website_upload.json

Just multiply the margin for the stock with the with available fund and do your calculations.
Works for me.

My program downloads this data every day so that I have the latest data.

output = requests.get(cfg.MARGINS_URL).json()
df = pd.DataFrame.from_dict(output["data"])
df.rename(columns={"symbol": "Symbol","exchange": "Exchange","intraday_multiplier": "Multiplier",},inplace=True, )
df.Symbol = df.Symbol.str.strip()
df.to_csv(cfg.MARGINS_FILE, index=False)

I want to use margin for intraday trading but i m not able to. can anyone help me?

Hi @114353234872920218084, could you let me know which scrip you’re trying to place the intraday order in? You’ll get margin for intraday trades on most segments, but I’ll need to check this specific case for you.

**Hi **@shruthi_shetty ,

I just realized that the margin option wasn’t enabled in my account, which is why I couldn’t trade using margin—even after comparing it with the JSON file.

Thank you so much for your support!