00Overview
Meridian talks to Angel One through SmartAPI, Angel One's free REST and WebSocket API for account holders. The flow has three layers:
- Meridian account: you sign in to this platform with your email and password.
- Integration (one-time): you save your SmartAPI API key, client code, static IP and, optionally, your TOTP secret. These are encrypted at rest.
- Daily session: each trading day you connect with your MPIN and a TOTP code. Angel One returns a JWT (for REST), a refresh token and a feed token (for streaming).
Browser ──► Meridian (api.php) ──► https://apiconnect.angelone.in (REST: login, orders, books, quotes, candles)
│
└──────────────────────────────► wss://smartapisocket.angelone.in/smart-stream (live ticks, feed token)
REST calls go through the Meridian server, so your API key and JWT never reach browser JavaScript. The only exception is the WebSocket, which the browser opens directly with the feed token for the lowest latency.
01Prerequisites
- An active Angel One trading and demat account, with your client code (e.g.
A123456) and 4-digit MPIN. - A smartphone authenticator app: Google Authenticator, Microsoft Authenticator or Authy.
- For placing orders: a static public IP for the machine running Meridian (see step 03).
- This server: PHP 8.0+ with the
curl,opensslandpdo_sqlite(orpdo_mysql) extensions. XAMPP ships all of them.
02Create a SmartAPI app
- Open smartapi.angelbroking.com and Sign up / Log in with your Angel One client code.
- Go to My Apps → Create an App.
- Choose the app type Trading APIs. Give it a name (e.g. Meridian).
- Redirect URL: any valid URL works for Meridian, because it uses the direct (MPIN + TOTP) login, not the redirect flow. Use
http://localhost/trading/connect.php. - Postback URL: optional; leave empty.
- Enter your static IP if asked (see next step), then create the app.
- Copy the API Key shown for the app. That is the value Meridian needs. You do not need the "Secret Key" for this login flow.
Historical candle data (getCandleData) is served on the same Trading API key for most accounts. If charts return an access error, open your app in the SmartAPI dashboard and check that historical data is enabled for it.
03Register a static IP
Under SEBI's framework for retail algorithmic trading, brokers require API orders to come from a whitelisted static IP. Angel One enforces this in the SmartAPI app settings. Market data and account reads may work from any IP, but order placement from an unregistered IP is rejected.
- Get a static IP: from your ISP (business / static plan), or host Meridian on a cloud VM with a reserved IP (AWS Elastic IP, a DigitalOcean reserved IP and so on).
- In Meridian's Integration page, click Detect this server's IP. That is the IP Angel One will see.
- Enter that exact IP in your SmartAPI app (My Apps → edit app → IP field) and in Meridian's static IP field.
On a home connection without a static plan your IP changes periodically, and orders will start failing when it does. If you can't get a static IP, use Meridian for analysis and place orders in the Angel One app.
04Enable TOTP
SmartAPI logins need a time-based one-time password (TOTP) in addition to the MPIN.
- Open smartapi.angelbroking.com/enable-totp.
- Enter your client code and MPIN (or password), then the OTP sent to your registered mobile / email.
- A QR code appears, with a text secret underneath it (letters A–Z and digits 2–7).
- Scan the QR code with your authenticator app. It now shows a 6-digit code that changes every 30 seconds.
- Optional: copy the text secret into Meridian's Generate TOTP codes automatically field. Meridian then generates codes itself, and connecting only needs your MPIN.
Anyone holding the TOTP secret and your MPIN can log in to your account. Save the secret only on a server you control, and keep data/app.key (the encryption key) private.
If codes are rejected, check that the phone's (or server's) clock is synced to network time. TOTP codes are valid only within their 30-second window.
05Connect in Meridian
- Create a Meridian account (or sign in).
- On the Integration page, in Step 1, enter your client code, API key and static IP, plus the TOTP secret if you want codes generated automatically. Click Save & continue.
- In Step 2, enter your MPIN and the current 6-digit TOTP. Click Connect & open terminal.
- The terminal opens. The status pill in the top bar shows Live when the WebSocket feed is streaming, or Polling when it falls back to REST quotes.
- Place a small test order first (e.g. 1 share of a liquid stock with a LIMIT price away from market) and cancel it, to confirm order permissions and IP whitelisting.
06Session lifecycle
| Token | Used for | Lifetime / handling |
|---|---|---|
jwtToken | Authorization: Bearer … on every REST call | Valid for the trading day. Meridian refreshes it automatically once if Angel One reports it expired. |
refreshToken | generateTokens to obtain a new JWT | Same day. Stored only in the PHP session. |
feedToken | WebSocket authentication | Same day. Sent to your browser for the stream. |
Sessions end daily, so connect again each trading day. Disconnect in the terminal calls Angel One's logout API and clears the tokens. Sign out also ends your Meridian session.
07Required headers
Every SmartAPI REST request carries these headers. Meridian sets them in lib/SmartApi.php.
| Header | Value |
|---|---|
Content-Type / Accept | application/json |
X-UserType | USER |
X-SourceID | WEB |
X-ClientLocalIP | Server LAN IP (config local_ip, default: server address) |
X-ClientPublicIP | Your static IP (Integration page, or config public_ip) |
X-MACAddress | Server MAC (config mac_address) |
X-PrivateKey | Your SmartAPI API key |
Authorization | Bearer <jwtToken> (all endpoints except login) |
Base URL: https://apiconnect.angelone.in. Responses are JSON: {"status": true, "message": "SUCCESS", "errorcode": "", "data": …}.
08Authentication APIs
| Purpose | Endpoint | Meridian action |
|---|---|---|
| Login | POST /rest/auth/angelbroking/user/v1/loginByPassword | connect |
| Refresh JWT | POST /rest/auth/angelbroking/jwt/v1/generateTokens | automatic |
| Profile | GET /rest/secure/angelbroking/user/v1/getProfile | profile |
| Logout | POST /rest/secure/angelbroking/user/v1/logout | disconnect |
Login request
POST /rest/auth/angelbroking/user/v1/loginByPassword
{
"clientcode": "A123456",
"password": "1234", // your MPIN
"totp": "482913" // current 6-digit TOTP
}
// response.data
{ "jwtToken": "eyJhbGciOi…", "refreshToken": "eyJhbGciOi…", "feedToken": "eyJhbGciOi…" }
09Order APIs
| Purpose | Endpoint | Meridian action |
|---|---|---|
| Place order | POST /rest/secure/angelbroking/order/v1/placeOrder | place |
| Modify order | POST /rest/secure/angelbroking/order/v1/modifyOrder | modify |
| Cancel order | POST /rest/secure/angelbroking/order/v1/cancelOrder | cancel |
| Order book | GET /rest/secure/angelbroking/order/v1/getOrderBook | orders |
| Trade book | GET /rest/secure/angelbroking/order/v1/getTradeBook | trades |
Place a limit order
{
"variety": "NORMAL",
"tradingsymbol": "SBIN-EQ",
"symboltoken": "3045",
"transactiontype": "BUY",
"exchange": "NSE",
"ordertype": "LIMIT",
"producttype": "INTRADAY",
"duration": "DAY",
"price": "805.50",
"triggerprice": "0",
"squareoff": "0",
"stoploss": "0",
"quantity": "1"
}
// response.data → { "orderid": "241105000123456", "uniqueorderid": "…", "script": "SBIN-EQ" }
Cancel takes {"variety": "NORMAL", "orderid": "…"}. Modify takes the full order fields plus orderid.
10Order parameters
| Field | Values |
|---|---|
variety | NORMAL regular · STOPLOSS SL orders · AMO after-market · ROBO bracket |
transactiontype | BUY · SELL |
ordertype | MARKET · LIMIT · STOPLOSS_LIMIT · STOPLOSS_MARKET |
producttype | DELIVERY cash CNC · INTRADAY MIS · CARRYFORWARD F&O NRML · MARGIN · BO |
duration | DAY · IOC |
exchange | NSE · BSE · NFO · BFO · MCX · CDS · NCDEX |
- Stop-loss orders need
variety: STOPLOSSand atriggerprice. Meridian sets the variety for you. - F&O quantities must be multiples of the contract's lot size (see the scrip master's
lotsize). - Prices must align to the instrument's tick size (usually ₹0.05 for equities).
11Portfolio & funds
| Purpose | Endpoint | Meridian action |
|---|---|---|
| Positions | GET /rest/secure/angelbroking/order/v1/getPosition | positions |
| Holdings (with totals) | GET /rest/secure/angelbroking/portfolio/v1/getAllHolding | holdings |
| Funds & margin (RMS) | GET /rest/secure/angelbroking/user/v1/getRMS | funds |
Empty books come back as "data": null. Meridian normalises them to empty lists.
12Market data APIs
| Purpose | Endpoint | Meridian action |
|---|---|---|
| Quotes (LTP / OHLC / FULL with depth) | POST /rest/secure/angelbroking/market/v1/quote/ | quote |
| Historical candles | POST /rest/secure/angelbroking/historical/v1/getCandleData | candles |
| Symbol search | POST /rest/secure/angelbroking/order/v1/searchScrip | search |
Quote
{ "mode": "FULL", "exchangeTokens": { "NSE": ["3045", "2885"], "NFO": ["43650"] } }
// up to 50 tokens per call · FULL adds depth.buy[5] / depth.sell[5], 52-week high/low, total buy/sell qty
Candles
{ "exchange": "NSE", "symboltoken": "3045", "interval": "FIVE_MINUTE",
"fromdate": "2026-11-01 09:15", "todate": "2026-11-05 15:30" }
// data: [[ "2026-11-05T09:15:00+05:30", open, high, low, close, volume ], …]
Intervals: ONE_MINUTE, THREE_MINUTE, FIVE_MINUTE, TEN_MINUTE, FIFTEEN_MINUTE, THIRTY_MINUTE, ONE_HOUR, ONE_DAY. Each interval has a maximum date range per request (short for 1-minute, years for daily). Meridian requests 4 days of 1-minute data, 15 days of 5-minute, 40 days of 15-minute, 120 days of hourly and 2 years of daily candles.
13WebSocket streaming (v2)
Live ticks come from wss://smartapisocket.angelone.in/smart-stream. Browsers can't set custom headers on a WebSocket, so authentication goes in the query string:
wss://smartapisocket.angelone.in/smart-stream?clientCode=A123456&feedToken=<feedToken>&apiKey=<apiKey>
Subscribe
{
"correlationID": "abc123", // any 10-char id, echoed back on errors
"action": 1, // 1 = subscribe, 0 = unsubscribe
"params": {
"mode": 2, // 1 LTP · 2 Quote · 3 SnapQuote (with depth)
"tokenList": [ { "exchangeType": 1, "tokens": ["3045", "2885"] } ]
}
}
| exchangeType | Segment |
|---|---|
1 | NSE cash (nse_cm) |
2 | NSE F&O (nse_fo) |
3 | BSE cash (bse_cm) |
4 | BSE F&O (bse_fo) |
5 | MCX F&O |
7 | NCDEX |
13 | Currency (cde_fo) |
Binary tick layout (little-endian)
| Bytes | Field | Type |
|---|---|---|
| 0 | Subscription mode | uint8 |
| 1 | Exchange type | uint8 |
| 2–26 | Token (null-terminated ASCII) | char[25] |
| 27–34 | Sequence number | int64 |
| 35–42 | Exchange timestamp (epoch ms) | int64 |
| 43–50 | Last traded price (paise) | int64 |
| 51–58 | Last traded qty (Quote mode +) | int64 |
| 59–66 | Average traded price | int64 |
| 67–74 | Volume traded today | int64 |
| 75–82 / 83–90 | Total buy / sell quantity | double |
| 91–98 / 99–106 / 107–114 / 115–122 | Open / High / Low / Close (paise) | int64 |
Divide prices by 100 (by 10,000,000 for currency). Send the text ping every ~30 s to keep the socket alive; the server replies pong. The parser is in assets/js/feed.js. If the socket can't connect, Meridian falls back to REST polling and keeps retrying the socket with backoff.
14Symbol tokens
Every instrument is addressed by a numeric symbol token plus its exchange. Meridian's search box uses searchScrip, so you rarely need tokens by hand. For bulk lookups, download Angel One's scrip master (a large JSON file, refreshed daily):
https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json
// [{ "token": "3045", "symbol": "SBIN-EQ", "name": "SBIN", "expiry": "", "strike": "-1.000000",
// "lotsize": "1", "instrumenttype": "", "exch_seg": "NSE", "tick_size": "5.000000" }, …]
| Instrument | Exchange | Token |
|---|---|---|
| Nifty 50 index | NSE | 99926000 |
| Nifty Bank index | NSE | 99926009 |
| Nifty Fin Service index | NSE | 99926037 |
| Sensex index | BSE | 99919000 |
| SBIN-EQ | NSE | 3045 |
| RELIANCE-EQ | NSE | 2885 |
Indices are for data only; they can't be traded. F&O tokens change with every expiry, so look them up again each series.
15Rate limits
SmartAPI throttles each endpoint per second, per minute and per hour. Exceeding a limit returns HTTP 403 / "Access denied because of exceeding access rate". Angel One revises these numbers, so check the Rate Limits page in the SmartAPI docs. Meridian stays well below them:
- Watchlist and indices stream over one WebSocket. REST polling (every 2.5 s, up to 50 tokens per call) runs only as a fallback.
- Market depth polls a single symbol every 2.5 s, and only while the tab is visible.
- Positions and orders refresh every 6 s, funds every 20 s.
- Symbol search is debounced (260 ms) and needs at least 2 characters.
16Errors & troubleshooting
| Symptom / code | Cause | Fix |
|---|---|---|
AB1050 Invalid totp and client combination | Wrong client code, or the TOTP is expired / out of sync | Check the client code and use a fresh code. Sync the phone or server clock. If you saved a secret, re-check it. |
AG8001 / AG8002 Invalid / expired token | JWT expired (daily) or revoked | Meridian refreshes once automatically. If that fails, reconnect on the Integration page. |
| Invalid API key / "Unexpected response (HTTP 403)" | Wrong key, app disabled, rate limit, or IP not whitelisted | Copy the API key again from My Apps. Confirm the static IP matches Detect this server's IP. Slow down requests. |
| Orders rejected, data works | Static IP not registered or changed | Update the IP in the SmartAPI app and in Meridian. |
| Rejected: lot size / tick size / price band | Exchange validation | Use lot multiples, tick-aligned prices, and prices within the circuit limits. |
| "Could not reach Angel One: SSL certificate problem" | PHP has no CA bundle | Set curl.cainfo in php.ini to C:\xampp\apache\bin\curl-ca-bundle.crt. |
| Status pill stays Polling | WebSocket blocked by firewall / proxy, or feed token invalid | Allow outbound wss://smartapisocket.angelone.in:443, then reconnect. |
| Charts empty after market hours | No candles in the requested window (weekend / holiday) | Switch to 1D or a longer interval. |
17Security checklist
- Encryption at rest: API keys and TOTP secrets are encrypted with AES-256-GCM using
data/app.key. Back that file up and never commit it; losing it means re-entering credentials. - Passwords: Meridian passwords are bcrypt-hashed. Sign-in locks for 15 minutes after 5 failures.
- MPIN: sent to Angel One at connect time and never stored.
- Web access:
.htaccessblocksconfig.php,lib/,data/andbin/. Every state-changing request needs a CSRF token. - Registration: set
'allow_registration' => falseinconfig.phponce your accounts exist. - HTTPS: required anywhere beyond
localhost. Session cookies are markedSecureautomatically over HTTPS.
18Going to production
- Host on a VM with a reserved static IP, and register that IP in your SmartAPI app.
- Serve over HTTPS (e.g. Apache + Let's Encrypt), and redirect HTTP to HTTPS.
- Use MySQL if you prefer: set
db_dsn,db_useranddb_passinconfig.php. Tables are created automatically. - Set a fixed
app_keyinconfig.php(32 random bytes, base64) so encrypted data survives redeploys. - Disable registration, and create users from the command line with
php bin/create-user.php. - Keep the server clock on NTP (needed for automatic TOTP).
- Test with the smallest possible quantities before trading normally.
# generate a production app_key
php -r "echo base64_encode(random_bytes(32)), PHP_EOL;"
# create a user from the command line
php bin/create-user.php "Your Name" you@example.com