### Example - Market Data Source: https://github.com/flattrade/pythonapi/blob/main/README.md This example demonstrates API usage for finding scrips and their properties. ```Python ## Example Symbol/Contract : Example_market.py This Example shows API usage for finding scrips and its properties ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/flattrade/pythonapi/blob/main/token_generator/setup.md Install all required Python packages for the project and the token generator module. This command reads the `requirements.txt` files to install the necessary libraries. ```bash pip install -r requirements.txt pip install -r ./token_generator/requirements.txt ``` -------------------------------- ### start_websocket Source: https://github.com/flattrade/pythonapi/blob/main/README.md Starts the websocket for real-time market data updates. Supports touchline and depth ticks, with acknowledgement and further change stages. ```APIDOC ## start_websocket() ### Description Starts the websocket, WebSocket feed has 2 types of ticks( t=touchline d=depth)and 2 stages (k=acknowledgement, f=further change in tick). ### Parameters #### Path Parameters - **subscribe_callback** (function) - False - callback for market updates - **order_update_callback** (function) - False - callback for order updates - **socket_open_callback** (function) - False - callback when socket is open (reconnection also) - **socket_close_callback** (function) - False - callback when socket is closed ``` -------------------------------- ### Search for Scrip by Partial Text Source: https://github.com/flattrade/pythonapi/blob/main/README.md This example demonstrates how to search for scrips using a partial text string. It returns a list of matching scrips with their exchange, token, and trading symbol. ```python api.searchscrip(exchange='NSE', searchtext='REL') ``` -------------------------------- ### WebSocket Source: https://context7.com/flattrade/pythonapi/llms.txt Starts a persistent WebSocket connection for real-time data feeds and order updates. ```APIDOC ## WebSocket — `start_websocket`, `subscribe`, `unsubscribe` ### Description Starts a persistent WebSocket connection that delivers real-time touchline (`t`) or depth (`d`) feed updates and order status updates via user-supplied callbacks. The first message per subscription is `tk` (full snapshot); subsequent messages are `tf` (incremental changes only). ### Methods - `start_websocket` - `subscribe` - `unsubscribe` ### Parameters for `start_websocket` - **order_update_callback** (function) - Callback function for order updates. - **subscribe_callback** (function) - Callback function for quote/feed updates. - **socket_open_callback** (function) - Callback function when the WebSocket connection is opened. ### Parameters for `subscribe` - **symbols** (list of strings) - List of symbols to subscribe to (e.g., 'NSE|11630'). - **feed_type** (string) - Type of feed: 't' for touchline, 'd' for depth. ### Parameters for `unsubscribe` - **symbols** (list of strings) - List of symbols to unsubscribe from. ### Request Example ```python from api_helper import NorenApiPy import time api = NorenApiPy() api.set_session(userid='FT12345', password='', usertoken='ey...token...') socket_opened = False SYMBOLDICT = {} def on_order_update(message): print(f"[ORDER] {message['status']} norenordno:{message.get('norenordno','')}") def on_quote_update(message): key = message['e'] + '|' + message['tk'] if key in SYMBOLDICT: SYMBOLDICT[key].update(message) else: SYMBOLDICT[key] = message snap = SYMBOLDICT[key] print(f"[{time.strftime('%H:%M:%S')}] {snap.get('ts','?'):20s} LTP:{snap.get('lp','N/A'):>10} Vol:{snap.get('v','N/A')}") def on_open(): global socket_opened socket_opened = True print("WebSocket connected") api.subscribe(['NSE|11630', 'NSE|22'], feed_type='t') api.start_websocket( order_update_callback=on_order_update, subscribe_callback=on_quote_update, socket_open_callback=on_open ) while not socket_opened: time.sleep(0.1) time.sleep(30) # stream for 30 seconds api.unsubscribe(['NSE|11630', 'NSE|22']) ``` ### Response Callbacks are triggered based on the type of update received (order, quote, or socket open). ``` -------------------------------- ### Get Live Quotes - `get_quotes` Source: https://context7.com/flattrade/pythonapi/llms.txt Fetches a full market depth snapshot for a single instrument, including LTP, OHLC, volume, and best bid/ask prices and quantities. ```python ret = api.get_quotes(exchange='NSE', token='22') if ret and ret.get('stat') == 'Ok': print(f"LTP: {ret['lp']} H: {ret['h']} L: {ret['l']} V: {ret['v']}") print(f"Best Bid: {ret['bp1']} x {ret['bq1']} Best Ask: {ret['sp1']} x {ret['sq1']}") # LTP: 2000.00 H: 2093.95 L: 1713.25 V: 0 # Best Bid: 2000.00 x 2 Best Ask: 0.00 x 0 ``` -------------------------------- ### Sample Success Output for Single Order History Source: https://github.com/flattrade/pythonapi/blob/main/README.md Example of a successful response when retrieving order history. This includes details about the order's status, trade information, and timestamps. ```json [ { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "avgprc": "800.00", "dscqty": "0", "prd": "M", "status": "COMPLETE", "rpt": "Fill", "fillshares": "180", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "dscqty": "0", "prd": "M", "status": "OPEN", "rpt": "New", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "dscqty": "0", "prd": "M", "status": "PENDING", "rpt": "PendingNew", "norentm": "19:59:32 13-12-2020", "remarks": "WC TEST Order" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "prd": "M", "status": "PENDING", "rpt": "NewAck", "norentm": "19:59:32 13-12-2020", "remarks": "WC TEST Order" } ] ``` -------------------------------- ### Sample Success Response - Holdings Source: https://github.com/flattrade/pythonapi/blob/main/README.md This is an example of a successful response when retrieving holdings. It includes details about exchange, symbol, and quantities. ```json [ { "stat":"Ok", "exch_tsym":[ { "exch":"NSE", "token":"13", "tsym":"ABB-EQ" } ], "holdqty":"2000000", "colqty":"200", "btstqty":"0", "btstcolqty":"0", "usedqty":"0", "upldprc" : "1800.00" }, { "stat":"Ok", "exch_tsym":[ { "exch":"NSE", "token":"22", "tsym":"ACC-EQ" } ], "holdqty":"2000000", "colqty":"200", "btstqty":"0", "btstcolqty":"0", "usedqty":"0", "upldprc" : "1400.00" } ] ``` -------------------------------- ### Real-time Quote Event Examples Source: https://github.com/flattrade/pythonapi/blob/main/README.md Illustrates the format of real-time quote events received from the API. 'tk' events provide all fields, while 'tf' events only include changed fields. ```text quote event: 03-12-2021 11:54:44{'t': 'tk', 'e': 'NSE', 'tk': '11630', 'ts': 'NTPC-EQ', 'pp': '2', 'ls': '1', 'ti': '0.05', 'lp': '118.55', 'h': '118.65', 'l': '118.10', 'ap': '118.39', 'v': '162220', 'bp1': '118.45', 'sp1': '118.50', 'bq1': '26', 'sq1': '6325'} quote event: 03-12-2021 11:54:45{'t': 'tf', 'e': 'NSE', 'tk': '11630', 'lp': '118.45', 'ap': '118.40', 'v': '166637', 'sp1': '118.55', 'bq1': '3135', 'sq1': '30'} quote event: 03-12-2021 11:54:46{'t': 'tf', 'e': 'NSE', 'tk': '11630', 'lp': '118.60'} ``` -------------------------------- ### Sample Failure Response - Holdings Source: https://github.com/flattrade/pythonapi/blob/main/README.md This is an example of a failure response when retrieving holdings. It indicates missing required input parameters. ```json { "stat":"Not_Ok", "emsg":"Invalid Input : Missing uid or actid or prd." } ``` -------------------------------- ### Get Positions - `get_positions` Source: https://context7.com/flattrade/pythonapi/llms.txt Retrieves intraday and carry-forward positions with unrealized MTM and realized PnL. MTM can be recalculated live. ```python ret = api.get_positions() mtm = pnl = 0.0 if ret: for pos in ret: mtm += float(pos.get('urmtom', 0)) pnl += float(pos.get('rpnl', 0)) print(f"{pos['tsym']:20s} netqty:{pos['netqty']:>6} " f"urmtom:{pos.get('urmtom','0'):>10} rpnl:{pos.get('rpnl','0'):>10}") day_m2m = mtm + pnl print(f"Daily MTM: {day_m2m:.2f}") # ACC-EQ netqty: 0 urmtom: 0.00 rpnl: 0.00 # Daily MTM: 0.00 ``` -------------------------------- ### Get Security Info - `get_security_info` Source: https://context7.com/flattrade/pythonapi/llms.txt Returns full static reference data for a contract, including company name, ISIN, lot size, tick size, margin rates, and freeze quantity. ```python ret = api.get_security_info(exchange='NSE', token='22') print(ret) # { # 'stat': 'Ok', 'exch': 'NSE', 'tsym': 'ACC-EQ', # 'cname': 'ACC LIMITED', 'isin': 'INE012A01025', # 'pp': '2', 'ls': '1', 'ti': '0.05', # 'varmrg': '40.00', 'token': '22', ... # } ``` -------------------------------- ### Get Limits Source: https://context7.com/flattrade/pythonapi/llms.txt Retrieves margin availability, cash balance, collateral, turnover, and detailed per-product margin utilization figures. ```APIDOC ## Get Limits — `get_limits` Retrieves margin availability, cash balance, collateral, turnover, and detailed per-product margin utilisation figures. ```python ret = api.get_limits() print(ret) # { # 'stat': 'Ok', # 'cash': '1500000000000000.00', # 'payin': '0.00', # 'marginused': '3945540.00', # 'urmtom': '30540.00', # 'grexpo': '3915000.00', # ... # } # Segment/product-specific limits ret_fo = api.get_limits(product_type='M', segment='FO', exchange='NFO') print(ret_fo) ``` ``` -------------------------------- ### Generate API Token with `token_generator/gettoken.py` Source: https://context7.com/flattrade/pythonapi/llms.txt This script handles the OAuth flow to obtain a session token. You need to fill in your API credentials, install dependencies, and run the script. Follow the printed URL to authenticate in your browser, and then copy the resulting token. ```bash # 1. Fill in your credentials in token_generator/gettoken.py: # api_key = "YOUR_API_KEY" # api_secret = "YOUR_SECRET_KEY" # 2. Install dependencies pip install -r requirements.txt pip install -r ./token_generator/requirements.txt # 3. Run the token generator python ./token_generator/gettoken.py # Output: # * * - * * - ... Click the link below to authenticate: # https://auth.flattrade.in/?app_key=YOUR_API_KEY # 4. Open the printed URL in a browser, log in and approve. # The page redirects to http://localhost:8080/?code=REQUEST_TOKEN # The Flask app exchanges the code for a session token and # displays it in the browser – copy it for use in set_session(). ``` -------------------------------- ### Get Limits - `get_limits` Source: https://context7.com/flattrade/pythonapi/llms.txt Retrieves margin availability, cash balance, collateral, turnover, and detailed per-product margin utilization figures. Supports segment/product-specific limits. ```python ret = api.get_limits() print(ret) # { # 'stat': 'Ok', # 'cash': '1500000000000000.00', # 'payin': '0.00', # 'marginused': '3945540.00', # 'urmtom': '30540.00', # 'grexpo': '3915000.00', # ... # } # Segment/product-specific limits ret_fo = api.get_limits(product_type='M', segment='FO', exchange='NFO') print(ret_fo) ``` -------------------------------- ### Activate Virtual Environment (Windows CMD) Source: https://github.com/flattrade/pythonapi/blob/main/token_generator/setup.md Activate the virtual environment on Windows using the Command Prompt (CMD). This command makes the virtual environment's Python interpreter and installed packages available in your current session. ```cmd myvenv\Scripts\activate ``` -------------------------------- ### Activate Virtual Environment (Windows PowerShell) Source: https://github.com/flattrade/pythonapi/blob/main/token_generator/setup.md Activate the virtual environment on Windows using PowerShell. This command enables the use of the virtual environment's isolated Python installation and dependencies. ```powershell myvenv\Scripts\Activate.ps1 ``` -------------------------------- ### Get Time Price Series Data Source: https://github.com/flattrade/pythonapi/blob/main/README.md Retrieves historical chart data for a given symbol. Specify the exchange, token, start time, and interval for the data. ```python lastBusDay = datetime.datetime.today() lastBusDay = lastBusDay.replace(hour=0, minute=0, second=0, microsecond=0) ret = api.get_time_price_series(exchange='NSE', token='22', starttime=lastBusDay.timestamp(), interval=5) ``` -------------------------------- ### Get Daily Price Series Data Source: https://github.com/flattrade/pythonapi/blob/main/README.md Fetches daily historical price data for a specified trading symbol. Requires exchange, trading symbol, start date, and end date. ```python ret =api.get_daily_price_series(exchange="NSE",tradingsymbol="PAYTM-EQ",startdate="457401600",enddate="480556800") ``` -------------------------------- ### Place Order Source: https://github.com/flattrade/pythonapi/blob/main/README.md Demonstrates how to place different types of orders: Limit, Market, StopLoss, Cover, and Bracket orders. ```APIDOC ## Place Limit Order ### Description Places a Limit order. ### Method `api.place_order` ### Parameters - `buy_or_sell` (string) - 'B' for Buy, 'S' for Sell - `product_type` (string) - 'C' for Cash (Intraday), 'D' for Delivery, 'B' for Bracket, 'H' for Cover - `exchange` (string) - Exchange name (e.g., 'NSE') - `tradingsymbol` (string) - Trading symbol of the instrument (e.g., 'INFY-EQ') - `quantity` (integer) - Number of units to trade - `discloseqty` (integer) - Quantity to disclose (0 for none) - `price_type` (string) - 'LMT' for Limit order - `price` (float) - The limit price for the order - `trigger_price` (float or None) - Trigger price for stop-loss orders - `retention` (string) - Order retention period (e.g., 'DAY') - `remarks` (string) - Optional remarks for the order - `bookloss_price` (float, optional) - For Cover and Bracket orders, the price at which to book loss - `bookprofit_price` (float, optional) - For Bracket orders, the price at which to book profit ### Request Example ```python api.place_order(buy_or_sell='B', product_type='C', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0, price_type='LMT', price=1500, trigger_price=None, retention='DAY', remarks='my_order_001') ``` ## Place Market Order ### Description Places a Market order. ### Method `api.place_order` ### Parameters - `buy_or_sell` (string) - 'B' for Buy, 'S' for Sell - `product_type` (string) - 'C' for Cash (Intraday), 'D' for Delivery, 'B' for Bracket, 'H' for Cover - `exchange` (string) - Exchange name (e.g., 'NSE') - `tradingsymbol` (string) - Trading symbol of the instrument (e.g., 'INFY-EQ') - `quantity` (integer) - Number of units to trade - `discloseqty` (integer) - Quantity to disclose (0 for none) - `price_type` (string) - 'MKT' for Market order - `price` (float) - Set to 0 for Market orders - `trigger_price` (float or None) - Trigger price for stop-loss orders - `retention` (string) - Order retention period (e.g., 'DAY') - `remarks` (string) - Optional remarks for the order ### Request Example ```python api.place_order(buy_or_sell='B', product_type='C', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0, price_type='MKT', price=0, trigger_price=None, retention='DAY', remarks='my_order_001') ``` ## Place StopLoss Order ### Description Places a StopLoss order. ### Method `api.place_order` ### Parameters - `buy_or_sell` (string) - 'B' for Buy, 'S' for Sell - `product_type` (string) - 'C' for Cash (Intraday), 'D' for Delivery, 'B' for Bracket, 'H' for Cover - `exchange` (string) - Exchange name (e.g., 'NSE') - `tradingsymbol` (string) - Trading symbol of the instrument (e.g., 'INFY-EQ') - `quantity` (integer) - Number of units to trade - `discloseqty` (integer) - Quantity to disclose (0 for none) - `price_type` (string) - 'SL-LMT' for StopLoss Limit order - `price` (float) - The limit price for the order - `trigger_price` (float) - The trigger price for the stop-loss order - `retention` (string) - Order retention period (e.g., 'DAY') - `remarks` (string) - Optional remarks for the order ### Request Example ```python api.place_order(buy_or_sell='B', product_type='C', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0, price_type='SL-LMT', price=1500, trigger_price=1450, retention='DAY', remarks='my_order_001') ``` ## Place Cover Order ### Description Places a Cover order. ### Method `api.place_order` ### Parameters - `buy_or_sell` (string) - 'B' for Buy, 'S' for Sell - `product_type` (string) - 'H' for Cover order - `exchange` (string) - Exchange name (e.g., 'NSE') - `tradingsymbol` (string) - Trading symbol of the instrument (e.g., 'INFY-EQ') - `quantity` (integer) - Number of units to trade - `discloseqty` (integer) - Quantity to disclose (0 for none) - `price_type` (string) - 'LMT' for Limit order - `price` (float) - The limit price for the order - `trigger_price` (float or None) - Trigger price for stop-loss orders - `retention` (string) - Order retention period (e.g., 'DAY') - `remarks` (string) - Optional remarks for the order - `bookloss_price` (float) - The price at which to book loss ### Request Example ```python api.place_order(buy_or_sell='B', product_type='H', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0, price_type='LMT', price=1500, trigger_price=None, retention='DAY', remarks='my_order_001', bookloss_price = 1490) ``` ## Place Bracket Order ### Description Places a Bracket order. ### Method `api.place_order` ### Parameters - `buy_or_sell` (string) - 'B' for Buy, 'S' for Sell - `product_type` (string) - 'B' for Bracket order - `exchange` (string) - Exchange name (e.g., 'NSE') - `tradingsymbol` (string) - Trading symbol of the instrument (e.g., 'INFY-EQ') - `quantity` (integer) - Number of units to trade - `discloseqty` (integer) - Quantity to disclose (0 for none) - `price_type` (string) - 'LMT' for Limit order - `price` (float) - The limit price for the order - `trigger_price` (float or None) - Trigger price for stop-loss orders - `retention` (string) - Order retention period (e.g., 'DAY') - `remarks` (string) - Optional remarks for the order - `bookloss_price` (float) - The price at which to book loss - `bookprofit_price` (float) - The price at which to book profit ### Request Example ```python api.place_order(buy_or_sell='B', product_type='B', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0, price_type='LMT', price=1500, trigger_price=None, retention='DAY', remarks='my_order_001', bookloss_price = 1490, bookprofit_price = 1510) ``` ``` -------------------------------- ### Get Single Order History Source: https://github.com/flattrade/pythonapi/blob/main/README.md Retrieves the history of a specific order using its order number. ```APIDOC ## Get Single Order History ### Description Retrieves the history of a specific order using its order number. This function is useful for tracking the status and details of a previously placed order. ### Method `api.single_order_history(orderno=orderno)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python orderno = ret['norenordno'] # from placeorder return value ret = api.single_order_history(orderno=orderno) ``` ### Response #### Success Response (200) Returns a JSON array of objects containing order history details. Fields include: - **stat** (string): Order book success or failure indication ('Ok' or 'Not_Ok'). - **exch** (string): Exchange Segment. - **tsym** (string): Trading symbol / contract on which order is placed. - **norenordno** (string): Noren Order Number. - **prc** (string): Order Price. - **qty** (string): Order Quantity. - **prd** (string): Display product alias name. - **status** (string): Current status of the order (e.g., 'COMPLETE', 'OPEN', 'PENDING'). - **rpt** (string): Order report type (e.g., 'Fill', 'New', 'PendingNew'). - **trantype** (string): Transaction type of the order ('B' for Buy, 'S' for Sell). - **prctyp** (string): Price type ('LMT' or 'MKT'). - **fillshares** (string): Total Traded Quantity of this order. - **avgprc** (string): Average trade price of total traded quantity. - **remarks** (string): Any message entered during order entry. - **exchordid** (string): Exchange Order Number. #### Response Example ```json [ { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "avgprc": "800.00", "dscqty": "0", "prd": "M", "status": "COMPLETE", "rpt": "Fill", "fillshares": "180", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" } ] ``` #### Error Response Returns a JSON object with error details in case of failure. Fields include: - **stat** (string): 'Not_Ok' indicating failure. - **request_time** (string): Response received time. - **emsg** (string): Error message. #### Error Response Example ```json { "stat": "Not_Ok", "request_time": "16:00:00 13-12-2020", "emsg": "Order not found" } ``` ``` -------------------------------- ### Initialize Flattrade API Session Source: https://github.com/flattrade/pythonapi/blob/main/README.md Sets up the API client by providing user ID and session token. Ensure the session token is generated via the login flow. ```python from api_helper import NorenApiPy import logging #enable dbug to see request and responses logging.basicConfig(level=logging.DEBUG) #start of our program api = NorenApiPy() #set token and user id #paste the token generated using the login flow described # in LOGIN FLOW of https://pi.flattrade.in/docs usersession='token here' userid = 'user id here' ret = api.set_session(userid= userid, password = '', usertoken= usersession) print(ret) ``` -------------------------------- ### Run Token Generator Script Source: https://github.com/flattrade/pythonapi/blob/main/token_generator/setup.md Execute the `gettoken.py` script to initiate the token generation process. This script will output an authentication URL that you need to visit in your browser. ```bash python ./token_generator/gettoken.py ``` -------------------------------- ### Retrieve Holdings - Python Source: https://github.com/flattrade/pythonapi/blob/main/README.md Call this method to get a list of your current holdings. Ensure you are logged in and have a valid account ID. ```python ret = api.get_holdings() ``` -------------------------------- ### Activate Virtual Environment (Linux/macOS) Source: https://github.com/flattrade/pythonapi/blob/main/token_generator/setup.md Activate the virtual environment on Linux or macOS systems using the `source` command. This ensures that subsequent commands use the Python interpreter and packages within this environment. ```bash source myvenv/bin/activate ``` -------------------------------- ### Get Positions Source: https://context7.com/flattrade/pythonapi/llms.txt Retrieves intraday and carry-forward positions, including unrealized MTM and realized PnL. MTM can be recalculated live. ```APIDOC ## Get Positions — `get_positions` Returns intraday and carry-forward positions with unrealized MTM (`urmtom`) and realized PnL (`rpnl`). MTM can be recalculated live: `netqty * (lp - netavgprc) * prcftr`. ```python ret = api.get_positions() mtm = pnl = 0.0 if ret: for pos in ret: mtm += float(pos.get('urmtom', 0)) pnl += float(pos.get('rpnl', 0)) print(f"{pos['tsym']:20s} netqty:{pos['netqty']:>6} " f"urmtom:{pos.get('urmtom','0'):>10} rpnl:{pos.get('rpnl','0'):>10}") day_m2m = mtm + pnl print(f"Daily MTM: {day_m2m:.2f}") # ACC-EQ netqty: 0 urmtom: 0.00 rpnl: 0.00 # Daily MTM: 0.00 ``` ``` -------------------------------- ### Product Conversion - `position_product_conversion` Source: https://context7.com/flattrade/pythonapi/llms.txt Converts an open position from one product type to another before the auto-square-off deadline. Requires specifying exchange, trading symbol, quantity, and product types. ```python ret = api.get_positions() p = ret[0] # Convert the first position's product from its current type to Intraday ('I') conv = api.position_product_conversion( exchange=p['exch'], tradingsymbol=p['tsym'], quantity=p['netqty'], new_product_type='I', # target product previous_product_type=p['prd'], # source product buy_or_sell='B', day_or_cf='DAY' ) print(conv) # {'request_time': '10:52:12 01-01-2025', 'stat': 'Ok'} ``` -------------------------------- ### Get Quotes using Flattrade API Source: https://github.com/flattrade/pythonapi/blob/main/README.md This function fetches complete details and properties for a given security. It requires the exchange and token of the security. ```python exch = 'NSE' token = '22' ret = api.get_quotes(exchange=exch, token=token) ``` -------------------------------- ### Configure API Credentials Source: https://github.com/flattrade/pythonapi/blob/main/token_generator/setup.md Edit the `gettoken.py` file to include your specific API credentials obtained from the Flattrade platform. Ensure you replace the placeholder values with your actual API Key, Secret Key, and Port. ```python # token_generator/gettoken.py # Configuration variables EndPoint = "/" GPort = 8080 api_key = "YOUR_API_KEY" api_secret = "YOUR_SECRET_KEY" ``` -------------------------------- ### Get Security Information using Flattrade API Source: https://github.com/flattrade/pythonapi/blob/main/README.md Use this function to retrieve comprehensive details and properties of a security. Requires exchange and token as parameters. ```python exch = 'NSE' token = '22' ret = api.get_security_info(exchange=exch, token=token) ``` -------------------------------- ### Place Market Order Source: https://github.com/flattrade/pythonapi/blob/main/README.md Use this to place a Market order. The price parameter should be set to 0 for market orders. ```python api.place_order(buy_or_sell='B', product_type='C', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0,price_type='MKT', price=0, trigger_price=None, retention='DAY', remarks='my_order_001') ``` -------------------------------- ### Get Trade Book - Python Source: https://github.com/flattrade/pythonapi/blob/main/README.md Call this function to retrieve a list of all trades executed for your account. Ensure you have authenticated with the API prior to calling this function. ```python ret = api.get_trade_book() print(ret) ``` -------------------------------- ### searchscrip Source: https://github.com/flattrade/pythonapi/blob/main/README.md Searches for a scrip or contract and its properties. This function can be used to retrieve the exchange-provided token for a scrip or to search for a partial string to get a list of matching scrips. ```APIDOC ## searchscrip(exchange, searchtext) ### Description Searches for a scrip or contract and its properties. This function can be used to retrieve the exchange-provided token for a scrip or to search for a partial string to get a list of matching scrips. ### Parameters #### Path Parameters - **exchange** (string) - Required - The exchange to search within (e.g., 'NSE', 'BSE', 'NFO'). - **searchtext** (string) - Required - The text to search for. This can be a symbol name, expiry date, option type, and strike price to narrow down results. ### Request Example ```python exch = 'NFO' query = 'BANKNIFTY 30DEC CE' ret = api.searchscrip(exchange=exch, searchtext=query) if ret != None: symbols = ret['values'] for symbol in symbols: print('{0} token is {1}'.format(symbol['tsym'], symbol['token'])) ``` ### Response #### Success Response (200) - **stat** (string) - Indicates success ('Ok') or failure ('Not_Ok'). - **values** (array) - An array of JSON objects, where each object represents a matching scrip. - **exch** (string) - The exchange of the scrip. - **token** (string) - The token of the scrip. - **tsym** (string) - The trading symbol of the scrip. - **pp** (string) - Price precision. - **ti** (string) - Tick size. - **ls** (string) - Lot size. - **emsg** (string) - Error message, present only in case of errors. #### Response Example ```json { "stat": "Ok", "values": [ { "exch": "NSE", "token": "18069", "tsym": "REL100NAV-EQ" }, { "exch": "NSE", "token": "24225", "tsym": "RELAXO-EQ" } ] } ``` #### Error Response Example ```json { "stat":"Not_Ok", "emsg":"No Data : " } ``` ``` -------------------------------- ### Sample Success Response for searchscrip Source: https://github.com/flattrade/pythonapi/blob/main/README.md This is a sample JSON response for a successful scrip search, detailing the exchange, token, and trading symbol for each matched scrip. ```json { "stat": "Ok", "values": [ { "exch": "NSE", "token": "18069", "tsym": "REL100NAV-EQ" }, { "exch": "NSE", "token": "24225", "tsym": "RELAXO-EQ" }, { "exch": "NSE", "token": "4327", "tsym": "RELAXOFOOT-EQ" }, { "exch": "NSE", "token": "18068", "tsym": "RELBANKNAV-EQ" }, { "exch": "NSE", "token": "2882", "tsym": "RELCAPITAL-EQ" }, { "exch": "NSE", "token": "18070", "tsym": "RELCONSNAV-EQ" }, { "exch": "NSE", "token": "18071", "tsym": "RELDIVNAV-EQ" }, { "exch": "NSE", "token": "18072", "tsym": "RELGOLDNAV-EQ" }, { "exch": "NSE", "token": "2885", "tsym": "RELIANCE-EQ" }, { "exch": "NSE", "token": "15068", "tsym": "RELIGARE-EQ" }, { "exch": "NSE", "token": "553", "tsym": "RELINFRA-EQ" }, { "exch": "NSE", "token": "18074", "tsym": "RELNV20NAV-EQ" } ] } ``` -------------------------------- ### Get Single Order History (Python) Source: https://github.com/flattrade/pythonapi/blob/main/README.md Retrieve the history of a single order by providing its order number. Ensure 'orderno' is obtained from a previous order placement. ```python orderno = ret['norenordno'] #from placeorder return value ret = api.single_order_history(orderno=orderno) ``` -------------------------------- ### Subscribe to Live Market Feed via WebSocket Source: https://github.com/flattrade/pythonapi/blob/main/README.md Connect to the WebSocket and subscribe to live market data for single or multiple tokens. Ensure the WebSocket connection is established before subscribing. The `event_handler_feed_update` function will be called for each received tick data. ```python api.subscribe('NSE|13') ``` ```python api.subscribe(['NSE|22', 'BSE|522032']) ``` ```python feed_opened = False def event_handler_feed_update(tick_data): print(f"feed update {tick_data}") def open_callback(): global feed_opened feed_opened = True api.start_websocket( order_update_callback=event_handler_order_update, subscribe_callback=event_handler_feed_update, socket_open_callback=open_callback) while(feed_opened==False): pass # subscribe to a single token api.subscribe('NSE|13') #subscribe to multiple tokens api.subscribe(['NSE|22', 'BSE|522032']) ``` -------------------------------- ### Place Bracket Order Source: https://github.com/flattrade/pythonapi/blob/main/README.md Use this to place a Bracket order, which includes both stop-loss and profit-taking levels. Requires bookloss_price and bookprofit_price. ```python api.place_order(buy_or_sell='B', product_type='B', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None, retention='DAY', remarks='my_order_001', bookloss_price = 1490, bookprofit_price = 1510) ``` -------------------------------- ### Get Single Order History Source: https://context7.com/flattrade/pythonapi/llms.txt Returns the complete lifecycle of a single order, tracking state transitions from new to filled or rejected. Requires the order number. ```python orderno = '250100000017' ret = api.single_order_history(orderno=orderno) for event in ret: print(f"qty:{event['qty']} prc:{event['prc']} f"trgprc:{event.get('trgprc','N/A')} status:{event['rpt']}") ``` -------------------------------- ### Place Limit Order Source: https://github.com/flattrade/pythonapi/blob/main/README.md Use this to place a Limit order. Ensure all required parameters like exchange, tradingsymbol, quantity, and price are correctly set. ```python api.place_order(buy_or_sell='B', product_type='C', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None, retention='DAY', remarks='my_order_001') ``` -------------------------------- ### Get Order Book Source: https://context7.com/flattrade/pythonapi/llms.txt Retrieves all orders placed during the current trading session, including status and fill details. Returns an empty list if no orders are found. ```python ret = api.get_order_book() if ret: for order in ret: print(f"{order['tsym']:20s} {order['trantype']} qty:{order['qty']:>6} f"prc:{order['prc']:>10} status:{order['status']}") ``` -------------------------------- ### Create a Virtual Environment Source: https://github.com/flattrade/pythonapi/blob/main/token_generator/setup.md This command creates an isolated Python environment for your project. It's recommended to use a virtual environment to manage project dependencies separately. ```bash python -m venv myvenv ``` -------------------------------- ### Place Cover Order Source: https://github.com/flattrade/pythonapi/blob/main/README.md Use this to place a Cover order, which includes a stop-loss. Requires bookloss_price to be set. ```python api.place_order(buy_or_sell='B', product_type='H', exchange='NSE', tradingsymbol='INFY-EQ', quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None, retention='DAY', remarks='my_order_001', bookloss_price = 1490) ``` -------------------------------- ### Get Holdings Source: https://context7.com/flattrade/pythonapi/llms.txt Fetches long-term stock holdings (CNC positions) from the demat account, including holding quantity and upload price. Returns an empty list if no holdings are found. ```python ret = api.get_holdings() if ret: for h in ret: sym = h['exch_tsym'][0]['tsym'] print(f"{sym:20s} holdqty:{h['holdqty']:>10} upldprc:{h.get('upldprc','N/A')}") ``` -------------------------------- ### Get Trade Book Source: https://context7.com/flattrade/pythonapi/llms.txt Returns all executed trades (fills) for the current trading day, including fill price, quantity, and time. Returns an empty list if no trades are found. ```python ret = api.get_trade_book() if ret: for trade in ret: print(f"{trade['tsym']:20s} {trade['trantype']} f"filled:{trade['fillshares']} @ {trade['flprc']} at {trade['fltm']}") ``` -------------------------------- ### Clone Flattrade Python API Repository Source: https://github.com/flattrade/pythonapi/blob/main/token_generator/setup.md Use this command to clone the official Flattrade Python API repository from GitHub. After cloning, navigate into the project directory using your code editor. ```bash git clone https://github.com/flattrade/pythonAPI.git code pythonAPI ``` -------------------------------- ### Place a Limit Order Source: https://github.com/flattrade/pythonapi/blob/main/README.md Use this function to place a limit order with specific price and trigger price. Ensure all required parameters like exchange, tradingsymbol, quantity, and price type are correctly provided. ```python ret = api.place_order(buy_or_sell='B', product_type='C', exchange='NSE', tradingsymbol='CANBK-EQ', quantity=1, discloseqty=0,price_type='SL-LMT', price=200.00, trigger_price=199.50, retention='DAY', remarks='my_order_001') ```