MATLAB
The OpenAlgo MATLAB library connects MATLAB to your OpenAlgo server. From the Command Window, a live script or a scheduled matlab -batch job you can place and manage orders, read funds, positions and holdings, pull historical candles into a timetable, work with option chains and Greeks, run strategies from the strategy module, and stream live prices and order updates.
Source code: https://github.com/marketcalls/openalgo-matlab-library
To install the OpenAlgo MATLAB library, download openalgo-matlab-1.1.0.mltbx from the GitHub releases page and double-click it in MATLAB, or install it from the Command Window:
matlab.addons.install("openalgo-matlab-1.1.0.mltbx");To work from the source instead, clone the repository and add the folder that contains +openalgo to the MATLAB path:
git clone https://github.com/marketcalls/openalgo-matlab-libraryaddpath("C:\path\to\openalgo-matlab-library") % the folder that contains +openalgo
savepath % optional: keep it for future sessionsThe library is tested on MATLAB R2026b and uses only base MATLAB, so no toolboxes are needed. A live feed from a hosted server over wss:// also needs one of .NET (Windows), MATLAB's Python interface or Java; see Connecting to a Hosted Server. A local ws:// feed needs none of them.
Get 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
Create a client with your API key:
% 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 = openalgo.api(api_key="your_api_key_here", host="http://127.0.0.1:5000");To keep the key out of your scripts, read it from an environment variable: openalgo.api(api_key=getenv("OPENALGO_API_KEY")).
The full constructor is:
api_key(text): your OpenAlgo API key. Required.host(text): base URL of your OpenAlgo server. REST calls go to{host}/api/{version}/.version(text): API version. Defaults to"v1".timeout(number): REST request timeout in seconds. Defaults to120.ws_port(number): WebSocket port. Defaults to8765.ws_url(text): full WebSocket URL. Overrideshostandws_port. When omitted it is derived fromhost:ws://<host-name>:<ws_port>for anhttp://host, so a local install needs nows_urlat all, andwss://<host>/wsfor anhttps://host (see Connecting to a Hosted Server).verbose: feed log level.0/falsesilent,1/truebasic,2full debug. See Websockets (Verbose Control).auto_reconnect(logical): defaults totrue. The client reconnects, re-authenticates and replays every active subscription after a drop, with increasing delays. Set tofalsefor manual reconnect handling.
The arguments can also be given by position in this order, for example openalgo.api("your_api_key_here", "http://127.0.0.1:5000").
Displaying the client never shows your API key; it prints the endpoints and the feed state only:
Call client.close() when you are done with the REST methods; any REST call after that returns an error struct. Call client.disconnect() when you are done with the live feed.
Name=value arguments
Methods are called on the client with ., using name=value arguments:
Names are exact and case-sensitive.
Exchange="NSE"is notexchange="NSE": an unknown name is sent as an extra field, so the requiredexchangeis reported missing. The older"name", valueform works too:client.quotes("symbol", "RELIANCE", "exchange", "NSE").A required parameter that is missing stops the script with an error such as
placeorder() missing 1 required keyword-only argument: 'exchange', before anything reaches the broker.A few methods also take their main value without a name:
client.analyzertoggle(true),client.holidays(2026),client.timings("2025-12-19"),client.whatsapp("NIFTY crossed 26000!"),client.telegramstats(30),client.telegrampreferences(123456789),client.updatetelegrampreferences(123456789, daily_summary=true), and on the webhook senders.start("sandbox"),s.signal("long_entry", leg_id=1)ands.send(payload).[]means "not set". An optional parameter left at[]is not sent.Extra name=value pairs are sent to the server as additional fields, for example
price=16,trigger_price=0ordisclosed_quantity=0onplaceorder. Methods that take no extra fields refuse them withopenalgo:unexpectedArgument.strategyis optional on the order methods. When it is left out, orders are tagged"MATLAB". Pass your own strategy name so your orders are easy to find in the OpenAlgo order book.Records and lists: a record is a scalar struct (
struct("symbol", "RELIANCE", "exchange", "NSE")); a list of records is a cell array of structs ({struct(...), struct(...)}) or a struct array (struct("symbol", {"RELIANCE", "TCS"}, "exchange", "NSE")); a list of texts is a cell array or a string array (["919876543210" "919812345678"]). Lists are always sent as JSON arrays, even with one element.
Numbers can be passed as numbers. Fields the server expects as text are converted for you (1 is sent as "1", 16.5 as "16.5"), with the shortest digits that read back as the same number (a price of 1180.05 is sent as 1180.05, a computed 0.1 + 0.2 as 0.30000000000000004). Large whole numbers are never written in exponent form (100000, not 1e+05). A whole number is sent without a decimal point, so price=50.0 sends "50"; write price="50.0" when the exact text matters. Pass order ids as text: they are longer than a double can hold exactly.
Reading responses
Every REST method returns the server's JSON answer as a MATLAB struct, so you read a field with .:
The examples below show each response as the JSON the server returns, because it is shorter to read. The MATLAB value has the same structure, decoded with jsondecode:
JSON objects are structs and JSON text is a character vector.
A list of records with the same fields is a struct array (
response.results(2)); a list of records with different fields is a cell array (response.results{2}). A one-element list of records is a 1x1 struct.A list of texts is a cell array of character vectors (
response.data{1}), and a list of numbers is a column vector.JSON
nullis[], so test it withisempty.Keys that are not valid MATLAB names are renamed:
"1"becomesx1,"d-e"becomesd_e.
When a list can hold records of different shapes (for example one leg that failed and carries a message field), loop over it in a way that works for both forms:
To see a response as JSON text, use jsonencode(response, PrettyPrint=true). history returns a timetable and instruments a table instead of a struct.
Check OpenAlgo Version
Help Pages
Every method has its own MATLAB help text with its parameters, the request it sends, its return value and examples:
Examples
Please refer to the documentation on order constants, and consult the API reference for details on optional parameters.
Ping Example
Run this at the start of a script, before it trades: it confirms that the API key is valid and that your broker session is logged in.
Ping Response
broker is the broker your OpenAlgo server is connected to. An invalid API key, or a broker session that is missing or has expired, is answered with HTTP 403, which the client returns as an http_error struct with code 403. A simple pre-flight check:
PlaceOrder Example
To place a new market order:
Place Market Order Response
To place a new limit order:
Place Limit Order Response
price, trigger_price and disclosed_quantity are extra fields, sent as text: "price": "16", "trigger_price": "0", "disclosed_quantity": "0".
PlaceSmartOrder Example
To place a smart order considering the current position size:
Place Smart Market Order Response
OptionsOrder Example
To place an ATM options order:
Place Options Order Response
To place an ITM options order:
Place Options Order Response
To place an OTM options order:
Place Options Order Response
For a LIMIT option order pass price as an extra field, for example price_type="LIMIT", price="50.0". strike_int is deprecated (the server detects the strike interval itself): passing it still works but warns with the identifier openalgo:deprecated.
OptionsMultiOrder Example
To place an Iron Condor (same expiry):
Place OptionsMultiOrder Response
To place a Diagonal Spread (different expiry), give each leg its own expiry_date:
Place OptionsMultiOrder Response
Check each leg's result rather than only the top-level status. A failed leg carries a message instead of an orderid, which makes results a cell array, so convert first:
Each leg takes offset, option_type, action and quantity, and optionally expiry_date, pricetype, product, price, trigger_price and disclosed_quantity. BUY legs are executed first for margin efficiency, then SELL legs.
BasketOrder Example
To place a new basket order:
Basket Order Response
Numbers inside an order (here quantity) are sent as text.
SplitOrder Example
To place a new split order:
SplitOrder Response
ModifyOrder Example
To modify an existing order:
Modify Order Response
Pass order ids as text. disclosed_quantity and trigger_price default to "0".
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 order status:
OrderStatus Response
OpenPosition Example
To get the current open position:
OpenPosition Response
The quantity comes back as text, as the server sends it. Use str2double(response.quantity) to compute with it.
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 (the default is CNC). MIS is refused: a GTT can sit for days and MIS is squared off the same session. GTT prices and quantities are sent as JSON numbers, and for a SINGLE the stoploss and target fields are sent as null.
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 price type 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 library 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
MATLAB's default format short shows 1.1878e+03; the value is exactly 1187.75 (format long g displays it in full).
MultiQuotes Example
MultiQuotes Response
results is a 3x1 struct array:
The same symbols can be given as a struct array: struct("symbol", {"RELIANCE", "TCS", "INFY"}, "exchange", "NSE").
Depth Example
Depth Response
History Example
Download data directly from broker API:
Download data from Historify DuckDB (stored data):
History Response
history returns a timetable:
The row times are named timestamp:
For intraday intervals they are
datetimevalues in the Asia/Kolkata time zone. MATLAB reports that zone under its canonical alias, sodf.Properties.RowTimes.TimeZoneshows'Asia/Calcutta'. It is the same zone.For
D,WandMthey carry no time zone.
Rows are sorted by time and duplicate timestamps are removed (the first is kept). The other columns keep the server's names (open, high, low, close, volume, and oi where the server sends it). The volume is stored exactly; 3.1862e+05 is only MATLAB's short display format.
When something goes wrong, history returns the usual error struct instead of a timetable, so check the type before using it:
With source="db" the server builds custom intervals (for example 2m, 3h, W, 2W, M, Q) from its stored 1 minute and daily candles.
Ticker Example
Historical candles for one symbol, straight from the broker, as JSON records or as plain text rows. history returns the same candles as a timetable and is usually the better choice for analysis in MATLAB; ticker is useful when you want the text rows, for example to write a file another program imports.
Ticker Response
With format="txt" a successful call returns the body as one character vector, one comma separated row per candle (Ticker,Date,Open,High,Low,Close,Volume, with the time after the date for intraday intervals). A failed call is the usual error struct, so test with ischar:
interval defaults to "D". The server limits the date range by interval: up to 10 years for D, W and M, and 30 days for intraday intervals.
Intervals Example
Intervals Response
client.interval() is the legacy name for the same call, kept for compatibility.
OptionChain Example
Note: To fetch the entire option chain for an expiry, omit the strike_count parameter.
OptionChain Response
Print one line per strike. A side that does not exist is null in the JSON, so it is empty in MATLAB:
Symbol Example
Symbol Response
Search Example
Search Response
exchange is optional; leave it out to search every exchange.
OptionSymbol Example
ATM Option:
OptionSymbol Response
ITM Option:
OptionSymbol Response
OTM Option:
OptionSymbol Response
The strategy and strike_int parameters of optionsymbol are deprecated: they are still sent when given, with an openalgo:deprecated warning.
SyntheticFuture Example
SyntheticFuture Response
OptionGreeks Example
OptionGreeks Response
Optional arguments: interest_rate (percent), forward_price (price against a custom forward instead of fetching the underlying), underlying_symbol, underlying_exchange and expiry_time ("HH:MM"). Leave any of them out (or []) and it is not sent.
MultiOptionGreeks Example
Implied volatility and Greeks (Black-76) for up to 50 options in one request, for example both legs of a straddle or a whole strike ladder. Use optiongreeks for a single option.
MultiOptionGreeks Response
The options can also be given as a struct array, one option per element:
Each option needs
symbolandexchange(NFO, BFO, CDS, MCX or CRYPTO);underlying_symbolandunderlying_exchangeare optional overrides.expiry_time="HH:MM"sets the expiry time for every option (for example"23:30"for MCX).The client checks the list before sending: 1 to 50 options. Otherwise it returns a
validation_errorstruct ('Symbols array cannot be empty','Maximum 50 symbols allowed') without calling the server.One option can fail while the rest succeed. The top-level
statusis then"partial"and the response is returned as is, so readsummaryand each item'sstatusrather than the top-level status alone. A failed item has different fields, which makesdataa cell array (see Reading responses). When every option fails the server answers"status": "error", which the client returns as anapi_errorstruct with the server's message.
Expiry Example
Expiry Response
response.data is an 18x1 cell array of character vectors.
Instruments Example
instruments returns a MATLAB table. 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
The columns are symbol, brsymbol, name, exchange, token, expiry, strike, lotsize, instrumenttype and tick_size; text columns are string arrays. With no exchange, client.instruments() downloads NSE, BSE, NFO, BFO, MCX, CDS, BCD, NSE_INDEX and BSE_INDEX and combines them into one table; an exchange that fails is skipped.
Telegram Alert Example
Telegram Alert Response
priority (1 to 10, default 5) marks how urgent the alert is. The username is your OpenAlgo login, not your Telegram handle, and the account must be linked with /link in the OpenAlgo Telegram bot. For a message over several lines, build it with sprintf: sprintf("Daily Summary\nWinning Trades: 8\nLosing Trades: 2").
WhatsApp Alert Example
Prerequisites: open /whatsapp in the OpenAlgo web UI, click Pair, and scan the QR code with your phone. With no recipient the message goes to yourself:
WhatsApp Alert Response
Other forms:
With wait_for_delivery=false the response is {"status": "success", "message": "Queued for 1 recipient(s)", "queued": 1}.
to as a list (a cell array, or a string array with more than one element) is always sent as a JSON array, even with one number (to={"919876543210"}).
A one-word message followed by exactly one more value is ambiguous in MATLAB: client.whatsapp("note", "x") reads as the extra field note="x" with no message. Name the message when it is a single word: client.whatsapp(message="Done", to="919876543210").
Telegram Bot Management Example
telegram sends you an alert. These methods manage the OpenAlgo Telegram bot itself: its configuration, starting and stopping it, the linked users and their preferences.
TelegramConfig Response
updatetelegramconfig, telegramstart and telegramstop answer with a status and a message, for example {"status": "success", "message": "Bot started successfully"}. updatetelegramconfig accepts token, webhook_url, polling_mode, broadcast_enabled and rate_limit_per_minute (1 to 120). telegramstart needs a bot token in the configuration ("Bot token not configured" otherwise). A stopped bot also stops the automatic order alerts, and telegram() is refused with HTTP 409 ("Telegram bot is stopped"). These endpoints answer an invalid or missing API key with HTTP 401.
TelegramUsers Response
TelegramStats Response
top_users mixes text and numbers, so it decodes to nested cell arrays: response.data.top_users{1}{1} is the handle and response.data.top_users{1}{2} the count.
TelegramPreferences Response
updatetelegrampreferences accepts order_notifications, trade_notifications, pnl_notifications, daily_summary, summary_time ("HH:MM"), language and timezone, and answers {"status": "success", "message": "Preferences updated successfully"}.
TelegramBroadcast Response
The current server validates a broadcast but does not deliver it yet, so it reports zero deliveries. A message can be up to 4096 characters (an empty or longer one is refused locally as a validation_error), the server allows 5 broadcasts per minute, and it refuses them (HTTP 403) when broadcasting is disabled in the bot configuration. filters (a struct) is passed through for user filtering.
Funds Example
Funds Response
Margin Example
Margin Response
positions must be a list of 1 to 50 positions. An empty list or more than 50 positions is refused before anything is sent, with error_type 'validation_error'. quantity, price and trigger_price are sent as text, and a missing price or trigger_price is sent as "0".
OrderBook Example
OrderBook Response
struct2table(response.data.orders) turns the orders into a table.
TradeBook Example
TradeBook Response
PositionBook Example
PositionBook Response
A list of records with the same fields is a struct array, which turns into a table in one line:
Holdings Example
Holdings Response
PnLSymbols Example
Today's realized and unrealized P&L of the open sandbox positions, one entry per symbol. It works only while analyzer (sandbox) mode is on; in live mode the server answers HTTP 400 ("This endpoint is only available in sandbox/analyzer mode").
PnLSymbols Response
Holidays Example
Holidays Response
Leave year out for the current year.
Timings Example
Timings Response
Times are epoch milliseconds. Leave date out for today. An empty data list means the market is closed that day. To convert a time:
Analyzer Status Example
Analyzer Status Response
Analyzer Toggle Example
Analyzer Toggle Response
Analyzer mode (sandbox mode) simulates orders instead of sending them to the broker, with sandbox capital, and responses then carry "mode": "analyze". client.analyzertoggle(false) switches back to live orders. Always confirm analyzer mode before running a test script against a broker-connected server. Simulated MARKET orders need a live price, so they fail while the market is closed; use LIMIT orders to test on holidays. GTT triggers placed in analyzer mode carry a GTT-... trigger id and fire against live LTP exactly as they would at the broker.
Chart Preferences Example
The chart workspace preferences OpenAlgo stores for your API key. Every name=value pair of updatechart is one preference; only the preferences you pass are changed.
UpdateChart Response
Chart Response
updatechart needs 1 to 50 preferences with names of at most 50 characters; anything else is returned as a validation_error struct without calling the server. Preference names that are not valid MATLAB names are renamed by jsondecode when you read them back with chart.
Error Handling
The client returns failures instead of raising them, so a trading loop handles a failed order the same way it handles a successful one. A failure is a struct with status 'error', a message and an error_type:
error_type
Cause
connection_error
The server could not be reached
timeout_error
The server did not answer within timeout seconds
http_error
A non-200 HTTP status ('HTTP 403: ...', with code) or another transport failure
api_error
The server answered "status": "error" (its message, plus code)
json_error
The server's answer was not valid JSON (with raw_response)
validation_error
Refused locally before sending (GTT trigger rules, margin positions, the option list of multioptiongreeks, the preferences of updatechart, the message of telegrambroadcast)
no_data
history or instruments returned nothing
processing_error
Candles or instruments could not be converted to a timetable or table (with raw_data)
unknown_error
Anything else, including a call after client.close()
For example, an invalid API key on ping:
A typical check:
history and instruments return a timetable or table on success, so test them with istimetable and istable first; ticker(format="txt") returns a character vector on success, so test it with ischar.
Programming mistakes are MATLAB errors, so they stop a script instead of reaching the broker. Each call below raises an error with the message shown under it:
(client.quotes("RELIANCE", "NSE") reads "RELIANCE" as a parameter name, so both required parameters are missing. Use client.quotes(symbol="RELIANCE", exchange="NSE").)
Every error has an identifier you can test in try/catch:
openalgo:missingArgument
A required parameter is missing
openalgo:unexpectedArgument
An unknown name on a method that takes no extra fields
openalgo:duplicateArgument
The same parameter is given twice
openalgo:invalidArguments
The argument list cannot be parsed (for example too many positional values)
openalgo:typeError
A value of the wrong kind, for example orders that is not a list
openalgo:valueError
An invalid value, for example openalgo.Strategy without a token
openalgo:clientClosed
send on a closed openalgo.Strategy
openalgo:notImplemented
The removed Strategy.strategyorder
openalgo:FeedAPI:badArgument, openalgo:FeedAPI:missingArgument
Wrong arguments to a feed method
Deprecated parameters (strike_int on the option methods and strategy on optionsymbol) still work and warn with the identifier openalgo:deprecated. Silence the warning with warning("off", "openalgo:deprecated").
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:
openalgo.api(api_key=...)
Your OpenAlgo API key
Lifecycle and reads: list, status, start, stop, close_all, close_leg, runs, orders, events
openalgo.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 library or on the server. Omitting it raisesopenalgo:missingArgument(strategystart() missing 1 required keyword-only argument: 'mode') rather than placing 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.
When the server answers with an HTTP error, the strategy methods return its JSON body with the status code attached as code, because that body holds the part you must act on:
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 empty ([], JSON 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. The keys of resolved_expiries are leg ids, which are not valid MATLAB names, so jsondecode renames them: leg 1 is response.run.resolved_expiries.x1.
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.
The response has the same shape as strategystop.
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(i).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 an empty 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. It is shown exactly once, in the browser, when the strategy is created or its token is rotated; no endpoint returns it. Treat it as a password, and keep it out of scripts you share (for example read it with getenv("OPENALGO_WEBHOOK_TOKEN")).
openalgo.Strategy speaks the webhook's protocol:
Webhook Start Response
Every documented outcome is returned, not raised, because the result label is the contract:
A signal that does nothing is a success with a note, not a failure: Signal accepted (already_long). The notes are already_long, already_short, no_matching_position, outside_entry_window and outside_trading_window. Reporting a no-op as a failure invites a retry, and a retry on an order path is how one alert becomes two positions. Being refused is different: a signal blocked by the strategy's direction, or naming a leg that does not exist, answers rejected_invalid_action with the engine's own message.
Other members of the webhook object:
openalgo.Strategy(host_url, webhook_id)also takes the token by position;webhook_token(name=value only) wins when both are given.timeout(name=value, default 30 seconds) sets the request timeout.s.signal(action, leg_id=..., symbol=..., exchange=...)sends any of the four signal actions by name, for examples.signal("long_entry", leg_id=1).s.send(payload)posts a raw struct.s.webhook_urlis the full URL. It embeds the token, so do not log it.s.close()releases the sender; a latersendraisesopenalgo:clientClosed.openalgo.Strategywith no token raisesopenalgo:valueError, ands.start()with no mode raisesopenalgo:missingArgument.s.strategyorder()was removed (the webhook it posted to no longer exists) and always raisesopenalgo:notImplemented, naming the replacements.Displaying the object never shows the token:
See the Strategy RMS API for every field of the nine strategy methods above.
Streaming WebSocket Feed
The feed streams live data from the OpenAlgo WebSocket server (port 8765 by default): LTP, full quotes, market depth, and the account's order updates.
MATLAB runs your code on one thread. The client reads the WebSocket from a MATLAB timer every 0.05 seconds, and your callbacks run on the main MATLAB thread:
At the command prompt the timer runs whenever MATLAB is idle, so data arrives and callbacks fire on their own after
client.connect().In a script or function, callbacks fire during
pause, sopause(10)keeps receiving data for ten seconds.client.wait(10)does the same and also runs a due reconnect attempt; use either one inmatlab -batchscripts. A long computation withoutpausedelays the feed until it finishes.Call
client.disconnect()when you are done. The feed timers hold a reference to the client until then.
Keep callbacks short, and do not call wait, connect, get_broker_info, get_supported_brokers or ws_ping from inside a callback. An error inside a callback is caught so the feed keeps running; it is logged as [ERROR] LTP callback error: ... at verbose=1 and is silent at verbose=0.
To make sure the feed is closed even when a script stops with an error or Ctrl+C, run it inside a function with an onCleanup object:
connect() returns true once the connection is authenticated. subscribe_* and unsubscribe_* return true when the request was sent and false otherwise (for example when not connected). Instruments are a cell array of structs or a struct array with exchange and symbol fields (struct("exchange", {"NSE", "NSE"}, "symbol", {"RELIANCE", "INFY"})); an exchange_token field is used as the symbol when symbol is empty.
Connecting to a Hosted Server (wss)
When OpenAlgo runs on your own domain behind HTTPS (a cloud server with a domain name and a TLS certificate), the WebSocket feed is served on the same domain at the path /ws, over secure WebSocket (wss://), not on port 8765. Give the client the https:// address and the feed URL follows from it:
host
Feed URL the client derives
http://127.0.0.1:5000
ws://127.0.0.1:8765 (ws_port sets the port)
https://yourdomain.com
wss://yourdomain.com/ws (ws_port is not used)
https://yourdomain.com:8443
wss://yourdomain.com:8443/ws
If your server serves the feed at a different address, pass ws_url; it always wins over host and ws_port:
For wss:// the library uses the first available TLS provider:
.NET on Windows (the default there). Nothing to install.
MATLAB's Python interface with Python 3.9 to 3.13, used on macOS and Linux. Point MATLAB at it once with
pyenv(Version="/usr/bin/python3.12").Java, when MATLAB runs with the JVM (the normal desktop and
-batchsessions; not-nojvm).
The server certificate and host name are always verified, with every provider. A local ws:// feed needs none of these. To force one provider, set client.tls_transport = "dotnet" (or "python", "java") before connect(). When none is available, connect() returns false and, at verbose=1, logs which options exist.
If your server's certificate comes from a private CA (not one the operating system trusts), give the client that CA as a PEM file before connect(). It is trusted in addition to the system trust store, and the host name is still checked:
LTP Data (Streaming Websocket)
Each LTP update passed to the callback is a struct; as JSON:
data.data also carries ltt (last trade time) when the server sends it.
Quotes (Streaming Websocket)
The quote data carries open, high, low, close, ltp, volume, last_trade_quantity, avg_trade_price, change, change_percent and timestamp.
Depth (Streaming Websocket)
(A local function such as onDepth goes at the end of the script file.)
The depth data carries ltp, timestamp and depth, where depth.buy and depth.sell are cell arrays of levels with price, quantity and orders. Five levels are requested by default.
Deeper Market Depth (20, 30 or 50 levels)
subscribe_depth takes a depth argument to request a deeper order book:
Which levels work (5, 20, 30 or 50) depends on your broker. With verbose=1 the subscription reply shows, per symbol, whether the broker accepted the level, and the reason when it refused:
The level is remembered per instrument, so an automatic reconnect replays each depth subscription with the level it was made with. get_depth returns every level received (buyBook and sellBook are 1x20 struct arrays in this example). A depth that is not a positive whole number raises openalgo:FeedAPI:badArgument before anything is sent.
Order Updates (Streaming Websocket)
Stream real-time order status changes (fills, partial fills, rejections and cancellations) into MATLAB through the OpenAlgo WebSocket feed. This is an account-level stream: unlike LTP, Quote and Depth there are no instruments to subscribe; one call covers every order in the connected broker account (and sandbox orders in analyzer mode).
subscribe_orders(on_order_update)
Start the stream; optional callback per update
unsubscribe_orders()
Stop the stream
get_orders()
Cached updates received so far, most recent first, capped at 500
subscribe_orders needs an authenticated connection, so call client.connect() first; it returns false if the client is not connected and authenticated. The subscription survives reconnects: auto reconnect replays it after re-authentication, like the market data subscriptions.
Each update passed to the callback is a struct in OpenAlgo's common order format, the same constants used by the REST order APIs; as JSON:
mode
live (broker feed) or analyze (sandbox engine)
action
BUY / SELL
pricetype
MARKET / LIMIT / SL / SL-M
product
CNC / NRML / MIS
order_status
open / trigger pending / complete / rejected / cancelled (plus broker extras)
rejection_reason
Populated when order_status is rejected
client.get_orders().orders returns the updates received so far as a cell array, most recent first: client.get_orders().orders{1}.order_status.
Notes:
Sandbox (analyzer mode) fires the same updates for order placements (open), engine fills, rejections and cancellations, so you can test end-to-end without a live broker.
Brokers with a push channel stream updates natively. Brokers with no push mechanism are covered by server-side order book polling (
ORDER_POLL_INTERVAL, default 5 seconds).On production deployments the
/postback/<broker>HTTPS webhook receivers feed the same stream. If both a broker WebSocket and a postback are configured the same transition can arrive twice, so deduplicate onorderid+order_status+filled_quantity.The stream is on by default. Set
ORDER_UPDATES_ENABLED=FALSEin the OpenAlgo server.envto disable it; no client-side flag is needed.With
verbose=2, each update is also printed with the[ORDER]log tag.
Polling Snapshots
Callbacks are optional. The client also keeps the latest value per instrument, which you can poll:
client.get_ltp(exchange, symbol)
r.ltp.NSE.RELIANCE with fields timestamp, ltp
client.get_quotes(exchange, symbol)
r.quote.NSE.RELIANCE with fields timestamp, open, high, low, close, ltp, volume, last_trade_quantity, avg_trade_price, change, change_percent
client.get_depth(exchange, symbol)
r.depth.NSE.SBIN with fields timestamp, ltp, buyBook, sellBook; each book is a 1xN struct array (N at least 5, more when a deeper book was received) with price, qty, orders, and buyBook(1) is the best bid
client.get_orders()
r.orders, a cell array of order updates, most recent first
exchange and symbol are optional filters, by position or name=value (client.get_ltp(exchange="NSE", symbol="RELIANCE")). Without data the result is empty (struct('ltp', struct())).
MATLAB field names must be valid identifiers, so exchange and symbol names pass through matlab.lang.makeValidName: M&M becomes M_M, BAJAJ-AUTO becomes BAJAJ_AUTO, and a name that starts with a digit gets an x prefix. The raw data is also kept under the original 'EXCHANGE:SYMBOL' key in client.ltp_data, client.quotes_data and client.depth_data (containers.Map objects), for example client.ltp_data("NSE:M&M").price.
Feed Utilities
client.wait(seconds)
Keep processing the feed for a number of seconds (default 1), for scripts
client.unsubscribe_all()
Drop every LTP, quote and depth subscription in one request
client.get_broker_info(timeout)
Ask which broker serves this feed session (default timeout 5 seconds)
client.get_supported_brokers(timeout)
Ask which brokers the server is configured for
client.ws_ping(timeout)
Measure the round trip to the feed server, in milliseconds
The replies, as JSON:
unsubscribe_allforgets every LTP, quote and depth subscription and clears the cached data, so an automatic reconnect does not replay them. The order-update stream is not affected; stop it withunsubscribe_orders. It returnstruewhen the request was sent.get_broker_info,get_supported_brokersandws_pingwait up totimeoutseconds for the server's reply. While they wait the feed keeps running, so market data keeps arriving and callbacks keep firing. Do not call them from inside a feed callback. Without a connection, or without a reply in time, they return a struct withstatus'error'and amessage('Not connected to WebSocket server','Timed out waiting for the broker_info reply'); a server error reply (for example"code": "NOT_AUTHENTICATED") is returned as is.countin the supported brokers reply is the number of brokers enabled on the server.latency_msin thews_pingreply is added by the client: the measured round trip in milliseconds. The method is calledws_pingbecausepingis the REST endpoint.
Websockets (Verbose Control)
The verbose parameter controls the library's logging for the WebSocket feed (LTP, Quote, Depth and order updates), from silent to full debug.
Silent
false or 0
No library output, not even errors (default)
Basic
true or 1
Connection, authentication, subscription and unsubscribe replies, server error frames and other error messages
Debug
2
Everything in Basic, plus every LTP, Quote, Depth and order update and the full server replies
verbose only controls what the library prints. Your callbacks always run, and every method still returns its result, so a silent client is not a blind one. Set verbose=1 while you are wiring up a feed: at level 0 a failed authentication or a rejected subscription is silent. client.verbose can also be changed on a live client.
ws_url is optional. When it is omitted the client derives the WebSocket URL from host, so a local install can simply use openalgo.api(api_key="...", verbose=2).
Sample output with verbose=true:
Unsubscribe acknowledgements (one line per symbol) and error frames sent by the server are shown at the same level:
unsubscribe_all() logs [UNSUB] Unsubscribing from all symbols, followed by one acknowledgement line per symbol that was dropped.
With verbose=2 each update is printed as well, for example [LTP] NSE:RELIANCE | LTP: 1424.5 and [QUOTE] NSE:INFY | O: 1532.1 H: 1560.3 L: 1532.1 C: 1530.6 LTP: 1557.9, and each depth update is followed by a table of the book:
[WS]
WebSocket connection events
[AUTH]
Authentication requests and responses
[SUB]
Subscription operations
[UNSUB]
Unsubscription logs
[LTP]
LTP updates (verbose=2)
[QUOTE]
Quote updates (verbose=2)
[DEPTH]
Market depth updates (verbose=2)
[ORDER]
Order status updates via subscribe_orders() (verbose=2)
[ERROR]
Error messages (verbose=1 and above)
Auto Reconnect
auto_reconnect defaults to true. After a dropped connection the client reconnects with increasing delays (1, 2, 5, 10, 30, then 60 seconds), re-authenticates, and replays every active LTP, Quote and Depth subscription plus the order-update subscription. Your callbacks are kept, so they resume firing without extra code. The reconnect attempts run on a MATLAB timer, so they happen while MATLAB is idle, during pause or during client.wait. disconnect() is a graceful shutdown and does not reconnect.
With verbose=1 or higher the reconnect attempts and the replayed subscriptions are logged under the [WS] and [SUB] tags:
The client also sends a WebSocket keepalive ping every 20 seconds and treats the connection as dropped when no pong arrives within 10 seconds. Change these through client.ping_interval and client.ping_timeout before connect() if needed.
Last updated