adona-robot · données de marché à la capacité

API reference

Candle history and live market data for data customers.

Start in three steps

  1. Get your API key on your account page. It stays on your server.
  2. Your server exchanges it for an access token at POST /v1/tokens.
  3. The token reads candles, or opens the live stream.
# 1. your server exchanges the key for a short-lived token
export ADONA_API_KEY="${ADONA_API_KEY:-adk_live_...}"
RESP=$(curl -s https://api.adona-robot.com/v1/tokens \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $ADONA_API_KEY" \
  -d '{"end_user_id":"u-42"}')
TOKEN=$(echo "$RESP" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)
[ -n "$TOKEN" ] || echo "refused: $RESP"

# 2. the token reads candles
curl -s 'https://api.adona-robot.com/v1/candles?symbol=EURUSD&timeframe=S1&limit=1000' \
  -H "Authorization: Bearer $TOKEN"

OpenAPI 3.1, for your tools

Point your client generator, Postman or your agent at this URL.

https://api.adona-robot.com/v1/openapi.json

Authentication

Two secrets, both on Authorization: Bearer. A long-lived API key (adk_live_…) is exchanged at POST /v1/tokens for a twelve-hour access token; every other call carries that token. Sending one where the other belongs is answered by name, not by an opaque 401. The key belongs on your server: POST /v1/tokens refuses a browser's preflight.

Errors

Every refusal from the routes below carries a code: {"detail": "CODE"}, and a 422 adds the reason: {"detail": "CODE: text"}. Branch on the part before the first colon. A 422 also lists the offending fields as data, "fields": [{"loc": ["limit"], "reason": "…"}] (empty when no field can be named, such as a body that is not JSON), so a client can point at the field without parsing the text. Each route lists its codes below with what to do.

POST/v1/tokens

Exchange the API key for a twelve-hour access token.

Example answer

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.<payload>.<signature>",
  "token_type": "bearer",
  "expires_in": 43200,
  "end_user_id": "user-42",
  "symbols": [
    "EURUSD",
    "XAUUSD"
  ]
}

Refusals

StatusCodeWhat to do
401INVALID_CUSTOMER_KEYUnknown, revoked or missing API key. Do not retry with the same key.
401EXPECTED_API_KEYAn access token was sent here; this door takes the API key (adk_...).
403CUSTOMER_TRIAL_EXPIREDThe free trial has ended. Move to a paid plan; the same key works again.
422INVALID_END_USER_IDend_user_id is empty or longer than 128 characters.
422INVALID_REQUESTThe body did not parse, or two fields are wrong at once.
429TOO_MANY_ATTEMPTSOver 300 token requests a minute for this account, or too many from one address. Wait for Retry-After seconds.
500REDIS_NOT_AVAILABLEOurs, and temporary. Retry with backoff.
Request and response fields

Body: TokenRequest

NameTypeRequiredNotes
end_user_idstringyes

Returns: TokenResponse

NameTypeRequiredNotes
access_tokenstringyes
token_typestringno
expires_inintegeryes
end_user_idstringyes
symbolsstring[]yes

GET/v1/candles

Candle history, one page, oldest first.

Candle history for the symbols this account may carry.

Page backwards with before, which takes the previous response's next_before verbatim. A null next_before means the horizon, not an error: history is bounded by retention and by what the archive holds.

Parameters

NameTypeRequiredNotes
symbolstringyes
timeframestringyesD1 · H4 · H1 · M15 · M5 · M1 · S1
limitintegerno1 to 5000, default 50
beforestring (date-time)noPage backwards: return bars strictly older than this instant (RFC3339).

Example answer

{
  "symbol": "EURUSD",
  "timeframe": "M1",
  "candles": [
    {
      "time": "2026-09-07T10:00:00Z",
      "open": "1.10000000",
      "high": "1.10012000",
      "low": "1.09995000",
      "close": "1.10007000",
      "volume": "37"
    },
    {
      "time": "2026-09-07T10:01:00Z",
      "open": "1.10007000",
      "high": "1.10020000",
      "low": "1.10001000",
      "close": "1.10018000",
      "volume": "42"
    }
  ],
  "next_before": "2026-09-07T10:00:00Z"
}

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/tokens.
401EXPECTED_ACCESS_TOKENThe API key was sent here; exchange it at POST /v1/tokens first.
401CUSTOMER_ACCESS_REVOKEDAccess was cut, or the key was rotated. A new token from the current key; if that is refused too, stop.
401CUSTOMER_ID_REQUIREDA data token without its account claim.
403EXPECTED_DATA_TOKENA token from another surface. Only tokens from POST /v1/tokens are accepted.
403MARKET_DATA_SCOPE_REQUIREDThe token's scope does not reach market data.
403CUSTOMER_ID_REQUIREDA data token without its account claim.
403CUSTOMER_KID_REQUIREDA data token without its key fingerprint.
403TRADER_ROLE_REQUIREDNot a data token, and not a trader either.
403MFA_REQUIREDNot a data token.
403SYMBOL_NOT_ALLOWEDThis instrument is not in your account's list.
403CUSTOMER_TRIAL_EXPIREDThe free trial has ended. Move to a paid plan; the same key works again.
422TIMEFRAME_UNSUPPORTEDNot one of S1, M1, M5, M15, H1, H4, D1.
422INVALID_SYMBOLShorter than two characters.
422INVALID_LIMITOutside 1 to 5000.
422INVALID_BEFORENot an RFC3339 instant. Pass next_before back verbatim.
422INVALID_REQUESTTwo parameters wrong at once, or one missing.
429CUSTOMER_MINUTE_CEILINGYour plan's slices for this minute are spent. Wait for Retry-After seconds.
429CUSTOMER_DAILY_CAPThe daily runaway guard is reached. Waiting seconds does not help; it reopens the next UTC day.
429TOO_MANY_ATTEMPTSOver 60 requests a minute for this end user. Wait for Retry-After seconds.
500SYMBOL_TRANSLATION_ERROROurs. Retrying does not help; tell us.
500REDIS_NOT_AVAILABLEOurs, and temporary. Retry with backoff.
503CUSTOMER_ACCESS_CHECK_UNAVAILABLEOurs, and temporary: your token is probably fine. Retry after Retry-After.
Request and response fields

Returns: CandlePage

