Skip to content

Python API

This tab documents every public class and member of the tradingmachine library, laid out like Zerodha's Kite Connect documentation: each page opens with a summary table, then gives each member its own section with its parameters, an example, what it returns and what it raises. This page is the index of all of them, one table per page, so you can find any member in one scroll.

The library is a Python face on the Unified Broker Interface (UBI), a REST API that combines ten Indian stock brokers into one account. Almost every member here sends one request to UBI, and each member's section names the UBI route it calls.

How to read the badges

Every member carries a coloured badge saying what kind of thing it is. The badge matters most for the red one, because those members send real orders to real brokers.

Badge Meaning
property Reads a value from UBI each time you access it, and never writes anything. Written without brackets: instrument.last_price.
method Takes arguments and reads only. Written with brackets: instrument.prices(days=10).
classmethod Called on the class rather than on an instrument, to find instruments: Equity.search("nse", "RELI").
places orders Sends orders to a broker, or cancels or changes them. These act on real money.
class A class you construct.

The rule behind the first two badges is the library's own: anything that only reports a value is a property, and only members that take an argument or write to the market are methods.

Where the members are

The chart below counts the members documented on each page of this tab, which shows where the bulk of the library's surface is. The 32 price wrappers are the largest group, because each names one place a price can come from, and the 24 contract members on Derivatives come second, most of them on options.

{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "description": "Number of public members documented on each Python API page", "width": "container", "height": 260, "data": { "values": [ {"page": "Price wrappers", "members": 32}, {"page": "Market data", "members": 15}, {"page": "Orders", "members": 15}, {"page": "Positions", "members": 8}, {"page": "The UBI client", "members": 8}, {"page": "Holdings", "members": 6}, {"page": "Derivatives", "members": 24}, {"page": "Finding instruments", "members": 5}, {"page": "Instruments", "members": 2}, {"page": "The account", "members": 3} ] }, "mark": {"type": "bar", "cornerRadiusEnd": 3, "color": "#ff7043"}, "encoding": { "y": {"field": "page", "type": "nominal", "sort": "-x", "title": null}, "x": {"field": "members", "type": "quantitative", "title": "Public members"}, "tooltip": [{"field": "page"}, {"field": "members"}] } }

Three pages hold classes rather than members. Synthetic orders documents the 54 order classes in tradingmachine.orders, Instruments documents the 27 instrument classes, and Asset baskets documents the five kinds of basket in tradingmachine.asset_baskets and the classes that store them. The fourteen classes of candle analysis, 209 methods from indicators to the performance measures, have their own Analysis tab, and every instrument and every basket inherits them.

Instruments

An instrument is looked up once when you construct it, and from then on every member reads from UBI. The Instruments page documents the 27 classes, such as Equity("nse", "RELIANCE") or EquityIndexOption("nse", "NIFTY", "2026-09-29", 25000, "CE"), and the attributes the lookup fills in. The first member below belongs to every instrument class, and the second only to indices and funds.

Kind Member Description
classmethod shared_unified_broker_interface Returns the one client all instruments share, creating it on first use.
property constituents The stored basket of what an index, an exchange traded fund or a mutual fund holds, on the four index classes, ExchangeTradedFund and MutualFund.

Market data

These members read candles, quotes and the order book. The first four work on every instrument; the order-book values exist only on instruments that can be traded, because an index has no order book.

Kind Member Description
method prices Fetches the instrument's candles for a range from UBI.
property quote The instrument's full unified quote, read from UBI on every access.
property last_price The instrument's last traded price, read from UBI on every access.
property ohlc The day's open, high and low with the last and previous close prices, read from UBI on every access.
property bids The buy side of the order book, read from UBI on every access.
property offers The sell side of the order book, read from UBI on every access.
property best_bid The highest bid in the order book.
property best_offer The lowest offer in the order book.
property bid_offer_spread The gap between the best offer and the best bid, measured from one quote.
property mid_price The price halfway between the best bid and the best offer, from one quote.
property volume_weighted_average_price Today's volume weighted average price.
property last_quantity The quantity of the last trade.
property total_traded_volume The quantity traded so far today.
property open_interest The open interest of a future or an option.
property last_trade_time When the last trade happened.

Finding instruments

These class methods find instruments rather than read one. search exists on the cash and index classes, and the other four are defined once on the Futures and Option base classes and inherited by every derivative class, each of which names its own segment.

Kind Member Description
classmethod search Finds listed instruments whose symbol contains a term, on the cash and index classes.
classmethod expiries Lists the expiry dates a derivative is listed for.
classmethod contracts Lists the contracts on an underlying as a DataFrame of identities.
classmethod strikes Lists the strike prices listed on one underlying for one expiry.
classmethod chain Lists every option listed on one underlying for one expiry.

Derivatives

