R
The OpenAlgo R SDK lets you trade through your OpenAlgo server from R, RStudio or a scheduled Rscript job: place and manage orders, read positions and funds, pull historical candles straight into a data.frame, work with option chains and Greeks, run the strategy module, and stream live prices and order updates.
To install the OpenAlgo R library from CRAN:
install.packages("openalgo")The package is under CRAN review right now. Until it is listed on CRAN, install it from GitHub:
install.packages("remotes")
remotes::install_github("marketcalls/openalgo-R-library")It needs R 4.1 or newer. The packages it depends on (R6, curl, jsonlite, websocket and later) are installed automatically.
Source code: https://github.com/marketcalls/openalgo-R-library
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
First, load the OpenAlgo library and create a client with your API key:
library(openalgo)
# 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:
host(character): base URL of your OpenAlgo server. REST calls go to{host}/api/{version}/.version(character): API version. Defaults to"v1".timeout(numeric): REST request timeout in seconds. Defaults to120.ws_port(numeric): WebSocket port. Defaults to8765.ws_url(character): full WebSocket URL. Overrideshostandws_port. When omitted it is derived fromhost:http://127.0.0.1:5000givesws://127.0.0.1:8765, and a hosted server such ashttps://yourdomain.comgiveswss://yourdomain.com/ws. A local install or a hosted server needs nows_urlat all. See Connecting to a Hosted Server.verbose(logical or numeric): SDK log level for the WebSocket feed.FALSE/0silent,TRUE/1basic,2full debug. See Websockets (Verbose Control).auto_reconnect(logical): defaults toTRUE. The SDK reconnects, re-authenticates and replays every active subscription after a drop, with backoff. Set toFALSEfor manual reconnect handling.
Every method is called on the client with $, and every argument is passed by name, for example client$quotes(symbol = "RELIANCE", exchange = "NSE"). An unnamed argument is refused with extra arguments must be named (they are sent as payload fields). Extra named arguments are sent to the server as additional fields, so optional API parameters such as price, trigger_price or disclosed_quantity are passed straight through.
A JSON object is written as a named list:
list(symbol = "RELIANCE", exchange = "NSE").A JSON array of objects is a list of named lists:
list(list(...), list(...)).true/false/nullareTRUE/FALSE/NULL.Numbers can be passed as numbers. Fields the server expects as strings are converted for you, and whole numbers are sent without a decimal point (
1is sent as"1",16.5as"16.5"). Decimal prices are sent with full precision, so1180.05reaches the server as1180.05.Pass order ids as strings. They are longer than R can hold exactly as a number.
Printing the client never shows your API key:
The client keeps a pooled HTTP connection open. Call client$close() when you are done with it.
Every method has its own R help page with its arguments, return value and examples: ?api lists every method, and ?placeorder, ?history, ?subscribe_ltp or ?Strategy open one topic.
Check OpenAlgo Version
Reading Responses
Every REST method returns the server's JSON response as a named list, so fields are read with $:
The examples below show each response as the JSON the server returns, because it is shorter to read. The R value has exactly the same structure: JSON objects are named lists, JSON arrays are unnamed lists, and null is NULL. To see an R response as JSON, use cat(jsonlite::toJSON(response, auto_unbox = TRUE, pretty = TRUE, null = "null")).
history() and instruments() return a data.frame instead of a list.
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 Condor options order (Same Expiry)
Place OptionsMultiOrder Response
To place Diagonal Spread options order (Different Expiry), give each leg its own expiry_date:
Place OptionsMultiOrder Response
Check each leg's result rather than only the top-level status:
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
The quantity comes back as a string, as the server sends it. Use as.numeric(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. 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
MultiQuotes Response
Depth Example
Depth Response
History Example
Download Data Directly from Broker API
Download Data Directly from Historify DuckDB (Stored Data)
History Response
history() returns a data.frame with timestamp as its first column. It is a POSIXct in the Asia/Kolkata time zone for intraday intervals, and in UTC for D, W and M (so the date is the trading date the server sent). Rows are sorted by time, duplicate timestamps are dropped and row names run from 1.
When something goes wrong, history() returns the usual error list instead of a data frame, 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. Use history() when you want a data.frame for analysis, and ticker() 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 string, 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 list, so test with is.character():
The server limits the date range by interval: up to 10 years for D, W and M, and 30 days for intraday intervals. API reference: Ticker.
Intervals Example
Intervals Response
client$interval() is an older name for the same call and still works.
OptionChain Example
Note: To fetch the entire option chain for an expiry, omit the strike_count (optional) parameter
OptionChain Response
Print one line per strike:
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
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 NULL) and it is not sent.
MultiOptionGreeks Example
Implied volatility and Greeks 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 data frame, one option per row:
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, each with a
symboland anexchange. Otherwise it returns avalidation_errorlist without calling the server.One option can fail while the rest succeed. The top-level
statusis then"partial", so readsummaryand each item'sstatusrather than the top-level status alone. When every option fails the server answers"status": "error", which the client returns as anapi_errorlist with the server's message.
API reference: MultiOptionGreeks.
Expiry Example
Expiry Response
Instruments Example
instruments() returns a data.frame. 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.
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.
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. A stopped bot also stops the automatic order alerts and refuses telegram() notifications.
TelegramUsers Response
TelegramStats Response
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, the server allows 5 broadcasts per minute, and it refuses them (HTTP 403) when broadcasting is disabled in the bot configuration. filters (a named list) is passed through for user filtering.
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.
One 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
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, not uploaded by the call. It must lie under the server's attachment roots (by default db/attachments/ in the OpenAlgo folder).
Send a document (PDF, CSV, ...)
Fire-and-forget (skip the delivery report)
With wait_for_delivery = FALSE the response is {"status": "success", "message": "Queued for 1 recipient(s)", "queued": 1}.
Send to a linked OpenAlgo user
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 list with code = 403. A simple pre-flight check:
Funds Example
Funds Response
Margin Example
Margin Response
positions must be an unnamed 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".
OrderBook Example
OrderBook Response
TradeBook Example
TradeBook Response
PositionBook Example
PositionBook Response
A list of records turns into a data frame in one line when every record has the same fields:
Holdings Example
Holdings 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:
Chart Preferences Example
The chart workspace preferences OpenAlgo stores for your API key. Every named argument 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 list without calling the server.
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(mode = 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.
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
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. Omitting it is an R error (argument "mode" is missing, with no default) rather 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.
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 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.
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 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. It is shown exactly once, in the browser, when the strategy is created or its token is rotated. Treat it as a password, and keep it out of scripts you share (for example read it with Sys.getenv("OPENALGO_WEBHOOK_TOKEN")). The SDK's Strategy() object speaks its protocol:
Strategy Webhook Response
A signal names its leg by leg_id, or by symbol and exchange; leg_id wins when both are given. 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:
strategy$signal(action, leg_id = , symbol = , exchange = )sends any of the four signal actions by name.strategy$send(payload)posts a raw named list.strategy$webhook_urlis the full URL. It embeds the token, so do not log it.strategy$close()releases the pooled connection.Printing the object never shows the token:
Strategy(host_url='http://127.0.0.1:5000', webhook_token=<redacted>).
See the Strategy RMS API for every field of the methods above.
WebSocket Feed in R
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.
The feed runs on the R event loop (the later package), and your callbacks run on the main R thread:
In the interactive console (R or RStudio) the loop runs whenever the console is idle, so data arrives and callbacks fire on their own after
client$connect().In a script (
Rscript, a scheduled job) the loop only advances while it is pumped. Callclient$wait(seconds)to keep the script receiving data for that many seconds.connect()and theget_*()snapshot methods also pump the loop briefly.
Do not call client$wait() or client$connect() from inside a feed callback; the loop cannot be pumped from there. Keep callbacks short.
Instruments are a list of named lists, as in the examples below. A single named list, or a data frame with exchange and symbol columns, works too. subscribe_*() and unsubscribe_*() return TRUE when the request was sent and FALSE otherwise (for example when not connected). connect() returns TRUE once the connection is authenticated.
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 automatically:
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:
LTP Data (Streaming Websocket)
LTP Update
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)
The depth data carries ltp, timestamp and depth, where depth$buy and depth$sell are lists of levels with price, quantity and orders. Five levels are requested by default.
Market Depth Levels (5, 20, 30 or 50)
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, the level the broker actually serves, or the reason 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 (books keyed "1" to "20" in this example). A depth that is not a positive whole number is refused locally: subscribe_depth() returns FALSE and logs the reason.
Order Updates (Streaming Websocket)
Stream real-time order status changes (fills, partial fills, rejections and cancellations) directly into your R strategy. 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 analyze mode).
client$subscribe_orders(on_order_update)
Start the stream; optional callback per update
client$unsubscribe_orders()
Stop the stream
client$get_orders()
Cached updates received so far, most recent first, capped at 500
Both calls require an authenticated connection, so call client$connect() first; subscribe_orders() returns FALSE if the client is not connected and authenticated. The subscription survives reconnects: auto-reconnect replays it after re-authentication, exactly like market data subscriptions.
Order Update
Each callback receives OpenAlgo's common order format, the same constants used by the REST order APIs:
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 (+ broker extras)
rejection_reason
Populated when order_status is rejected
client$get_orders()$orders returns the updates received so far, newest first.
Sandbox (analyze 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 orderbook polling (
ORDER_POLL_INTERVAL, default 5 seconds).If both a broker WebSocket and a postback are configured on the server, the same transition can arrive twice, so deduplicate on
orderid+order_status+filled_quantity.Set
ORDER_UPDATES_ENABLED=FALSEin the OpenAlgo server.envto disable the whole stream; it isTRUEby default, and 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 = NULL, symbol = NULL)
list(ltp = list(NSE = list(RELIANCE = list(timestamp, ltp))))
client$get_quotes(exchange = NULL, symbol = NULL)
list(quote = list(NSE = list(RELIANCE = list(timestamp, open, high, low, close, ltp, volume, ...))))
client$get_depth(exchange = NULL, symbol = NULL)
list(depth = list(NSE = list(SBIN = list(timestamp, ltp, buyBook, sellBook)))), each book keyed "1" to "5" (or up to the number of levels received, such as "20") with price, qty, orders
client$get_orders()
list(orders = list(...)), most recent first
Feed Utilities
client$unsubscribe_all()
Drop every LTP, quote and depth subscription in one request
client$get_broker_info(timeout = 5)
Ask which broker serves this feed session
client$get_supported_brokers(timeout = 5)
Ask which brokers the server is configured for
client$ws_ping(timeout = 5)
Measure the round trip to the feed server, in milliseconds
client$wait(seconds = 1)
Keep a script receiving data for that many seconds
Feed Utilities Response
unsubscribe_all()forgets 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; the local subscriptions are cleared even when it could not be sent.get_broker_info(),get_supported_brokers()andws_ping()wait up totimeoutseconds for the server's reply. While they wait the event loop keeps running, so market data keeps arriving and callbacks keep firing. Do not call them from inside a feed callback. Without a connection they return aconnection_errorlist, without a reply in time atimeout_errorlist, and 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_ping()reply is the round trip measured by the client, in milliseconds. The method is calledws_ping()becauseping()is the REST endpoint.
Websockets (Verbose Control)
The verbose argument of api() manages SDK-level logging for WebSocket feed operations (LTP, Quote, Depth and order updates).
Silent
FALSE or 0
No SDK 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
verbose only controls what the SDK prints. Your own 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.
Sample Output with verbose = TRUE
Unsubscribe acknowledgements and server error frames are printed at the same level:
Sample Output with verbose = 2
Everything above, plus the full server replies and one line per update:
Log Categories
[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 backoff (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 any extra code. The reconnect timers run on the same event loop, so a script must keep calling 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.
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 named list 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 or a transport failure (with code where known)
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())
no_data
history() or instruments() returned nothing
processing_error
Candles or instruments could not be converted to a data frame (with raw_data)
unknown_error
Anything else
A typical check:
Programming mistakes, such as a missing required argument or an unnamed one, are R errors, so they stop a script instead of reaching the broker:
Wrap a call in tryCatch() if a script must survive such a mistake.
Last updated