NameTypeRequiredNotes
symbolstringyesThe canonical symbol the page was read for.
timeframestringyesOne of S1, M1, M5, M15, H1, H4, D1.
candlesCandle[]yesAscending by time. May be empty.
next_beforestringyesPass it back verbatim as before for the previous page. null means there is nothing older: stop. On S1 a page covers one day, so an empty page with a non-null cursor is an empty day (a weekend): continue.

POST/v1/ws-ticket

A single-use ticket to open the live stream.

Mint a single-use ticket for this end user's socket.

The ticket carries the customer and the key fingerprint forward, so the connect guard re-checks both: a key revoked between the mint and the connect does not get a socket, even though the ticket itself is valid.

Example answer

{
  "ticket": "<single-use ticket>",
  "expires_in_seconds": 30
}

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/tokens.
401EXPECTED_ACCESS_TOKENThe API key was sent here; exchange it at POST /v1/tokens first.
401CUSTOMER_ACCESS_REVOKEDAccess was cut, or the key was rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_DATA_TOKENA token from another surface. Only tokens from POST /v1/tokens are accepted.
403MARKET_DATA_SCOPE_REQUIREDThe token's scope does not reach market data.
403CUSTOMER_ID_REQUIREDA data token without its account claim.
403CUSTOMER_KID_REQUIREDA data token without its key fingerprint.
403TRADER_ROLE_REQUIREDNot a data token, and not a trader either.
403MFA_REQUIREDNot a data token.
403CUSTOMER_TRIAL_EXPIREDThe free trial has ended. Move to a paid plan; the same key works again.
429TOO_MANY_ATTEMPTSOver 20 tickets a minute for this end user, or 60 for this address. Wait for Retry-After seconds.
500REDIS_NOT_AVAILABLEOurs, and temporary. Retry with backoff.
503CUSTOMER_ACCESS_CHECK_UNAVAILABLEOurs, and temporary: your token is probably fine. Retry after Retry-After.
Request and response fields

Returns: WsTicket

NameTypeRequiredNotes
ticketstringyesSingle use. Open wss://<host>/v1/stream offering two subprotocols, adona.data.v1 and ticket.<ticket>; never put the ticket in the URL.
expires_in_secondsintegeryesSeconds before an unused ticket expires.

Live stream

Live stream. POST /v1/ws-ticket returns a single-use ticket. Open wss://<host>/v1/stream offering TWO subprotocols: adona.data.v1 and ticket.<ticket>, e.g. new WebSocket(url, ["adona.data.v1", "ticket." + ticket]). The ticket never goes in the URL: a ticket sent only in the query string is ignored, and the connection is refused with no reason. Five frames are accepted: ping, subscribe, unsubscribe, candle.watch, candle.unwatch; anything else answers FRAME_NOT_ALLOWED. Channels are quote:<SYMBOL> and candle:<SYMBOL>:<TIMEFRAME>. The subscribed and candle.watched acknowledgements carry market: for each symbol, its session as of the acknowledgement, open, closed (outside trading hours, such as a weekend, a holiday or the daily break: after its snapshot the channel stays silent until the market opens) or unknown (no session signal). It is not sent again when the session changes.

Close codes

Close codes. 1008 carries a reason you must not reconnect in a loop on: CUSTOMER_ACCESS_REVOKED, CUSTOMER_TRIAL_EXPIRED, CUSTOMER_CONNECTION_LIMIT, EXPECTED_DATA_TOKEN, INVALID_TICKET (mint a new ticket once), and RATE_LIMITED (more than 40 messages a second: slow down, then reconnect). 1009 FRAME_TOO_LARGE: a message over 16 KiB; split the subscription. 1011 is ours and temporary, whatever its reason (CUSTOMER_ACCESS_CHECK_UNAVAILABLE, REDIS_NOT_AVAILABLE, REALTIME_HUB_NOT_AVAILABLE): reconnect with backoff.

Prop firm API (beta)

Beta. The prop-firm tenant API: your traders, their accounts and their trading, judged by Adona's rules. It is published here only while it is open, and every change a client can see is dated on adona-robot.com/changelog.

Its own secret. A tenant key (adp_live_…), on your server only, is exchanged at POST /v1/prop/tokens for a 12-hour prop token, sent as Authorization: Bearer on every other /v1/prop call. A data token is refused here (EXPECTED_PROP_TOKEN), and a prop token on the data routes (EXPECTED_DATA_TOKEN). Your tenant comes from the token, never from the request: another tenant's id answers the 404 of an unknown one.

Start with the prop firm quickstart: six calls, from your tenant key to your first order. The rules Adona judges every order by, and the codes a refusal answers, are on the rules on every order.

POST/v1/prop/tokens

Exchange the tenant key for a twelve-hour prop token.

Refusals

StatusCodeWhat to do
401INVALID_TENANT_KEYUnknown, rotated, revoked or missing tenant key. Do not retry with the same key.
401EXPECTED_API_KEYAn access token was sent here; this door takes the tenant key (adp_...).
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
429TOO_MANY_ATTEMPTSOver 60 token requests a minute for this tenant, or too many from one address. Wait for Retry-After seconds.
500REDIS_NOT_AVAILABLEOurs, and temporary. Retry with backoff.
Request and response fields

Returns: PropTokenResponse

NameTypeRequiredNotes
access_tokenstringyes
token_typestringno
expires_inintegeryes
tenant_idstringyes

GET/v1/prop/tenant

The tenant this token speaks for.

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
Request and response fields

Returns: PropTenant

NameTypeRequiredNotes
tenant_idstringyes
namestringyes
productsstring[]yes
statusstringyes

GET/v1/prop/traders

Your traders, oldest first.

Parameters

NameTypeRequiredNotes
limitintegerno1 to 500, default 100
offsetintegerno0 to 1000000, default 0
external_refstringno

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
422INVALID_LIMITOutside 1 to 500.
422INVALID_OFFSETNegative, or over 1000000.
422INVALID_EXTERNAL_REFEmpty or over 128 characters.
422INVALID_REQUESTTwo parameters wrong at once.
Request and response fields

Returns: PropTraderPage

NameTypeRequiredNotes
tradersPropTrader[]yes
next_offsetintegeryes

POST/v1/prop/traders