These members report what a futures or option contract has and a share does not: its expiry, its underlying, its basis, and for an option its moneyness, implied volatility and greeks. They are defined on the derivative base classes and inherited by all sixteen futures and option classes, and none of them places an order. Those marked futures or options exist only on that kind of contract.

Kind Member Description
property days_to_expiry The calendar days left until the contract expires.
property expired Whether the expiry date has passed.
property expiry_kind Whether the contract is the month's last expiry or a weekly one.
property next_expiry The next expiry after this one, where a position rolls to.
property underlying The underlying instrument, built afresh on every read.
property underlying_price The underlying's last traded price.
property open_interest_day_high The highest open interest reached today.
property open_interest_day_low The lowest open interest reached today.
property contract_value What one lot is worth at the last price.
property basis How far a future's price is above its underlying's. Futures only.
property basis_percent The basis as a percentage of the underlying's price. Futures only.
property cost_of_carry The basis as a yearly rate. Futures only.
property is_call, is_put Whether an option is a call or a put. Options only.
property intrinsic_value What the option would be worth if exercised now. Options only.
property time_value The part of the premium above the intrinsic value. Options only.
property in_the_money Whether the option has intrinsic value. Options only.
property moneyness_percent How far in or out of the money the option is, in per cent. Options only.
property breakeven_price The underlying price at which a buyer breaks even at expiry. Options only.
property premium_per_lot What one lot costs to buy. Options only.
property notional_value What one lot controls at the strike price. Options only.
method implied_volatility The volatility the option's price implies. Options only.
method greeks The option's fair price, delta, gamma, theta, vega and rho. Options only.

Orders

The red badges place real orders

Members with a places orders badge send orders through UBI to real brokers, with real money. Pass dry_run=True to place_order, modify_order or cancel_order to have UBI check an order and show the request it would send, without sending it.

These members place, change and cancel orders in one instrument, read that instrument's rows out of the day's order book and trade book, and read the order engine's parents, which are the synthetic orders and held limit orders UBI is working.

Kind Member Description
places orders place_order Places one order in this instrument through UBI.
places orders modify_order Changes one pending order through UBI.
places orders cancel_order Cancels one pending order through UBI.
places orders cancel_open_orders Cancels every order in this instrument that is still waiting, whether at a broker or held in UBI's order engine.
places orders cancel_parent Cancels one of the order engine's parents, with every leg it still has resting at a broker, or one part of a plan.
property orders Every one of today's orders in this instrument, whatever its status.
property open_orders Today's orders in this instrument that can still be changed.
property completed_orders Today's orders in this instrument that filled in full.
property rejected_orders Today's orders in this instrument that a broker or the exchange refused.
property cancelled_orders Today's orders in this instrument that were cancelled.
property trades Today's trades in this instrument.
property parents This instrument's synthetic orders and held orders that the order engine has not finished.
method parent Reads one of the order engine's parents, whether or not it has finished.
method parent_orders Today's broker orders that one parent placed.
method parent_trades Today's trades in the broker orders that one parent placed.

Price wrappers

Each wrapper is place_order with the price source written into its name, so buy_at_best_bid_price(quantity=1, product="cnc") joins the queue at the best bid. Apart from the market and limit pairs, UBI works out the price itself when it sends the order. The sixteen wrappers below are the market and limit pairs and the twelve that name a single price.

Kind Member Description
places orders buy_at_market_price Buys at whatever price the market is asking.
places orders sell_at_market_price Sells at whatever price the market is bidding.
places orders buy_at_limit_price Buys at a price of your choosing, or better.
places orders sell_at_limit_price Sells at a price of your choosing, or better.
places orders buy_at_best_bid_price Buys patiently, joining the queue at the highest price anyone is bidding.
places orders buy_at_best_offer_price Buys at once, by crossing the spread to the lowest price anyone is offering.
places orders sell_at_best_offer_price Sells patiently, joining the queue at the lowest price anyone is offering.
places orders sell_at_best_bid_price Sells at once, by crossing the spread to the highest price anyone is bidding.
places orders buy_at_mid_price Buys halfway between the best bid and the best offer.
places orders sell_at_mid_price Sells halfway between the best bid and the best offer.
places orders buy_at_volume_weighted_average_price Buys at the average price the day has traded at so far.
places orders sell_at_volume_weighted_average_price Sells at the average price the day has traded at so far.
places orders buy_at_marketable_price Buys now with a limit order priced at the best offer, the price it takes to fill immediately.
places orders sell_at_marketable_price Sells now with a limit order priced at the best bid, the price it takes to fill immediately.
places orders buy_at_last_price Buys with a limit order at the price the instrument last traded at.
places orders sell_at_last_price Sells with a limit order at the price the instrument last traded at.

The other sixteen reach deeper into the order book, from the second to the fifth price on each side. They are listed in the collapsed table below.

