Meridian
Integration guide

Integrating the Angel One SmartAPI

Everything you need to go from an Angel One account to live trading in Meridian: account setup, then a reference for every API the platform uses.

00Overview

Meridian talks to Angel One through SmartAPI, Angel One's free REST and WebSocket API for account holders. The flow has three layers:

  1. Meridian account: you sign in to this platform with your email and password.
  2. Integration (one-time): you save your SmartAPI API key, client code, static IP and, optionally, your TOTP secret. These are encrypted at rest.
  3. 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, openssl and pdo_sqlite (or pdo_mysql) extensions. XAMPP ships all of them.

02Create a SmartAPI app

  1. Open smartapi.angelbroking.com and Sign up / Log in with your Angel One client code.
  2. Go to My Apps → Create an App.
  3. Choose the app type Trading APIs. Give it a name (e.g. Meridian).
  4. 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.
  5. Postback URL: optional; leave empty.
  6. Enter your static IP if asked (see next step), then create the app.
  7. 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.
i

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.

  1. 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).
  2. In Meridian's Integration page, click Detect this server's IP. That is the IP Angel One will see.
  3. 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.

  1. Open smartapi.angelbroking.com/enable-totp.
  2. Enter your client code and MPIN (or password), then the OTP sent to your registered mobile / email.
  3. A QR code appears, with a text secret underneath it (letters A–Z and digits 2–7).
  4. Scan the QR code with your authenticator app. It now shows a 6-digit code that changes every 30 seconds.
  5. 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

  1. Create a Meridian account (or sign in).
  2. 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.
  3. In Step 2, enter your MPIN and the current 6-digit TOTP. Click Connect & open terminal.
  4. 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.
  5. 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.
Create account →

06Session lifecycle

TokenUsed forLifetime / handling
jwtTokenAuthorization: Bearer … on every REST callValid for the trading day. Meridian refreshes it automatically once if Angel One reports it expired.
refreshTokengenerateTokens to obtain a new JWTSame day. Stored only in the PHP session.
feedTokenWebSocket authenticationSame 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.

HeaderValue
Content-Type / Acceptapplication/json
X-UserTypeUSER
X-SourceIDWEB
X-ClientLocalIPServer LAN IP (config local_ip, default: server address)
X-ClientPublicIPYour static IP (Integration page, or config public_ip)
X-MACAddressServer MAC (config mac_address)
X-PrivateKeyYour SmartAPI API key
AuthorizationBearer <jwtToken> (all endpoints except login)

Base URL: https://apiconnect.angelone.in. Responses are JSON: {"status": true, "message": "SUCCESS", "errorcode": "", "data": …}.

08Authentication APIs

PurposeEndpointMeridian action
LoginPOST /rest/auth/angelbroking/user/v1/loginByPasswordconnect
Refresh JWTPOST /rest/auth/angelbroking/jwt/v1/generateTokensautomatic
ProfileGET /rest/secure/angelbroking/user/v1/getProfileprofile
LogoutPOST /rest/secure/angelbroking/user/v1/logoutdisconnect

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

PurposeEndpointMeridian action
Place orderPOST /rest/secure/angelbroking/order/v1/placeOrderplace
Modify orderPOST /rest/secure/angelbroking/order/v1/modifyOrdermodify
Cancel orderPOST /rest/secure/angelbroking/order/v1/cancelOrdercancel
Order bookGET /rest/secure/angelbroking/order/v1/getOrderBookorders
Trade bookGET /rest/secure/angelbroking/order/v1/getTradeBooktrades

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

FieldValues
varietyNORMAL regular · STOPLOSS SL orders · AMO after-market · ROBO bracket
transactiontypeBUY · SELL
ordertypeMARKET · LIMIT · STOPLOSS_LIMIT · STOPLOSS_MARKET
producttypeDELIVERY cash CNC · INTRADAY MIS · CARRYFORWARD F&O NRML · MARGIN · BO
durationDAY · IOC
exchangeNSE · BSE · NFO · BFO · MCX · CDS · NCDEX
  • Stop-loss orders need variety: STOPLOSS and a triggerprice. 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

PurposeEndpointMeridian action
PositionsGET /rest/secure/angelbroking/order/v1/getPositionpositions
Holdings (with totals)GET /rest/secure/angelbroking/portfolio/v1/getAllHoldingholdings
Funds & margin (RMS)GET /rest/secure/angelbroking/user/v1/getRMSfunds

Empty books come back as "data": null. Meridian normalises them to empty lists.

12Market data APIs

PurposeEndpointMeridian action
Quotes (LTP / OHLC / FULL with depth)POST /rest/secure/angelbroking/market/v1/quote/quote
Historical candlesPOST /rest/secure/angelbroking/historical/v1/getCandleDatacandles
Symbol searchPOST /rest/secure/angelbroking/order/v1/searchScripsearch

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"] } ]
  }
}
exchangeTypeSegment
1NSE cash (nse_cm)
2NSE F&O (nse_fo)
3BSE cash (bse_cm)
4BSE F&O (bse_fo)
5MCX F&O
7NCDEX
13Currency (cde_fo)

Binary tick layout (little-endian)

BytesFieldType
0Subscription modeuint8
1Exchange typeuint8
2–26Token (null-terminated ASCII)char[25]
27–34Sequence numberint64
35–42Exchange timestamp (epoch ms)int64
43–50Last traded price (paise)int64
51–58Last traded qty (Quote mode +)int64
59–66Average traded priceint64
67–74Volume traded todayint64
75–82 / 83–90Total buy / sell quantitydouble
91–98 / 99–106 / 107–114 / 115–122Open / 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" }, …]
InstrumentExchangeToken
Nifty 50 indexNSE99926000
Nifty Bank indexNSE99926009
Nifty Fin Service indexNSE99926037
Sensex indexBSE99919000
SBIN-EQNSE3045
RELIANCE-EQNSE2885

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 / codeCauseFix
AB1050 Invalid totp and client combinationWrong client code, or the TOTP is expired / out of syncCheck 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 tokenJWT expired (daily) or revokedMeridian 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 whitelistedCopy the API key again from My Apps. Confirm the static IP matches Detect this server's IP. Slow down requests.
Orders rejected, data worksStatic IP not registered or changedUpdate the IP in the SmartAPI app and in Meridian.
Rejected: lot size / tick size / price bandExchange validationUse lot multiples, tick-aligned prices, and prices within the circuit limits.
"Could not reach Angel One: SSL certificate problem"PHP has no CA bundleSet curl.cainfo in php.ini to C:\xampp\apache\bin\curl-ca-bundle.crt.
Status pill stays PollingWebSocket blocked by firewall / proxy, or feed token invalidAllow outbound wss://smartapisocket.angelone.in:443, then reconnect.
Charts empty after market hoursNo 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: .htaccess blocks config.php, lib/, data/ and bin/. Every state-changing request needs a CSRF token.
  • Registration: set 'allow_registration' => false in config.php once your accounts exist.
  • HTTPS: required anywhere beyond localhost. Session cookies are marked Secure automatically over HTTPS.

18Going to production

  1. Host on a VM with a reserved static IP, and register that IP in your SmartAPI app.
  2. Serve over HTTPS (e.g. Apache + Let's Encrypt), and redirect HTTP to HTTPS.
  3. Use MySQL if you prefer: set db_dsn, db_user and db_pass in config.php. Tables are created automatically.
  4. Set a fixed app_key in config.php (32 random bytes, base64) so encrypted data survives redeploys.
  5. Disable registration, and create users from the command line with php bin/create-user.php.
  6. Keep the server clock on NTP (needed for automatic TOTP).
  7. 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