Create a trader, at once: you hold your traders' identities.

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
409EXTERNAL_REF_IN_USEYou already used this external_ref for another trader. Your own namespace: pick another.
409TENANT_IDENTITY_SWITCH_OFFHolding your traders' identities is not open yet on our side. Contact us; retrying does not help.
422TRADER_EMAIL_NOT_ACCEPTEDYou hold your traders' identities: Adona never takes their address. Send external_ref alone.
422INVALID_EXTERNAL_REFEmpty or over 128 characters.
422INVALID_DISPLAY_NAMEOver 64 characters.
422INVALID_REQUESTThe body did not parse, or two fields are wrong at once.
429TOO_MANY_ATTEMPTSOver 120 creations an hour for your tenant. Wait for Retry-After seconds.
500REDIS_NOT_AVAILABLEOurs, and temporary. Retry with backoff.
Request and response fields

Body: CreateTraderRequest

NameTypeRequiredNotes
external_refstringyes
display_namestringno

Returns: TraderAccepted

NameTypeRequiredNotes
external_refstringyes
statusstringno
trader_idstringyes

GET/v1/prop/traders/{trader_id}

One of your traders.

Parameters

NameTypeRequiredNotes
trader_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404TRADER_NOT_FOUNDNo trader of yours has this id. Another tenant's id answers the same.
422INVALID_TRADER_IDNot a UUID.
Request and response fields

Returns: PropTrader

NameTypeRequiredNotes
trader_idstringyes
external_refstringyes
emailstringyesNull, except for a trader created before 04.11.2026.
display_namestringyes
is_activebooleanyes
blocked_atstring (date-time)yes
created_atstring (date-time)yes

DELETE/v1/prop/traders/{trader_id}

Erase a trader whose identity you hold: Adona keeps no pseudonym of them.

Lot 2 of #1254, 2e: only a trader you hold, with no account in progress (block it first). Erasing twice answers the same.

Parameters

NameTypeRequiredNotes
trader_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404TRADER_NOT_FOUNDNo trader of yours has this id. Another tenant's id answers the same.
409TRADER_NOT_HELD_BY_TENANTThis trader's account was not created by you: it is their own, not yours to erase.
409TRADER_ACCOUNTS_OPENAn account of this trader is still in progress. Block the trader first, which ends it, then erase.
422INVALID_TRADER_IDNot a UUID.
422INVALID_REQUESTThe request did not parse.
503TENANT_ACTIONS_BUSYToo many of your actions at once on this server. Retry after Retry-After.
Request and response fields

Returns: TraderErased

NameTypeRequiredNotes
trader_idstringyes
erasedbooleanno

GET/v1/prop/traders/{trader_id}/accounts

A trader's accounts, newest first, with the rules each one runs under.

Parameters

NameTypeRequiredNotes
trader_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404TRADER_NOT_FOUNDNo trader of yours has this id. Another tenant's id answers the same.
422INVALID_TRADER_IDNot a UUID.

POST/v1/prop/traders/{trader_id}/accounts

Open an account for a trader on one of your products.

Parameters

NameTypeRequiredNotes
trader_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404TRADER_NOT_FOUNDNo trader of yours has this id. Another tenant's id answers the same.
404PRODUCT_NOT_FOUNDNone of your active products is called so (GET /v1/prop/products).
409TRADER_INACTIVEThis trader cannot trade (blocked by us or erased). Contact us.
409TRADER_BLOCKEDYou blocked this trader. POST /v1/prop/traders/{id}/unblock first.
409ACCOUNT_IN_PROGRESSThe trader already has an account in progress or funded.
409NO_EXECUTION_ACCOUNTYour tenant has no execution account yet. Contact us.
409CONTRACT_ENDEDYour contract with us has ended: no account opens again.
422INVALID_TRADER_IDNot a UUID.
422INVALID_PRODUCTEmpty or over 32 characters.
422INVALID_REQUESTThe body did not parse, or two fields are wrong at once.
503TENANT_ACTIONS_BUSYToo many of your actions at once on this server. Retry after Retry-After.
503ACCOUNT_OPENING_UNAVAILABLEOurs, and temporary. Retry after Retry-After.
Request and response fields

Body: OpenAccountRequest

NameTypeRequiredNotes
productstringyes

Returns: PropAccount

NameTypeRequiredNotes
account_idstringyes
trader_idstringyes
productstringyes
statusstringyes
is_demobooleanyes
starting_balancestringyes
profit_target_pctstringyes
max_drawdown_pctstringyes
daily_loss_limit_pctstringyes
max_concurrent_sl_pctstringyes
max_concurrent_tp_pctstringyes
profit_share_trader_pctstringyes
created_atstring (date-time)yes
started_atstring (date-time)yes
completed_atstring (date-time)yes
promotedbooleanyes

POST/v1/prop/traders/{trader_id}/block

Block a trader: every position closed and every account ended, then no new one.

Parameters

NameTypeRequiredNotes
trader_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404TRADER_NOT_FOUNDNo trader of yours has this id. Another tenant's id answers the same.
409BLOCK_IN_PROGRESSThe trader IS blocked, and another call is closing one of their accounts. Block again in a few seconds to finish the others.
409TRADER_INACTIVEThis trader's account was erased: there is nothing to block.
422INVALID_TRADER_IDNot a UUID.
422REASON_REQUIREDA block needs a reason: it was blank.
422INVALID_REASONNot a string, or over 2000 characters.
422INVALID_REQUESTNo body, no reason in it, the body did not parse, or two fields are wrong at once.
503TENANT_ACTIONS_BUSYToo many of your actions at once on this server. Retry after Retry-After.
Request and response fields

Body: BlockRequest

NameTypeRequiredNotes
reasonstringyes

Returns: TraderBlocked

NameTypeRequiredNotes
trader_idstringyes
blockedbooleanno
alreadybooleanyes
accountsBlockedAccountBody[]yes

POST/v1/prop/traders/{trader_id}/unblock

Lift your block: the trader may open a new account.

Parameters

NameTypeRequiredNotes
trader_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404TRADER_NOT_FOUNDNo trader of yours has this id. Another tenant's id answers the same.
409BLOCK_IN_PROGRESSThe block is still closing this trader's accounts, or a position waits for its market to reopen. Retry later.
422INVALID_TRADER_IDNot a UUID.
503TENANT_ACTIONS_BUSYToo many of your actions at once on this server. Retry after Retry-After.
Request and response fields

