Build trading apps on Mile Global Markets: REST for accounts and contracts, and WebSockets for real-time trading and prices. Your users approve your app with OAuth 2.0, and you earn a markup on every trade they place.
All requests and responses are JSON. Money amounts on REST are in cents unless a field says otherwise. Connect WebSockets to the API origin directly. Build and test against the testing environment first: it gets new endpoints before production does.
Quickstart
1Register an app with its redirect URLs and the scopes it needs. You get an 8-digit app_id.
2Send the user through OAuth 2.0 with PKCE and exchange the code for an access token.
3Call REST with Authorization: Bearer mp_…, or open the gateway and send {"authorize": "mp_…"}.
4Get a price proposal, buy, and follow the contract until it settles.
Third-party apps get a scoped API token for a user through OAuth 2.0 authorization code with PKCE (S256). A user can also create personal API tokens. Both kinds are the same mp_ token. Tokens authenticate REST calls and the /ws/v1 gateway (via the authorize call).
Presenting a token
REST: Authorization: Bearer mp_... header (the scheme is matched as "Bearer " or "bearer ").
REST (alternative): ?token=mp_... query parameter. Works, but puts the secret in URLs; prefer the header.
Gateway /ws/v1: Send {"authorize": "mp_..."} as the first message. Only API tokens are accepted here, not browser session tokens.
Price feed /api/v1/feed/ws: ?token=mp_... on the connection URL (or the browser session cookie).
Token formats
mp_ API access token. 24 random bytes, base64url. Only a SHA-256 hash is stored. Does not expire; valid until deleted.
mps_ App secret, shown once at registration. Not used by any current endpoint (the token exchange does not take it).
(none) app_id: 8-digit numeric string, for example "10482736".
OAuth 2.0 with PKCE
1. Create a code verifier and its S256 challenge. 2. Send the user to /api/v1/oauth/authorize. 3. They approve on our consent page and come back to your redirect_uri with a code. 4. Exchange it at /api/v1/oauth/token from your server.
Must exactly equal one of the app's registered redirect_uris.
code_challengeRequiredstringin query
base64url(SHA-256(code_verifier)) with no padding.
code_challenge_methodOptionalstringin query
Only S256 is accepted. May be omitted; the challenge is always verified as S256.
response_typeOptionalstringin query
Only code is accepted. May be omitted.
scopeOptionalstringin query
Space or comma separated. Must be a subset of the app's registered scopes. Defaults to all of the app's scopes.
stateOptionalstringin query
Opaque value echoed back on the redirect. Use it for CSRF protection.
Authorize
GET https://api.miletrades.site/api/v1/oauth/authorize?app_id=10482736&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback&response_type=code&scope=read%20trade&state=Xy7pQ2&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256
The server renders an HTML consent page listing the requested scopes. If the browser has no session on the API origin, the page asks for email and password. Approving POSTs the form back to /api/v1/oauth/authorize.
Invalid input on the authorize request (unknown app_id, unregistered redirect_uri, wrong response_type or code_challenge_method, missing code_challenge, scope beyond the app's scopes) renders an HTML "Can't authorize" page. It never redirects to an unvalidated URI.
grant_typeRequiredstringin form
Must be authorization_code. No other grant type exists (no refresh_token, no client_credentials).
codeRequiredstringin form
The mpc_ code from the redirect.
redirect_uriRequiredstringin form
Must equal the redirect_uri used on the authorize request.
code_verifierRequiredstringin form
The PKCE verifier whose S256 hash was sent as code_challenge.
app_idOptionalstringin form
Optional. If sent, must match the app the code was issued to.
Token request
POST /api/v1/oauth/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=mpc_EXAMPLEauthCode000000000000000&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk&app_id=10482736
Code unknown, already used or expired; app_id mismatch; redirect_uri mismatch; PKCE verification failed.
500
server_error
The token could not be issued.
Parameters are read from a form body (application/x-www-form-urlencoded) or the query string. A JSON body is not read.
No expires_in and no refresh_token are returned: the token does not expire.
Each successful exchange creates a new token named oauth:<app_id> in the user's token list.
Personal tokens and revocation
A signed-in user can create personal tokens with POST /api/v1/tokens, list them with GET /api/v1/tokens and delete them with DELETE /api/v1/tokens/{id}. See the API tokens group. You can also make and delete them on the API tokens page.
There is no OAuth revocation endpoint. A token stops working only when the user deletes it (DELETE /api/v1/tokens/{id}). OAuth-issued tokens appear in that list with the name oauth:<app_id>. Deleting an app does not delete tokens already issued for it.
Introduction
Scopes
Request only the scopes your app needs. The user sees each one on the consent page.
Scope
The user sees
Grants
read
View your markets, balance, portfolio and history
Gateway: balance, portfolio, proposal, proposal_open_contract, statement, profit_table, transaction, account_status, account_list, set_account. REST has no endpoint gated on read: every signed-in REST read accepts any valid token.
trade
Buy and sell contracts on your behalf
Gateway: buy, new_account_real, new_account_virtual. REST: POST /api/v1/contracts, POST /api/v1/contracts/bulk, POST /api/v1/accounts.
payments
Deposit and withdraw from your account
Gateway: transfer_between_accounts. REST: every deposit and withdrawal initiation (POST /api/v1/deposits/*, POST /api/v1/withdrawals/*), POST /api/v1/accounts/transfer, POST /api/v1/apps/{app_id}/claim, POST /api/v1/partner/claim, POST /api/v1/ib/transfer.
admin
Manage your API apps and tokens
REST: satisfies every REST scope check (read, trade, payments). Gateway: grants nothing by itself, because the gateway checks for the exact scope name.
REST API
Using REST
Base URL https://api.miletrades.site. Send JSON bodies with Content-Type: application/json; unknown fields are rejected.
OAuth 2.0
Authorization code flow with mandatory PKCE (S256). The authorize endpoints are browser pages; only the token endpoint is called by your server.
OAuth 2.0
Show the consent page.
GET/api/v1/oauth/authorize
Browser page
Open this URL in the user's browser. It renders an HTML login and consent page. See AUTH.oauth for parameters.
app_idRequiredstringin query
Your 8-digit app_id.
redirect_uriRequiredstringin query
Must exactly equal one of the app's registered redirect_uris.
code_challengeRequiredstringin query
base64url(SHA-256(code_verifier)) with no padding.
code_challenge_methodOptionalstringin query
Only S256 is accepted. May be omitted; the challenge is always verified as S256.
response_typeOptionalstringin query
Only code is accepted. May be omitted.
scopeOptionalstringin query
Space or comma separated. Must be a subset of the app's registered scopes. Defaults to all of the app's scopes.
stateOptionalstringin query
Opaque value echoed back on the redirect. Use it for CSRF protection.
Response 200
HTML consent page (text/html)
200Invalid parameters render an HTML "Can't authorize" page with the reason.
OAuth 2.0
Consent form submission (posted by the consent page).
POST/api/v1/oauth/authorize
Browser page
Not for direct use. The consent page posts app_id, redirect_uri, scope, state, code_challenge, action (approve or deny) and, when the browser has no session, email and password. On approve it redirects with code and state; on deny it redirects with error=access_denied and state.
actionRequired"approve" | "deny"in form
deny redirects with error=access_denied. Any other value is treated as approve.
emailOptionalstringin form
Only when the browser has no session.
passwordOptionalstringin form
Only when the browser has no session.
Response 302
302 Found
Location: https://example.com/callback?code=mpc_EXAMPLEauthCode000000000000000&state=Xy7pQ2
200Wrong email or password re-renders the consent page with "Incorrect email or password."
OAuth 2.0
Exchange an authorization code for an API token.
POST/api/v1/oauth/token
No auth
grant_typeRequiredstringin form
Must be authorization_code. No other grant type exists (no refresh_token, no client_credentials).
codeRequiredstringin form
The mpc_ code from the redirect.
redirect_uriRequiredstringin form
Must equal the redirect_uri used on the authorize request.
code_verifierRequiredstringin form
The PKCE verifier whose S256 hash was sent as code_challenge.
app_idOptionalstringin form
Optional. If sent, must match the app the code was issued to.
Request
POST /api/v1/oauth/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=mpc_EXAMPLEauthCode000000000000000&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk&app_id=10482736
400unsupported_grant_type or invalid_grant (see AUTH.oauth.tokenErrors).
500server_error: could not issue token.
Parameters are read from a form body (application/x-www-form-urlencoded) or the query string. A JSON body is not read.
No expires_in and no refresh_token are returned: the token does not expire.
Each successful exchange creates a new token named oauth:<app_id> in the user's token list.
Developer apps
Register and manage OAuth apps, and read and claim app earnings. Intended for the app owner's signed-in browser session (the Developer apps page); these routes also accept the owner's API token.
Developer apps
Register an app.
POST/api/v1/apps
Bearer token
nameRequiredstring
Display name shown on the consent page.
redirect_urisRequiredstring[]
At least one. Matched exactly on authorize and token requests.
scopesOptionalstring[]
Any of read, trade, payments, admin. Defaults to ["read"].
homepageOptionalstring
Linked from the consent page.
markup_bpOptionalinteger
Your markup in basis points, 0..300 (0% to 3%). Default 0. Added to the price of every real USD trade placed through the app; you earn it on every settled trade.
400Body is not valid JSON, contains an unknown field, or exceeds 1 MB ("invalid json").
404Not one of the caller's apps ("app not found").
401No valid token or session ("not authenticated").
New prices use the change within 30 seconds. Contracts already bought keep the price they were bought at.
Developer apps
Delete an app.
DELETE/api/v1/apps/{app_id}
Bearer token
app_idRequiredstringin path
One of the caller's apps.
Response 200
{ "deleted": true }
404Not one of the caller's apps ("app not found").
401No valid token or session ("not authenticated").
Tokens already issued for the app are not deleted and keep working.
Developer apps
Revenue-share earnings for each of the caller's apps.
GET/api/v1/apps/earnings
Bearer token
ngr_cents is lifetime stake minus payout over settled (won or lost) contracts attributed to the app, counting only real-money USD accounts. commission_cents is ngr_cents times the platform rate (app_profit_share_bp, default 1000 = 10%), floored at 0. claimable_cents = commission_cents minus paid_cents, floored at 0.
401No valid token or session ("not authenticated").
API tokens
Delete (revoke) one of the caller's tokens.
DELETE/api/v1/tokens/{id}
Bearer token
idRequireduuidin path
Token id from the list.
Response 200
{ "revoked": true }
400id is not a UUID ("invalid id").
404Not one of the caller's tokens ("token not found").
401No valid token or session ("not authenticated").
Account and balances
The user's profile, options accounts (wallets) and multi-currency transfers. Account ids (loginid) are MP followed by 10 hex characters for real accounts and VR followed by 10 hex characters for demo accounts.
Account and balances
The caller's user record, wallets and verification state.
400limit is not a positive integer, or before is not a ledger id.
404Not one of the caller's options accounts ("account not found").
401No valid token or session ("not authenticated").
category is one of deposit, withdrawal, refund, transfer, trade, commission, adjustment.
next_before is omitted on the last page.
Contracts (REST trading)
Price, place and list contracts over REST. Trades placed with an OAuth-issued token are attributed to that token's app, and a real USD trade carries the app's markup in its price. Digit contracts: even, odd, match, differ, over, under (synthetic indices only). Price contracts: rise, fall (any instrument). Amounts are integer minor units (cents) of the account currency.
Contracts (REST trading)
Price a prospective contract. Changes nothing.
POST/api/v1/contracts/proposal
Bearer token
symbolOptionalstring
Instrument, for example volatility_100. Defaults to the first registered index.
contract_typeRequiredstring
even, odd, match, differ, over, under, rise or fall (lowercase).
400Body is not valid JSON, contains an unknown field, or exceeds 1 MB ("invalid json").
400Unknown symbol, digit contract on a non-synthetic instrument, or invalid type or params.
401No valid token or session ("not authenticated").
Called with an app's token on a real account, the multiplier already includes the app's markup, and app_markup_bp says what it is.
Contracts (REST trading)
Buy a contract. The stake is debited immediately.
POST/api/v1/contracts
Bearer tokenscope: trade
The contract enters at the latest tick and settles a number of ticks later (the platform default, currently 3, unless duration_ticks is given). Settlement is pushed on the price feed WebSocket as contract.settled.
symbolOptionalstring
Instrument. Defaults to the first registered index.
contract_typeRequiredstring
even, odd, match, differ, over, under, rise or fall.
stake_centsRequiredinteger
Stake in minor units of the account currency. Must be greater than 0.
400Body is not valid JSON, contains an unknown field, or exceeds 1 MB ("invalid json").
400Unknown symbol or account, demo user on a real wallet, digit contract off synthetics, invalid type, params or stake, wallet not found, or a view-only market.
402Insufficient balance.
403Token without trade.
503Price feed not ready.
401No valid token or session ("not authenticated").
Contracts (REST trading)
Place up to 60 contracts in one request. Each item succeeds or fails on its own.
POST/api/v1/contracts/bulk
Bearer tokenscope: trade
itemsRequiredobject[]
1..60 items with the same fields as POST /api/v1/contracts. The loginid field is accepted but ignored: bulk items always use the USD account of wallet_kind.
400Body is not valid JSON, contains an unknown field, or exceeds 1 MB ("invalid json").
400No items, or more than 60 ("too many items").
403Token without trade.
401No valid token or session ("not authenticated").
Each placed result carries a full contract object (abbreviated in the example).
Item error strings: unknown symbol, demo users can only trade the demo wallet, price feed not ready, invalid contract type, invalid params, invalid stake, wallet not found, insufficient balance, could not create contract.
Contracts (REST trading)
List the caller's contracts, newest first.
GET/api/v1/contracts
Bearer token
statusOptional"open" | "closed"in query
open = pending. closed = won, lost or cancelled. Omitted or any other value = all.
symbolOptionalstringin query
Filter by instrument.
fromOptionalstringin query
RFC 3339 time or YYYY-MM-DD. Unparseable values are ignored.
toOptionalstringin query
RFC 3339 time or YYYY-MM-DD. Unparseable values are ignored.
401No valid token or session ("not authenticated").
status values: pending, won, lost, cancelled. settle_price, settle_digit, payout_cents and settled_at are omitted until settlement.
Market data (public)
Read-only prices with no authentication and CORS open to any origin (Access-Control-Allow-Origin: *). /api/v1/quotes covers the platform's own instruments (synthetic indices plus display-only real-feed prices). /api/v1/markets/* is the MT5 trade server's symbol catalog.
503Market browser not configured, or catalog loading.
The top level also carries every field of a /symbols row (abbreviated here).
tier is standard, pro or vip. sessions has 7 entries, Sunday first; times are minutes since 00:00 trade-server time. swap_3day: 0 = Sunday, -1 = none. The example values are illustrative.
Market data (public)
Liveness check.
GET/health
No auth
No parameters.
Response 200
{ "status": "ok" }
WebSockets
Trading gateway
Open wss://<api-origin>/ws/v1. Any Origin is accepted. Optional ?app_id=<app_id> on the URL sets attribution for tokens that are not bound to an app; a token bound to an app always uses its own app_id.
Send {"authorize": "mp_..."} first. Market calls (active_symbols, ticks, ticks_history, ping, time, forget, forget_all) work without it. Every other call returns AuthorizationRequired until authorized, and PermissionDenied if the token lacks the exact scope (admin does not stand in for other scopes here).
A request is one JSON object. The first recognised call key names the call. Envelope fields: req_id (integer, echoed back), subscribe (1 to stream, where supported), passthrough and app_id (ignored by the server; passthrough is not echoed separately, but appears inside echo_req). A response is {"msg_type": <type>, "echo_req": <your request>, <type>: <payload>, "req_id"?: <int>, "subscription"?: {"id": <id>}}.
The server sends a WebSocket ping control frame every 25 seconds; standard clients answer with pong automatically. The server does not close idle connections itself. You can also send {"ping": 1}.
DIGITOVER or OVER, DIGITUNDER or UNDER, DIGITMATCH or MATCH, DIGITDIFF or DIFFER or DIFF, DIGITEVEN or EVEN, DIGITODD or ODD (case-insensitive). Rise and fall are not available on the gateway. Responses always use the DIGIT... names.
Replies have msg_type history. Error: UnknownSymbol.
forgetYou sendNo auth
Stop one subscription.
forgetRequiredstring
Subscription id.
Example
{ "forget": "sub_9f1c2a3b4d5e6f70" }
forget_allYou sendNo auth
Stop every subscription of one type, or all.
forget_allRequiredstring
ticks, balance, transaction, proposal or proposal_open_contract. An empty string stops all. A non-string value (an array, for example) is read as empty and also stops all.
Example
{ "forget_all": "ticks" }
balanceYou sendscope: readSubscribable
Account balance; with subscribe: 1, re-sent after every account event for the user.
balanceRequiredany
Value is ignored.
accountOptionalstring
Operate on this account: a loginid, "real" or "demo". Defaults to the connection's active account. Demo-only users are always pinned to their demo account.
Errors: InputValidationFailed (same account, bad amount, unknown account, real to demo); PermissionDenied (insufficient balance); InternalError (no exchange rate).
account_statusYou sendscope: read
Verification tier and withdrawal limit.
account_statusRequiredany
Value is ignored.
accountOptionalstring
Operate on this account: a loginid, "real" or "demo". Defaults to the connection's active account. Demo-only users are always pinned to their demo account.
Example
{ "account_status": 1 }
statementYou sendscope: read
Ledger rows of one account, newest first.
statementRequiredany
Value is ignored.
limitOptionalinteger
Default 50, max 200.
accountOptionalstring
Operate on this account: a loginid, "real" or "demo". Defaults to the connection's active account. Demo-only users are always pinned to their demo account.
Example
{ "statement": 1, "limit": 50 }
profit_tableYou sendscope: read
Settled contracts on the active (or chosen) account.
profit_tableRequiredany
Value is ignored.
limitOptionalinteger
Default 50, max 200. Drawn from the user's 200 most recent settled contracts.
accountOptionalstring
Operate on this account: a loginid, "real" or "demo". Defaults to the connection's active account. Demo-only users are always pinned to their demo account.
Example
{ "profit_table": 1, "limit": 20 }
transactionYou sendscope: readSubscribable
Stream of the user's money events. Must be sent with subscribe: 1.
transactionRequiredany
Value is ignored.
Example
{ "transaction": 1, "subscribe": 1 }
Without subscribe: 1 the reply is {"info": "add \"subscribe\":1 to stream transactions"} and nothing streams.
portfolioYou sendscope: read
Open (pending) contracts across all accounts, up to 100.
portfolioRequiredany
Value is ignored.
Example
{ "portfolio": 1 }
proposalYou sendscope: readSubscribable
Price a digit contract. With subscribe: 1, re-priced on every tick.
proposalRequiredany
Value is ignored, for example 1.
contract_typeRequiredstring
See GATEWAY.contractTypes.
symbolRequiredstring
Market.
amountRequirednumber
Stake, account currency, major units, greater than 0.
barrierOptionalinteger | string
0..9 for over, under, match, differ. Ignored for even, odd. Over 9 and under 0 pass here but fail at buy.
accountOptionalstring
Operate on this account: a loginid, "real" or "demo". Defaults to the connection's active account. Demo-only users are always pinned to their demo account.
Open wss://<api-origin>/api/v1/feed/ws. Without credentials you get market data only. Add ?token=mp_... (or have a browser session cookie) to also receive the user's account events and to use user channels. Connections that carry ?token= are accepted from any Origin; connections without a token must come from an allow-listed Origin or send no Origin.
The server immediately sends one symbols message, then one history message per tradeable symbol (up to 300 ticks each), then streams tick messages for every symbol. There is no per-symbol subscription for ticks.
The server sends a WebSocket ping control frame every 20 seconds.
symbolsServer sends
Catalog of tradeable platform instruments. First message after connect.
trade_types lists contract families for the instrument's asset class. Only even/odd, match/differ, over/under and rise/fall can actually be traded through the API.
historyServer sends
Initial tick snapshot for one symbol (up to 300 ticks).
Event data, despite the key name. Usually { deposit: {...} } or { withdrawal: {...} }, sometimes with new_balance_cents. transfer.completed carries { from_wallet_id, to_wallet_id }.
Subscribe to a channel. User channels need a token or session.
typeRequired"subscribe"
Literal.
channelRequiredstring
mt5.state (the user's MT5 account balance and equity) or mt5.positions (full open-position list of one of the user's MT5 accounts). Other names are staff-only or unknown.
REST errors are JSON {"error": "<message>"} with an HTTP status. A few routes add fields, for example the withdrawal step-up 401 (code, stepup_id, ...) and the prelive allow-list 403 ({"error": "prelive_not_allowlisted"}). The scope gate message is "token is missing the `<scope>` scope".
REST
{ "error": "insufficient balance" }
OAuth
{
"error": "invalid_grant",
"error_description": "invalid or expired authorization code"
}
Token is missing the required scope, or the action is not allowed for this user.
404
Not found, or not owned by the caller.
409
Conflict, for example the currency account already exists.
429
Too soon: repeated withdrawal or step-up code request.
500
Server error.
502
Payment provider call failed.
503
Temporarily unavailable: price feed not ready, no FX rate, market browser not available, Kenyan deposits switched off.
Gateway error codes
InvalidToken
authorize with an unknown or deleted token.
AuthorizationRequired
A call that needs a token before authorize succeeded.
PermissionDenied
Token lacks the exact scope; demo-only restrictions; insufficient balance on buy or transfer.
UnrecognisedRequest
No known call key in the message, or an unknown call.
InputValidationFailed
Bad or missing parameters.
UnknownSymbol
Symbol not found.
RateLimit
More than the per-connection message budget (see LIMITS).
InternalError
Server-side failure, no price yet, no account, no exchange rate.
OAuth error codes
unsupported_grant_type
grant_type is not authorization_code.
invalid_grant
Bad, used or expired code; app_id or redirect_uri mismatch; PKCE failed.
server_error
Token could not be issued.
access_denied
Redirect parameter when the user cancels on the consent page.
Feed error codes
unknown_channel
Subscribe to a channel name that does not exist.
forbidden
Subscribe to a staff channel.
unauthenticated
Subscribe to a user channel without a token or session.
Reference
Limits
Gateway message rate
Token bucket per connection: 30 messages per second sustained, burst 60. Over the limit returns a RateLimit error for that message.
REST rate limiting
None found. No HTTP rate limiter is mounted on the router.
Withdrawal frequency
About one withdrawal initiation per minute per user (429).
REST JSON body
1 MB maximum; unknown fields are rejected.
Bulk contracts
1 to 60 items per request.
Contract duration
Platform default 3 ticks (admin setting contract_duration_ticks). REST duration_ticks clamped to 1..3600. Gateway contracts always use the default.
Contract list
GET /api/v1/contracts limit default 50, max 1000.
Gateway history
ticks_history count default 100, max 5000. statement and profit_table limit default 50, max 200. portfolio up to 100 open contracts.
Feed snapshot
Up to 300 ticks per symbol on connect.
Market catalog
/markets/symbols limit default 50, max 200. /markets/quotes up to 200 symbols.
Account transactions
limit default 50, max 200.
Unified deposits
limit default 30, max 100.
App earnings claim
Minimum 500 cents (5 USD) claimable.
App markup
markup_bp 0..300 (0% to 3%), default 0.
Authorization code
Single use, 5 minute lifetime.
Access token lifetime
No expiry.
Introduction
Markup commission
An app earns its markup. The markup (0% to 3%) is added to the price of every real USD trade placed through the app, as a share of the payout: the multiplier becomes 1 / (1/base + markup), so the trader receives a slightly lower payout. The app earns markup × payout on every settled trade, won or lost. Trades placed before markup pricing earn the old flat share (app_profit_share_bp, default 10%) of their net house revenue instead.
A contract is attributed to an app when it is bought with a token bound to that app (an OAuth-issued token, or a personal token created with app_id), on the gateway buy call, REST POST /api/v1/contracts or REST POST /api/v1/contracts/bulk. On the gateway, a token with no app binding uses ?app_id= from the connection URL.
Endpoints: GET /api/v1/apps/earnings, POST /api/v1/apps/{app_id}/claim. See Developer apps, and your figures in the commission report.