TypeScript implementation for Saxo Bank OpenAPI authentication and real-time streaming with automatic token management.
Requirements:
- Node.js 18+ and
npm install .envconfigured with own app credentials.
Available Scripts:
- Authorization Code Flow →
npm run dev:auth-code - Authorization Code with PKCE →
npm run dev:auth-pkce - WebSocket Streaming →
npm run dev:stream-balances
- Install dependencies:
npm install - Copy environment file:
cp .env.example .env - Configure
.envwith credentials from developer portal
APP_NAME=your_app_name_here
APP_KEY=your_app_key_here
AUTHORIZATION_ENDPOINT=https://sim.logonvalidation.net/authorize
TOKEN_ENDPOINT=https://sim.logonvalidation.net/token
GRANT_TYPE=grant-type # "code" or "pkce"
OPEN_API_BASE_URL=https://gateway.saxobank.com/sim/openapi/
REDIRECT_URLS=http://localhost:3000/callback
APP_SECRET=your_app_secret_here # Only for Authorization Code flowAutomatically detects OAuth configuration and handles authentication to stream real-time balance updates:
npm run dev:stream-balancesStreams TotalValue, CollateralAvailable, and MarginAvailableForTrading with automatic token refresh at 85% of token lifetime.
Otherwise defaults to manual token entry, which also disables the refresh flow.
- Flow Selection: From the .env
GRANT_TYPEtocodeorpkce- only the required auth module loads- Or use a 24-hour simulation token. The streaming script will prompt you for it if you have not setup the .env file
- Token Refresh: Automatic refresh at 85% of token lifetime with 3-retry mechanism
- WebSocket Reauth: Seamless reauthorization on token refresh
- Connection Recovery: Auto-reconnection with subscription replacement
Logs all activity to stream_history/:
subscriptions.json- Current WebSocket connection with all subscriptions (replaced on new connection)control-messages.json- System control messages (last 50)
Each subscription tracks: snapshot, last 50 messages, status (active, replaced, deleted).
The OAuth 2.0 flow samples can also be run independently in order to obtain access tokens:
npm run dev:auth-code # Authorization Code Flow
npm run dev:auth-pkce # Authorization Code with PKCERegister apps at: https://www.developer.saxo/openapi/appmanagement
The app variables are what should populate the .env file.