Returns: TraderUnblocked

NameTypeRequiredNotes
trader_idstringyes
blockedbooleanno

GET/v1/prop/accounts/{account_id}

One of your traders' accounts, with its rules.

Parameters

NameTypeRequiredNotes
account_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404ACCOUNT_NOT_FOUNDNo account of your traders has this id. Another tenant's id answers the same.
422INVALID_ACCOUNT_IDNot a UUID.
Request and response fields

Returns: PropAccount

NameTypeRequiredNotes
account_idstringyes
trader_idstringyes
productstringyes
statusstringyes
is_demobooleanyes
starting_balancestringyes
profit_target_pctstringyes
max_drawdown_pctstringyes
daily_loss_limit_pctstringyes
max_concurrent_sl_pctstringyes
max_concurrent_tp_pctstringyes
profit_share_trader_pctstringyes
created_atstring (date-time)yes
started_atstring (date-time)yes
completed_atstring (date-time)yes
promotedbooleanyes

GET/v1/prop/accounts/{account_id}/status

Where an account stands: whether its rules bind, and its drawdown in percent.

Parameters

NameTypeRequiredNotes
account_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404ACCOUNT_NOT_FOUNDNo account of your traders has this id. Another tenant's id answers the same.
422INVALID_ACCOUNT_IDNot a UUID.
Request and response fields

Returns: PropAccountStatus

NameTypeRequiredNotes
account_idstringyes
statusstringyes
rules_bindbooleanyes
availablebooleanyes
drawdownobjectyes

POST/v1/prop/accounts/{account_id}/promote

Promote a passed challenge to a funded account, signed by your key.

Parameters

NameTypeRequiredNotes
account_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404ACCOUNT_NOT_FOUNDNo account of your traders has this id. Another tenant's id answers the same.
409NOT_PASSEDOnly a passed challenge is promoted.
409ALREADY_FUNDEDThis challenge was promoted already.
409TRADER_INACTIVEThis trader cannot trade (blocked by us or erased). Contact us.
409TRADER_BLOCKEDYou blocked this trader. POST /v1/prop/traders/{id}/unblock first.
409TOTP_NOT_ENROLLEDThe trader has no second factor yet: a funded account requires one. Have them enable it, then retry.
409ACTIVE_STRATEGY_EXISTSThe trader still holds an active account. Retry once it has ended.
409NO_EXECUTION_ACCOUNTYour tenant has no execution account yet. Contact us.
422INVALID_ACCOUNT_IDNot a UUID.
422INVALID_REASONNot a string, or over 2000 characters.
422INVALID_REQUESTThe body did not parse, or two fields are wrong at once.
503TENANT_ACTIONS_BUSYToo many of your actions at once on this server. Retry after Retry-After.
503ACCOUNT_OPENING_UNAVAILABLEOurs, and temporary. Retry after Retry-After.
Request and response fields

Returns: PropAccount

NameTypeRequiredNotes
account_idstringyes
trader_idstringyes
productstringyes
statusstringyes
is_demobooleanyes
starting_balancestringyes
profit_target_pctstringyes
max_drawdown_pctstringyes
daily_loss_limit_pctstringyes
max_concurrent_sl_pctstringyes
max_concurrent_tp_pctstringyes
profit_share_trader_pctstringyes
created_atstring (date-time)yes
started_atstring (date-time)yes
completed_atstring (date-time)yes
promotedbooleanyes

POST/v1/prop/accounts/{account_id}/revoke

Revoke a funded account: closed, flattened and deactivated, signed by your key.

Parameters

NameTypeRequiredNotes
account_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404ACCOUNT_NOT_FOUNDNo account of your traders has this id. Another tenant's id answers the same.
409NOT_FUNDEDOnly a funded account is revoked.
409REVOCATION_IN_PROGRESSThis account is being revoked. Retry in a few seconds: the replay answers already: true.
422INVALID_ACCOUNT_IDNot a UUID.
422REASON_REQUIREDA revocation needs a reason: it was blank.
422INVALID_REASONNot a string, or over 2000 characters.
422INVALID_REQUESTNo body, no reason in it, the body did not parse, or two fields are wrong at once.
503TENANT_ACTIONS_BUSYToo many of your actions at once on this server. Retry after Retry-After.
Request and response fields

Body: RevokeRequest

NameTypeRequiredNotes
reasonstringyes

Returns: PropRevoked

NameTypeRequiredNotes
account_idstringyes
statusstringno
alreadybooleanyes
finishedbooleanyes

GET/v1/prop/accounts/{account_id}/hedge

The H of one of your funded accounts, and the limits you hold.

Parameters

NameTypeRequiredNotes
account_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404ACCOUNT_NOT_FOUNDNo account of your traders has this id. Another tenant's id answers the same.
422INVALID_ACCOUNT_IDNot a UUID.
Request and response fields

Returns: PropHedge

NameTypeRequiredNotes
account_idstringyes
statusstringyes
h_effectivestringyes
sourcestringyes
h_algostringyes
h_overridestringyes
override_set_byyou | adonayes
limitsHedgeLimitsyes

PUT/v1/prop/accounts/{account_id}/hedge/override

Set H for the new positions of a funded account, within your limits.

Parameters

NameTypeRequiredNotes
account_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
403H_OVERRIDE_NOT_ALLOWEDYour tenant holds no H limits: no override can be set. Contact us.
404ACCOUNT_NOT_FOUNDNo account of your traders has this id. Another tenant's id answers the same.
409NOT_FUNDEDOnly a funded account has an H override.
422INVALID_ACCOUNT_IDNot a UUID.
422INVALID_VALUENot a number.
422OVERRIDE_OUT_OF_RANGEAn override is between 0 and 1.
422OVERRIDE_OFF_STEPAn override is a multiple of the step (limits.step on GET .../hedge).
422H_OVERRIDE_OUTSIDE_LIMITSOutside your tenant's limits (limits on GET .../hedge).
422INVALID_REASONNot a string, or over 2000 characters.
422INVALID_REQUESTThe body did not parse, or two fields are wrong at once.
Request and response fields

Body: OverrideRequest

NameTypeRequiredNotes
valuenumber | stringyes
reasonstringno

Returns: PropHedgeChange