The sixteen depth-level wrappers
Kind Member Description
places orders buy_at_second_best_bid_price Buys at the second best price on the buy side of the book.
places orders buy_at_third_best_bid_price Buys at the third best price on the buy side of the book.
places orders buy_at_fourth_best_bid_price Buys at the fourth best price on the buy side of the book.
places orders buy_at_fifth_best_bid_price Buys at the fifth best price on the buy side of the book.
places orders sell_at_second_best_bid_price Sells at the second best price on the buy side of the book.
places orders sell_at_third_best_bid_price Sells at the third best price on the buy side of the book.
places orders sell_at_fourth_best_bid_price Sells at the fourth best price on the buy side of the book.
places orders sell_at_fifth_best_bid_price Sells at the fifth best price on the buy side of the book.
places orders buy_at_second_best_offer_price Buys at the second best price on the sell side of the book.
places orders buy_at_third_best_offer_price Buys at the third best price on the sell side of the book.
places orders buy_at_fourth_best_offer_price Buys at the fourth best price on the sell side of the book.
places orders buy_at_fifth_best_offer_price Buys at the fifth best price on the sell side of the book.
places orders sell_at_second_best_offer_price Sells at the second best price on the sell side of the book.
places orders sell_at_third_best_offer_price Sells at the third best price on the sell side of the book.
places orders sell_at_fourth_best_offer_price Sells at the fourth best price on the sell side of the book.
places orders sell_at_fifth_best_offer_price Sells at the fifth best price on the sell side of the book.

Positions

These members act on this instrument's positions without being told which side you are on, so a long position is reduced by selling and a short one by buying.

Kind Member Description
property net_positions The positions held in this instrument now, merged across every broker.
property day_positions Today's own positions in this instrument, without what was carried in.
property positions_value What this instrument's open positions are worth at the moment.
property positions_pnl What this instrument's positions have made or lost.
places orders add_to_position Makes an existing position bigger, or opens a new one.
places orders reduce_position Makes an existing position smaller, without turning it around.
places orders liquidate_position Closes one position in this instrument completely.
places orders liquidate_all_positions Closes every position this instrument holds, under every product.

Holdings

Holdings are shares kept for the long term in a demat account. Only Equity, FixedIncome, ExchangeTradedFund, InvestmentTrust and MutualFund carry these six members, and their orders are always sent under the cnc product.

Kind Member Description
property holdings The long-term holding of this share, merged across every broker.
property holdings_value What the shares held are worth at the moment.
property holdings_pnl What the shares held have made or lost.
places orders add_to_holdings Buys more of this share to keep.
places orders reduce_holdings Sells some of the shares held, without selling more than are free.
places orders liquidate_holdings Sells every share held that is free to sell.

The account

Account acts on the whole account rather than on one instrument. It holds the kill switch and two readers of UBI's order engine.

Kind Member Description
places orders flatten Stops every synthetic order, cancels every open order at every broker, then closes every position in the account.
property parents Every synthetic order and held order the order engine has not finished, in every instrument.
method intent Reads what the order engine did with one order after its placement stopped waiting.

Asset baskets

An asset basket is a group of instruments that is priced, analysed and stored as one, such as a portfolio, a watchlist or what an index or a fund holds. The Asset baskets page documents the classes below, each with its own members; two of Portfolio's members place real orders.

Kind Member Description
class AssetBasket The shared base: live prices for every member in one request, weights, correlation, risk, and every analysis method.
class Portfolio What you hold, with a quantity per member: its value, its profit and loss, and orders for the whole basket.
places orders Portfolio.place_orders Sends one market order per member, all in one request.
places orders Portfolio.rebalance Sends the buys and sells that give the portfolio another basket's weights.
class Watchlist Instruments followed together, each counting equally.
class Index A weighted index, published or your own, which can be turned into a portfolio.
class ExchangeTradedFundConstituents What an exchange traded fund holds, compared with the fund's own price.
class MutualFundConstituents What a mutual fund holds, the only way to measure one.
class BasketStore, BasketCsvImporter Save and load baskets in MongoDB, and fill them from a CSV file.

The UBI client

UnifiedBrokerInterface is the HTTP client every instrument shares. You rarely call it directly, but it is how you reach a UBI route the library does not wrap.

Kind Member Description
method connect Exchanges the api key and secret for a new access token.
method disconnect Revokes the access token in force on the server.
method status Reports whether the session is connected and when its token expires.
method get Sends a GET request.
method post Sends a POST request.
method put Sends a PUT request.
method patch Sends a PATCH request.
method delete Sends a DELETE request.

Reference pages

Two pages support all the others. Vocabulary lists every plain string the library passes through, such as "buy", "limit" and "cnc", in the style of Kite's glossary of constants. Errors lists every exception, which HTTP status from UBI raises it, and what to do next.