Python
To install the OpenAlgo Python library, use pip:
# Trading API + the Rust-powered ta indicator library, in one package
pip install openalgoGet the OpenAlgo apikey
Make Sure that your OpenAlgo Application is running. Login to OpenAlgo Application with valid credentials and get the OpenAlgo apikey
For detailed function parameters refer to the API Documentation
Getting Started with OpenAlgo
First, import the api class from the OpenAlgo library and initialize it with your API key:
from openalgo import api
# Replace 'your_api_key_here' with your actual API key
# Specify the host URL with your hosted domain or ngrok domain.
# If running locally in windows then use the default host value.
client = api(api_key='your_api_key_here', host='http://127.0.0.1:5000')
The full constructor is:
api(api_key, host="http://127.0.0.1:5000", version="v1", timeout=120.0,
ws_port=8765, ws_url=None, verbose=False, auto_reconnect=True)host(str): base URL of your OpenAlgo server. REST calls go to{host}/api/{version}/.version(str): API version. Defaults tov1.timeout(float): REST request timeout in seconds. Defaults to120.0.ws_port(int): WebSocket port. Defaults to8765.ws_url(str): full WebSocket URL. Overrideshostandws_port. When omitted it is derived asws://<host-name>:<ws_port>, so a local install needs nows_urlat all.verbose(int): SDK log level for the WebSocket feed.0/Falsesilent,1/Truebasic,2full debug. See Websockets (Verbose Control).auto_reconnect(bool): defaults toTrue. The SDK reconnects, re-authenticates and replays every active subscription after a drop, with exponential backoff. Set toFalsefor manual reconnect handling.
All order and data methods are keyword-only, so every argument must be passed by name.
The client keeps a pooled HTTP connection open. Call client.close() when you are done, or use it as a context manager:
Check OpenAlgo Version
GTT orders and the strategy module methods need openalgo 2.0.4 or newer. Upgrade with pip install -U openalgo.
Examples
Please refer to the documentation on order constants, and consult the API reference for details on optional parameters
PlaceOrder example
To place a new market order:
Place Market Order Response
To place a new limit order:
Place Limit Order Response
PlaceSmartOrder Example
To place a smart order considering the current position size:
Place Smart Market Order Response
OptionsOrder Example
To place ATM options order
Place Options Order Response
To place ITM options order
Place Options Order Response
To place OTM options order
Place Options Order Response
OptionsMultiOrder Example
To place Iron options order (Same Expiry)
Place OptionsMultiOrder Response
To place Diagonal Spread options order (Different Expiry)
Place OptionsMultiOrder Response
BasketOrder example
To place a new basket order:
Basket Order Response
SplitOrder example
To place a new split order:
SplitOrder Response
ModifyOrder Example
To modify an existing order:
Modify Order Response
CancelOrder Example
To cancel an existing order:
Cancelorder Response
CancelAllOrder Example
To cancel all open orders and trigger pending orders
Cancelallorder Response
ClosePosition Example
To close all open positions across various exchanges
ClosePosition Response
OrderStatus Example
To Get the Current OrderStatus
Orderstatus Response
OpenPosition Example
To Get the Current OpenPosition
OpenPosition Response
PlaceGTTOrder Example
A GTT (Good Till Triggered) order is a price trigger that sits with the broker until LTP crosses your level, then places the underlying order automatically.
There are two shapes, and picking the wrong one is the usual mistake:
SINGLE
One entry or exit at a level
1
1
OCO
You hold a position and want both a stoploss and a target, whichever hits first
2
1 of 2, the other is auto-cancelled
For a SINGLE, exactly one of triggerprice_sl / triggerprice_tg carries your level and the other stays 0. Pick by where the trigger sits relative to LTP: triggerprice_sl for a level below LTP (sell stop-loss, buy the dip), triggerprice_tg for one above (breakout buy, sell at target). A SINGLE has no stoploss leg, so the suffix is only a directional hint.
For an OCO, the suffix is a real role and all four fields are required: triggerprice_sl with its stoploss limit, and triggerprice_tg with its target limit, where triggerprice_sl < triggerprice_tg.
GTT accepts CNC and NRML only. MIS is refused: a GTT can sit for days and MIS is squared off the same session.
PlaceGTTOrder Response:
Save the trigger_id: modify and cancel both need it.
ModifyGTTOrder Example
Modify is a full replacement, not a patch. Every field on the trigger is replaced by what the call sends, so pass everything you want to keep rather than only the values that changed.
ModifyGTTOrder Response:
Trigger prices, limit prices, quantity and pricetype are modifiable. trigger_type, symbol, exchange and action are not - cancel and re-place instead. Only active GTTs can be modified; triggered, cancelled and expired ones are immutable.
CancelGTTOrder Example
CancelGTTOrder Response:
Cancelling an OCO removes both legs atomically; there is no per-leg cancel.
GTTOrderBook Example
By default this lists active triggers only, the ones that can still fire. Pass status="all" to include the history as well (triggered, cancelled, expired, rejected), ordered active first; in analyzer mode a fired leg also carries the triggered_order_id of the sandbox order it placed.
GTTOrderBook Response:
trigger_prices is sorted ascending: a SINGLE has one element and one leg, an OCO has two of each with the stoploss first.
The SDK refuses an impossible trigger spec before anything leaves the machine, and returns the refusal in the same shape as an API error:
API reference: PlaceGTTOrder, ModifyGTTOrder, CancelGTTOrder, GTTOrderBook.
Quotes Example
Quotes response
MultiQuotes Example
Quotes response
Depth Example
Depth Response
History Example
Download Data Directly from Broker API
Download Data Directly from Historify DuckDB (Stored Data)
History Response
Intervals Example
Intervals response
OptionChain Example
Note : To fetch entire option chain for a expiry remove the strike_count (optional) parameter
Symbols Response
Symbol Example
Symbols Response
Search Example
Search Response
OptionSymbol Example
ATM Option
OptionSymbol Response
ITM Option
OptionSymbol Response
OTM Option
OptionSymbol Response
SyntheticFuture Example
SyntheticFuture Response
OptionGreeks Example
OptionGreeks Response
Expiry Example
Expiry Response
Instruments Example
instruments() returns a pandas DataFrame, not a dict. Omit exchange to download every exchange in one call, which is a large download, so pass an exchange when you only need one.
Instruments Response
Telegram Alert Example
Telegram Alert Response
WhatsApp Alert Example
Prerequisites: open /whatsapp in the OpenAlgo web UI, click Pair, scan the QR with your phone. Pairing is admin-only on purpose: the REST API exposes only the send endpoint so a leaked API key cannot re-pair the device. Once paired, the bot auto-reconnects on every server boot from the encrypted session blob stored in openalgo.db.
One unified call handles every common case: text, image, document, self-send, single recipient, or small broadcast (max 5).
Send to yourself (simplest case)
WhatsApp Alert Response (wait_for_delivery=True, the default):
Send to a single phone number
Small broadcast (up to 5 recipients)
Send an image with caption
The path is read from the OpenAlgo server's filesystem. It must lie under WHATSAPP_ATTACHMENT_ROOTS (defaults to <openalgo>/db/attachments/).
Send a document (PDF, CSV, ...)
Fire-and-forget (skip the delivery report)
Send to a linked OpenAlgo user (legacy multi-recipient path)
Funds Example
Funds Response
Margin Example
Margin Response
OrderBook Example
TradeBook Example
TradeBook Response
PositionBook Example
PositionBook Response
Holdings Example
Holdings Response
Holidays Example
Holidays Response
Timings Example
Timings Response
Analyzer Status Example
Analyzer Status Response
Analyzer Toggle Example
Analyzer Toggle Response
Strategy Module
OpenAlgo's /strategy module runs multi-leg options strategies with end-to-end risk management, plus a signal-driven mode for TradingView alerts. Two surfaces reach it, and they take different credentials:
api(api_key=...)
Your OpenAlgo API key
Lifecycle and reads: list, status, start, stop, close_all, close_leg, runs, orders, events
Strategy(...)
The strategy's oaws_ webhook token
The public webhook at /strategy/webhook/<token>, which is what TradingView posts to
Building a strategy stays in the browser wizard at /strategy. The API-key surface is lifecycle plus reads only: nothing on it can create a strategy, edit its configuration, enable live trading, rotate a webhook token, or delete anything.
Two strategy kinds, and each refuses the other's vocabulary:
batch - a multi-leg spread entered and exited as a unit.
start/stop.signal - one alert moves one leg.
long_entry/long_exit/short_entry/short_exit. There is no start and no mode: the first signal after the platform session boundary opens the run.
Four rules worth knowing before you call anything:
modeon start is required and is never defaulted, in the SDK or on the server. It is a keyword argument with no default, so omitting it is aTypeErrorrather than a live order.Live is opt-in per strategy. A strategy is created sandbox-only, and
mode="live"is refused with a 409 until the operator enables live trading on the strategy page.An accepted stop is not proof of flatness. Read
stop_pendingand the per-leg outcomes; never infer flatness from the HTTP status.A strategy that is not yours answers 404, identical to one that does not exist, so the id space cannot be probed.
StrategyList Example
StrategyList Response:
The list form omits legs; call strategystatus for one strategy's legs. For a stopped strategy, last_finalized_run.pnl_realized is the durable final P&L.
StrategyStatus Example
StrategyStatus Response:
run is null whenever the strategy has no current run, which is the normal state of a stopped strategy. Prefer it over the strategy's own status when you need to know whether anything is actually open. A populated stop_requested_reason means a stop is durable but not yet confirmed flat: the run is still current and still managed.
StrategyStart Example
Starts a batch strategy: every leg's entry order is placed.
StrategyStart Response:
ok: true with acknowledged: false is a real broker order whose id could not be written back, not a rejection - it reconciles itself. A second start against a running strategy answers 409, so two triggers firing at once cannot both place a full set of entries.
StrategyStop Example
Exits every owned position at market.
StrategyStop Response:
stop_pending: true means the request is durable and its exits were accepted, but the run stays open, subscribed and managed until fills prove every position is flat. A 409 can also carry stop_pending: true when an unfilled entry or a refused exit still needs management - retry the stop in that case.
StrategyCloseAll Example
Same stop mechanics as strategystop, different audit intent: a close_all_manual event is written first, which proves an operator asked for a flatten.
StrategyCloseLeg Example
Exits one leg at market; the run continues with the rest. leg_id is the id the wizard assigned within the strategy, the same value that appears in legs[].id on strategystatus. It is not an order id.
StrategyCloseLeg Response:
run_stopped reports only what this call could prove. A live broker normally acknowledges before its fill, so even the last accepted exit returns false and the fill finalises the run later. A leg_id that names no open leg is a 409, not a 404.
StrategyRuns Example
Every activation of a strategy, newest first.
StrategyRuns Response:
limit is 1 to 500 and is bounded rather than clamped: a value outside the range is a 400, so you learn it was refused. An overall threshold triggers an exit, it does not promise the result - market exits fill at the available bid/ask, so pnl_realized can differ from the threshold that caused the stop.
StrategyOrders Example
Every order the engine placed, oldest first, so an entry always precedes its exit.
StrategyOrders Response:
A row is written before the broker answers, so an order can appear with status: "pending" and a null broker_order_id. That is deliberate: an order that reached the broker but was never recorded would be invisible to crash recovery.
StrategyEvents Example
The risk-event audit trail, newest first. The trail is append-only.
StrategyEvents Response:
Events an operator should not ignore:
run_stop_requested
info
The stop is durable and new signal entries are gated. Not proof the broker is flat
run_stop_failed
critical
The broker refused a stop's exits and the run is still holding those positions
order_ack_unrecorded
critical
The broker accepted an order but its acknowledgement could not be written; it reconciles itself
leg_expiry_fallback
warn
The chain did not list the expiry rank the leg asked for, so a nearer one was used
flip_outgoing_exit_rejected
critical
The outgoing side of a signal flip is still held
Strategy Webhook Example
The public webhook at /strategy/webhook/<token> is what TradingView and other alert senders post to. It is not under /api/v1 and takes no API key: the oaws_ token in the URL is the whole credential. The SDK's Strategy class speaks its protocol:
Every documented outcome is returned rather than raised, with its result label. See Strategy RMS From Python for the full webhook guide, and the Strategy RMS API for every field of the nine methods above.
LTP Data (Streaming Websocket)
Quotes (Streaming Websocket)
Depth (Streaming Websocket)
Last updated
Was this helpful?