NameTypeRequiredNotes
account_idstringyes
h_effective_beforestringyes
h_effectivestringyes
sourcestringyes
changedbooleanyes

POST/v1/prop/accounts/{account_id}/hedge/override/clear

Clear the H override of a funded account: back to our algorithm.

Parameters

NameTypeRequiredNotes
account_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404ACCOUNT_NOT_FOUNDNo account of your traders has this id. Another tenant's id answers the same.
422INVALID_ACCOUNT_IDNot a UUID.
422INVALID_REASONNot a string, or over 2000 characters.
422INVALID_REQUESTThe body did not parse, or two fields are wrong at once.
Request and response fields

Returns: PropHedgeChange

NameTypeRequiredNotes
account_idstringyes
h_effective_beforestringyes
h_effectivestringyes
sourcestringyes
changedbooleanyes

POST/v1/prop/accounts/{account_id}/hedge/dehedge

Dehedge the open positions of a funded account.

Parameters

NameTypeRequiredNotes
account_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
403DEHEDGE_NOT_ALLOWEDYour tenant's H floor is not 0: the open positions stay hedged. Contact us.
404ACCOUNT_NOT_FOUNDNo account of your traders has this id. Another tenant's id answers the same.
409NOT_FUNDEDOnly a funded account, or one still holding hedged positions, is dehedged.
409NOTHING_TO_DEHEDGENo open position is left to dehedge.
422INVALID_ACCOUNT_IDNot a UUID.
422INVALID_REASONNot a string, or over 2000 characters.
422INVALID_REQUESTThe body did not parse, or two fields are wrong at once.
503HEDGE_UNAVAILABLEOurs. Retry after Retry-After; if it persists, contact us.
Request and response fields

Returns: PropDehedged

NameTypeRequiredNotes
account_idstringyes
positions_coveredintegeryes

GET/v1/prop/products

Your active products and their rules, smallest first.

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.

GET/v1/prop/exposure

Your hedge accounts' exposure and drift, per symbol.

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
Request and response fields

Returns: PropExposure

NameTypeRequiredNotes
as_ofstringyes
targets_availablebooleanyes
hedge_accountsExposureAccount[]yes

GET/v1/prop/traders/{trader_id}/reports

The months your trader has a report for.

Parameters

NameTypeRequiredNotes
trader_idstring (uuid)yes

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404TRADER_NOT_FOUNDNo trader of yours has this id. Another tenant's id answers the same.
422INVALID_TRADER_IDNot a UUID.
Request and response fields

Returns: ReportMonths

NameTypeRequiredNotes
trader_idstringyes
monthsReportMonth[]yes

GET/v1/prop/traders/{trader_id}/reports/{month}

Your trader's month: performance, risk, lifecycle and coverage.

Parameters

NameTypeRequiredNotes
trader_idstring (uuid)yes
monthstringyespattern ^\d{4}-(0[1-9]|1[0-2])$

Refusals

StatusCodeWhat to do
401MISSING_BEARER_TOKENNo Authorization: Bearer header.
401INVALID_ACCESS_TOKENNot an access token.
401INVALID_JWTThe token is malformed or expired: request a new one at POST /v1/prop/tokens.
401EXPECTED_ACCESS_TOKENThe tenant key was sent here; exchange it at POST /v1/prop/tokens first.
401TENANT_ACCESS_REVOKEDThe key was revoked or rotated. A new token from the current key; if that is refused too, stop.
403EXPECTED_PROP_TOKENA token from another surface. Only tokens from POST /v1/prop/tokens are accepted.
403TENANT_SUSPENDEDYour tenant is suspended. Contact us; retrying does not help.
404REPORT_NOT_FOUNDNo report for this month: before the trader's first account, or in the future.
404TRADER_NOT_FOUNDNo trader of yours has this id. Another tenant's id answers the same.
422INVALID_TRADER_IDNot a UUID.
422INVALID_MONTHNot a month as YYYY-MM.
Request and response fields

Returns: TraderReport

NameTypeRequiredNotes
schema_versionintegeryes
trader_idstringyes
monthstringyes
finalbooleanyes
computed_atstringyes
accountsReportAccount[]yes

Examples

Three files, no dependency, tested against the shapes this reference describes. The API key stays on your server; the browser gets a token from it. The same files, with their tests, are on GitHub.

Your server: the key for a token

Node 18+, no dependency. Exchanges the API key for a twelve-hour token per end user and reuses it until a minute before it expires, with a fresh one after a key rotation; the key never reaches a browser. token-server.ts

/**
 * adona-robot: the one call that must stay on your server.
 *
 * Node 18+ (global fetch), no dependency. Your API key never leaves this process:
 * it is exchanged at POST /v1/tokens for a twelve-hour token per end user, and the
 * browser only ever sees that token (see browser.ts).
 *
 * Mount `tokenFor` behind a route of your own, after your own login has decided who
 * the end user is. With Express, for example:
 *
 *   app.post("/market-token", requireLogin, async (req, res) => {
 *     try {
 *       res.json(await tokenFor(req.user.id, { fresh: req.query.fresh === "1" }));
 *     } catch (error) {
 *       // A key the API refused (revoked, trial ended) is an answer: 403, and the
 *       // browser stops. Anything else is temporary: 503, and the browser retries.
 *       const answer = error instanceof Refused && error.status >= 400 && error.status < 500 && error.status !== 429;
 *       res.status(answer ? 403 : 503).json({ error: String(error) });
 *     }
 *   });
 */

const API = "https://api.adona-robot.com";
const KEY = process.env.ADONA_API_KEY ?? ""; // adk_live_...
if (!KEY.startsWith("adk_")) throw new Error("ADONA_API_KEY is not set: it starts with adk_live_ or adk_test_");

export interface MarketToken {
  access_token: string;
  /** Seconds the token is still valid for. */
  expires_in: number;
}

export class Refused extends Error {
  constructor(
    readonly status: number,
    /** The part of `detail` before the first colon: branch on this. */
    readonly code: string,
  ) {
    super(`${status} ${code}`);
  }
}

// One token per end user, reused until a minute before it expires: minting one per
// page view spends the account's 300 token requests a minute for nothing.
const cache = new Map<string, { token: string; until: number }>();
const inFlight = new Map<string, Promise<MarketToken>>();
const lastFresh = new Map<string, number>();

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/**
 * `fresh` skips the cache, for a browser whose token was refused after a key
 * rotation. It is honoured at most once a minute per end user, so a page that
 * asks for it in a loop cannot spend the account's budget.
 */
export function tokenFor(endUserId: string, { fresh = false } = {}): Promise<MarketToken> {
  const now = Date.now();
  const hit = cache.get(endUserId);
  const honourFresh = fresh && now - (lastFresh.get(endUserId) ?? 0) > 60_000;
  if (honourFresh) lastFresh.set(endUserId, now);
  if (hit && hit.until > now && !honourFresh) {
    return Promise.resolve({ access_token: hit.token, expires_in: Math.floor((hit.until - now) / 1000) + 60 });
  }
  // Two calls for the same end user at once share one mint.
  const pending = inFlight.get(endUserId) ?? mint(endUserId).finally(() => inFlight.delete(endUserId));
  inFlight.set(endUserId, pending);
  return pending;
}

async function mint(endUserId: string, attempts = 5): Promise<MarketToken> {
  for (let attempt = 0; ; attempt++) {
    let status = 0;
    let code = "NETWORK";
    let retryAfter = 0;
    try {
      const response = await fetch(`${API}/v1/tokens`, {
        method: "POST",
        headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
        body: JSON.stringify({ end_user_id: endUserId }),
      });
      if (response.ok) {
        const body = (await response.json()) as MarketToken;
        const now = Date.now();
        remember(endUserId, { token: body.access_token, until: now + (body.expires_in - 60) * 1000 });
        return { access_token: body.access_token, expires_in: body.expires_in };
      }
      status = response.status;
      const detail = String(((await response.json().catch(() => ({}))) as { detail?: unknown }).detail ?? "");
      code = detail.split(":")[0].trim();
      retryAfter = Number(response.headers.get("Retry-After")) || 0;
    } catch {
      // The network: retried below like a 5xx.
    }
    // 429 TOO_MANY_ATTEMPTS clears within the minute; 5xx and the network are
    // temporary. Anything else (a revoked key, an ended trial) will not clear.
    const retryable = status === 0 || status === 429 || status >= 500;
    if (!retryable || attempt === attempts - 1) throw new Refused(status, code);
    await sleep(1000 * (retryAfter > 0 ? retryAfter : 2 ** attempt));
  }
}

function remember(endUserId: string, entry: { token: string; until: number }) {
  cache.set(endUserId, entry);
  // Forget expired tokens now and then, so the map holds live end users only.
  if (cache.size % 1000 === 0) {
    const now = Date.now();
    for (const [id, { until }] of cache) if (until <= now) cache.delete(id);
    for (const [id, at] of lastFresh) if (now - at > 60_000) lastFresh.delete(id);
  }
}

The browser: history and the live stream

No dependency. Reads candle history once with the cursor, then keeps the chart current from the live stream: the ticket as a subprotocol, a reconnect through deploys and network loss, and a stop on the refusals that retrying cannot change. browser.ts

/**
 * adona-robot in the browser: candle history and the live stream, for one end user.
 *
 * No dependency. The page calls the API directly, so your site's origin must be
 * declared on your account page (browser origins); the token comes from your own
 * server (token-server.ts), never the API key.
 *
 *   const bars = await history("EURUSD", "M1");        // once, when the chart opens
 *   const stream = openStream(["quote:EURUSD", "candle:EURUSD:M1"], {
 *     onQuote: (q) => console.log(q.symbol, q.bid, q.ask),
 *     onBar: (channel, bar) => console.log(channel, bar.time, bar.close),
 *     onStop: (reason) => console.warn("stream stopped:", reason),
 *   });
 *   // later, e.g. when the chart unmounts: stream.close();
 *
 * The stream carries closed bars of every timeframe, S1 to D1:
 * "candle:EURUSD:S1" delivers each one-second bar as it closes, and
 * "candle:EURUSD:D1" the day's bar at the 17:00 New York close.
 *
 * Fetch history once, then let the stream keep the chart current: polling
 * /v1/candles spends slices on bars the stream already delivers. Prices are
 * strings, exactly as served; convert them at the last moment, for display.
 */

const API = "https://api.adona-robot.com";
const STREAM = "wss://api.adona-robot.com/v1/stream";
const TOKEN_ROUTE = "/market-token"; // your server's route around POST /v1/tokens

export interface Bar {
  time: string; // bar open time, RFC3339 UTC
  open: string;
  high: string;
  low: string;
  close: string;
  volume: string;
}

export interface Quote {
  symbol: string;
  bid: string;
  ask: string;
  as_of: string;
}

export class Refused extends Error {
  constructor(
    readonly status: number,
    /** The part of `detail` before the first colon: branch on this. */
    readonly code: string,
  ) {
    super(`${status} ${code}`);
  }
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/** An answer rather than an accident: retrying will not change it. */
const isAnswer = (error: unknown) => error instanceof Refused && (error.status === 401 || error.status === 403);

// ---------------------------------------------------------------- the token

let token: { value: string; until: number } | null = null;

async function accessToken(fresh = false): Promise<string> {
  if (!fresh && token && token.until > Date.now()) return token.value;
  const response = await fetch(fresh ? `${TOKEN_ROUTE}?fresh=1` : TOKEN_ROUTE, { method: "POST", credentials: "same-origin" });
  if (!response.ok) throw new Refused(response.status, "TOKEN_ROUTE_FAILED");
  const body = (await response.json()) as { access_token: string; expires_in: number };
  token = { value: body.access_token, until: Date.now() + (body.expires_in - 60) * 1000 };
  return token.value;
}

// ---------------------------------------------------------------- REST

/** One call to the API, retried when waiting helps and only then. */
async function call<T>(path: string, init: RequestInit = {}, attempts = 6): Promise<T> {
  let fresh = false;
  for (let attempt = 0; ; attempt++) {
    let status = 0;
    let code = "NETWORK";
    let retryAfter = 0;
    try {
      const response = await fetch(`${API}${path}`, {
        ...init,
        headers: { Authorization: `Bearer ${await accessToken(fresh)}` },
      });
      if (response.ok) return (await response.json()) as T;
      status = response.status;
      const detail = String(((await response.json().catch(() => ({}))) as { detail?: unknown }).detail ?? "");
      code = detail.split(":")[0].trim();
      retryAfter = Number(response.headers.get("Retry-After")) || 0;
    } catch (error) {
      if (error instanceof Refused) throw error; // from your token route
      // Otherwise the network: retried below like a 5xx.
    }
    // An expired token, or one the key's rotation retired: a fresh one, once.
    if (status === 401 && (code === "INVALID_JWT" || code === "CUSTOMER_ACCESS_REVOKED") && !fresh) {
      fresh = true;
      continue;
    }
    fresh = false;
    // 429 clears by waiting, except the daily guard, which reopens the next UTC day.
    // 5xx and the network are temporary. Everything else is an answer: stop.
    const retryable = status === 0 || (status === 429 && code !== "CUSTOMER_DAILY_CAP") || status >= 500;
    if (!retryable || attempt === attempts - 1) throw new Refused(status, code);
    await sleep(1000 * (retryAfter > 0 ? retryAfter : 2 ** attempt));
  }
}

interface CandlePage {
  candles: Bar[];
  next_before: string | null;
}

/** The latest `bars` bars (1000 by default), oldest first. */
export async function history(symbol: string, timeframe: string, bars = 1000): Promise<Bar[]> {
  const out: Bar[] = [];
  let before: string | null = null;
  while (out.length < bars) {
    const params = new URLSearchParams({ symbol, timeframe, limit: String(Math.min(5000, bars - out.length)) });
    if (before) params.set("before", before);
    const page: CandlePage = await call<CandlePage>(`/v1/candles?${params}`);
    out.unshift(...page.candles);
    before = page.next_before;
    if (!before) break; // nothing older
  }
  return out.slice(-bars);
}

// ---------------------------------------------------------------- the live stream

export interface StreamHandlers {
  onQuote?: (quote: Quote) => void;
  /** A bar: the history sent on (re)subscribe, then each bar as it closes. */
  onBar?: (channel: string, bar: Bar) => void;
  /** Called once when the stream gives up; the reason is a code to show or log. */
  onStop?: (reason: string) => void;
}

type Frame = { type: string; payload: Record<string, unknown> };

const OPEN = 1; // WebSocket.OPEN

/** Channels are `quote:<SYMBOL>` and `candle:<SYMBOL>:<TIMEFRAME>`, up to 64. */
export function openStream(channels: string[], handlers: StreamHandlers): { close(): void } {
  let socket: WebSocket | null = null;
  let stopped = false;
  let failures = 0; // consecutive, for the backoff
  let badTickets = 0;
  let revoked = 0;

  const stop = (reason: string) => {
    if (stopped) return;
    stopped = true;
    socket?.close(1000);
    handlers.onStop?.(reason);
  };

  // Each (re)subscribe sends the channels' recent history again, which is metered:
  // it is what a reconnect costs, and why the backoff below is not a tight loop.
  const subscribe = (on: WebSocket) => {
    if (on === socket && on.readyState === OPEN) {
      on.send(JSON.stringify({ type: "subscribe", request_id: "sub", payload: { channels } }));
    }
  };

  const onFrame = (on: WebSocket, { type, payload }: Frame) => {
    if (type === "subscribed") {
      failures = 0;
      badTickets = 0;
      revoked = 0;
      const rejected = (payload.rejected as string[] | undefined) ?? [];
      if (rejected.length) console.warn("not in your account's list:", rejected);
    } else if (type === "quote.update" || type === "quote.snapshot") {
      handlers.onQuote?.(payload as unknown as Quote);
    } else if (type === "candle.snapshot") {
      for (const bar of payload.candles as Bar[]) handlers.onBar?.(payload.channel as string, bar);
    } else if (type === "candle.bar") {
      // Live bars use short keys and carry no channel: rebuild both.
      const p = payload as Record<string, string | number>;
      handlers.onBar?.(`candle:${p.symbol}:${p.tf}`, {
        time: String(p.ts), open: String(p.o), high: String(p.h), low: String(p.l), close: String(p.c), volume: String(p.v),
      });
    } else if (type === "error") {
      // The plan's slices for this minute are spent and the subscribe was undone:
      // ask again once the minute has turned, on this same socket.
      if (payload.code === "CUSTOMER_MINUTE_CEILING") setTimeout(() => subscribe(on), 15_000);
      else if (payload.code === "CUSTOMER_DAILY_CAP") stop("CUSTOMER_DAILY_CAP");
      else console.warn("stream error:", payload.code);
    }
  };

  const reconnectLater = () => {
    if (stopped) return;
    const delay = Math.min(30_000, 1000 * 2 ** failures++) * (0.5 + Math.random() / 2);
    setTimeout(connect, delay);
  };

  async function connect() {
    if (stopped) return;
    let ticket: string;
    try {
      ticket = (await call<{ ticket: string }>("/v1/ws-ticket", { method: "POST" })).ticket;
    } catch (error) {
      // Access cut, trial ended, signed out of your site: stop. Anything else
      // (a deploy, the network, a busy minute) passes: try again later.
      return isAnswer(error) ? stop((error as Refused).code) : reconnectLater();
    }
    if (stopped) return; // closed while the ticket was on its way
    // Two subprotocols, the ticket as the second. Never in the URL: it is not read there.
    const on = new WebSocket(STREAM, ["adona.data.v1", `ticket.${ticket}`]);
    socket = on;
    on.onopen = () => subscribe(on);
    on.onmessage = (event) => onFrame(on, JSON.parse(event.data as string) as Frame);
    on.onclose = (event) => {
      if (stopped || on !== socket) return;
      if (event.code === 1008 && event.reason === "INVALID_TICKET" && ++badTickets < 2) return void connect();
      // A key rotation closes every socket this way: the next ticket call gets a fresh
      // token from your server, once. Refused again, the access really is cut. After a
      // pause, not at once: every end user is closed at the same instant.
      if (event.code === 1008 && event.reason === "CUSTOMER_ACCESS_REVOKED" && ++revoked < 2) return reconnectLater();
      if (event.code === 1008 && event.reason === "RATE_LIMITED") return reconnectLater();
      // Any other 1008 means stop (revoked, trial ended, connection limit): reconnecting
      // in a loop would be refused the same way. 1009: a message over 16 KiB.
      if (event.code === 1008 || event.code === 1009) return stop(event.reason || String(event.code));
      reconnectLater(); // 1011 is ours and temporary; 1006 and 1012 are the network or a deploy
    };
  }

  void connect();
  return { close: () => stop("closed") };
}

A script or a notebook: history to CSV

Python 3.9+, standard library only. Pulls every bar back to a date into a CSV and keeps a local store, so the next run asks for about as many bars as can have arrived since: closed history is paid for once. history.py

"""Pull candle history from adona-robot into CSV, and keep it up to date.

Python 3.9+, standard library only. Run it on your server or in a notebook:

    ADONA_API_KEY=adk_live_... python history.py EURUSD M1 2026-09-01

It pages backwards from now to the date you give and writes the bars oldest
first. What it has fetched is kept in a local store, so the next run asks for
about as many bars as can have arrived since, plus any older range the store
does not hold: closed history is paid for once.
"""

import csv
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from pathlib import Path

API = "https://api.adona-robot.com"
STORE = Path(".adona-store")
PAGE = 5000  # the most bars one page returns
SECONDS = {"S1": 1, "M1": 60, "M5": 300, "M15": 900, "H1": 3600, "H4": 14400, "D1": 86400}


class Refused(Exception):
    """A refusal to stop on. `code` is the part of `detail` before the first colon."""

    def __init__(self, status, code, detail):
        super().__init__(f"{status} {detail}")
        self.status, self.code = status, code


def call(method, path, *, token, body=None, attempts=6):
    """One call, retried when waiting helps and only then."""
    data = json.dumps(body).encode() if body is not None else None
    for attempt in range(attempts):
        request = urllib.request.Request(API + path, data=data, method=method)
        request.add_header("Authorization", f"Bearer {token}")
        if data is not None:
            request.add_header("Content-Type", "application/json")
        wait = 2**attempt  # 1, 2, 4... seconds
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            try:
                detail = str(json.loads(error.read()).get("detail", ""))
            except ValueError:
                detail = ""  # not ours: a proxy's page during a deploy
            code = detail.split(":", 1)[0].strip()
            # 429 clears by waiting, except the daily guard, which reopens the next
            # UTC day. 5xx is temporary. Everything else is an answer: stop.
            retryable = (error.code == 429 and code != "CUSTOMER_DAILY_CAP") or error.code >= 500
            if not retryable or attempt == attempts - 1:
                raise Refused(error.code, code, detail or str(error.code)) from None
            header = error.headers.get("Retry-After", "")
            wait = int(header) if header.isdigit() and int(header) > 0 else wait
        except OSError as error:  # the network: refused, reset, timed out (after HTTPError, a subclass)
            if attempt == attempts - 1:
                raise Refused(0, "NETWORK", str(error)) from None
        time.sleep(wait)
    raise AssertionError("unreachable")


def access_token(api_key, end_user_id="history-script"):
    """The key stays here; every other call carries the twelve-hour token."""
    return call("POST", "/v1/tokens", token=api_key, body={"end_user_id": end_user_id})["access_token"]


def page(token, symbol, timeframe, before, limit):
    """Up to `limit` bars older than `before` (newest if None), oldest first, and the next cursor."""
    params = {"symbol": symbol, "timeframe": timeframe, "limit": limit}
    if before:
        params["before"] = before
    result = call("GET", "/v1/candles?" + urllib.parse.urlencode(params), token=token)
    return result["candles"], result["next_before"]


def walk(token, symbol, timeframe, before, stop_at, first=None):
    """Pages back from `before` until a bar at or before `stop_at`, oldest first.

    It also stops at a null cursor: nothing older for this account (the end of the
    archive, or of your plan's history). On S1 a page is one day, so an empty page
    with a cursor is an empty day: keep going.
    """
    bars, limit = [], first or PAGE
    while True:
        candles, before = page(token, symbol, timeframe, before, limit)
        bars = candles + bars  # each page is older than the last
        if before is None or before <= stop_at:
            return bars
        limit = PAGE


def history(token, symbol, timeframe, since):
    """Every bar from `since` (YYYY-MM-DD, or an RFC3339 instant) to now, oldest first."""
    if len(since) == 10:
        since += "T00:00:00Z"  # compared as text with the bars' RFC3339 times
    STORE.mkdir(exist_ok=True)
    path = STORE / f"{symbol}-{timeframe}.json"
    known = json.loads(path.read_text()) if path.exists() else {}

    # The newest bars, back until they meet what the store already holds. Every bar
    # served is paid for, so the first page asks for roughly what can have arrived.
    first = PAGE
    if known:
        elapsed = time.time() - datetime.fromisoformat(max(known).replace("Z", "+00:00")).timestamp()
        first = max(2, min(PAGE, int(elapsed // SECONDS[timeframe]) + 2))
    fresh = walk(token, symbol, timeframe, None, max(known, default=since), first)
    # The newest bar can still be forming: served, never stored as final.
    forming = fresh.pop() if fresh else None

    # Older than the store, if it does not reach back to `since`. Asked again on
    # every such run: a plan with a deeper history (after a trial) answers with
    # more, and an answer with nothing older is an empty page, which costs no slices.
    if known and since < min(known):
        fresh += walk(token, symbol, timeframe, min(known), since)
    for bar in fresh:
        known[bar["time"]] = bar
    path.write_text(json.dumps(known))

    bars = [known[t] for t in sorted(known) if t >= since]
    if forming and forming["time"] >= since:
        bars = [bar for bar in bars if bar["time"] < forming["time"]] + [forming]
    return bars


def main():
    symbol, timeframe, since = sys.argv[1], sys.argv[2], sys.argv[3]
    try:
        token = access_token(os.environ["ADONA_API_KEY"])
        bars = history(token, symbol, timeframe, since)
    except Refused as refused:
        sys.exit(f"refused: {refused}")
    out = f"{symbol}-{timeframe}.csv"
    with open(out, "w", newline="") as file:
        writer = csv.DictWriter(file, fieldnames=["time", "open", "high", "low", "close", "volume"])
        writer.writeheader()
        writer.writerows(bars)  # prices stay strings, exactly as served
    print(f"{len(bars)} bars written to {out}")


if __name__ == "__main__":
    main()

Generated from /v1/openapi.json, version 0.1.0, refreshed every ten minutes.