### Fetch User Profile with Access Token Source: https://partner.tradovate.com/overview/quick-setup/5-minute-quickstart This snippet demonstrates how to make an authenticated API call to retrieve user profile information using the obtained access token. Examples are provided in TypeScript and Python, making a GET request to the `/auth/me` endpoint with the 'Authorization' header. ```typescript const userResponse = await fetch('https://live.tradovateapi.com/v1/auth/me', { headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' } }); const user = await userResponse.json(); console.log('Current user:', user); ``` ```python headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } user_response = requests.get( 'https://live.tradovateapi.com/v1/auth/me', headers=headers ) user = user_response.json() print(f'Current user: {user}') ``` -------------------------------- ### GET /auth/me Source: https://partner.tradovate.com/overview/quick-setup/5-minute-quickstart Retrieve the current user's profile information using the obtained access token. This endpoint confirms successful authentication and provides user-specific details. ```APIDOC ## GET /auth/me ### Description Fetches the profile information of the authenticated user. ### Method GET ### Endpoint `https://live.tradovateapi.com/v1/auth/me` ### Parameters #### Request Headers - **Authorization** (string) - Required - Bearer token obtained from the /auth/accesstokenrequest endpoint (e.g., `Bearer YOUR_ACCESS_TOKEN`). - **Content-Type** (string) - Required - Set to `application/json`. ### Request Example ```json { "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` ### Response #### Success Response (200) - **id** (integer) - The user's unique identifier. - **name** (string) - The user's name. - **email** (string) - The user's email address. - **accountIds** (array of integers) - A list of associated account IDs. #### Response Example ```json { "id": 12345, "name": "John Doe", "email": "john.doe@example.com", "accountIds": [1001, 1002] } ``` ``` -------------------------------- ### Secure Token Storage Example (TypeScript) Source: https://partner.tradovate.com/overview/quick-setup/auth-overview Provides a basic implementation for securely storing and retrieving access tokens using encryption and localStorage. It includes methods for storing, getting, encrypting, and decrypting token data. This is a simplified example; production environments require more robust encryption and storage solutions. ```typescript // In production, use secure storage mechanisms class SecureTokenStorage { private encryptionKey: string; constructor(encryptionKey: string) { this.encryptionKey = encryptionKey; } storeToken(token: string, userId: number, expiresAt: number): void { const data = JSON.stringify({ token, userId, expiresAt }); const encrypted = this.encrypt(data); // Store in secure location (database, encrypted file, etc.) localStorage.setItem('tradovate_auth', encrypted); } getStoredToken(): { token: string; userId: number; expiresAt: number } | null { const encrypted = localStorage.getItem('tradovate_auth'); if (!encrypted) return null; try { const decrypted = this.decrypt(encrypted); return JSON.parse(decrypted); } catch { return null; } } private encrypt(data: string): string { // Implement encryption logic return Buffer.from(data).toString('base64'); // Simplified example } private decrypt(encrypted: string): string { // Implement decryption logic return Buffer.from(encrypted, 'base64').toString(); // Simplified example } } ``` -------------------------------- ### Authenticate with Tradovate API Source: https://partner.tradovate.com/overview/quick-setup/5-minute-quickstart This section demonstrates how to authenticate with the Tradovate API to obtain an access token. It shows examples in TypeScript, Python, and cURL, utilizing the credentials obtained in the previous step. The POST request sends a JSON payload to the `/auth/accesstokenrequest` endpoint. ```typescript const YOUR_CREDENTIALS = { name: "", password: "", //or API dedicated password appId: "", appVersion: "1.0.0", cid: 1234, // use your API key ID presented when key is created sec: "" // use the secret presented when key is created } const response = await fetch('https://live.tradovateapi.com/v1/auth/accesstokenrequest', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(YOUR_CREDENTIALS) }); const { accessToken } = await response.json(); console.log('Access token:', accessToken); ``` ```python import requests import json your_credentials = json.dumps({ 'name': '', 'password': '', # or API dedicated password 'appId': '', 'appVersion': '1.0.0', 'cid': 1234, # use your API key ID presented when key is created 'sec': '' # use the secret presented when key is created }) response = requests.post( 'https://live.tradovateapi.com/v1/auth/accesstokenrequest', json=your_credentials ) access_token = response.json()['accessToken'] print(f'Access token: {access_token}') ``` ```cURL curl -X POST https://live.tradovateapi.com/v1/auth/accesstokenrequest \ -H "Content-Type: application/json" \ -d '{ "name": "your_username", "password": "your_password", "appId": "your_api_key", "environment": "demo" }' ``` -------------------------------- ### Query All Entities using GET Request Source: https://partner.tradovate.com/overview/core-concepts/architecture-overview Shows how to retrieve all entities of a particular type using the `/list` endpoint with an HTTP GET request. This pattern is demonstrated for retrieving all fills. Examples are provided in cURL, TypeScript, Python, and C#, all requiring authentication. ```bash curl -X GET \ --header 'Accept: application/json' \ --header 'Authorization: Bearer YOUR_TOKEN' \ 'https://demo.tradovateapi.com/v1/fill/list' ``` ```typescript const response = await fetch(`${baseUrl}/fill/list`, { headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json", }, }); const fills = await response.json(); ``` ```python response = requests.get( f'{base_url}/fill/list', headers={'Authorization': f'Bearer {access_token}'} ) fills = response.json() ``` ```csharp List result = apiInstance.FillList(); ``` -------------------------------- ### Get Product Fee Params Request Example (OpenAPI) Source: https://partner.tradovate.com/api/rest-api-endpoints/contract-library/get-product-fee-params This snippet shows an example of how to structure a request to the Get Product Fee Params endpoint using the OpenAPI specification. It defines the request body schema, including the `productIds` array. ```yaml openapi: 3.1.1 info: title: Get Product Fee Params version: endpoint_contractLibrary.getProductFeeParams paths: /contract/getproductfeeparams: post: operationId: get-product-fee-params summary: Get Product Fee Params description: '### Query the a product''s fee parameters.' tags: - - subpackage_contractLibrary parameters: - name: Authorization in: header description: >- Bearer authentication of the form `Bearer `, where token is your auth token. required: true schema: type: string responses: '200': description: ProductFeeParamsResponse content: application/json: schema: $ref: '#/components/schemas/ProductFeeParamsResponse' requestBody: content: application/json: schema: $ref: '#/components/schemas/GetProductFeeParams' components: schemas: GetProductFeeParams: type: object properties: productIds: type: array items: type: integer format: int64 required: - productIds ProductMargin: type: object properties: id: type: integer format: int64 initialMargin: type: number format: double maintenanceMargin: type: number format: double timestamp: type: string format: date-time required: - initialMargin - maintenanceMargin - timestamp ProductFeeParams: type: object properties: clearingFee: type: number format: double clearingCurrencyId: type: integer format: int64 exchangeFee: type: number format: double exchangeCurrencyId: type: integer format: int64 nfaFee: type: number format: double nfaCurrencyId: type: integer format: int64 brokerageFee: type: number format: double brokerageCurrencyId: type: integer format: int64 ipFee: type: number format: double ipCurrencyId: type: integer format: int64 commission: type: number format: double commissionCurrencyId: type: integer format: int64 orderRoutingFee: type: number format: double orderRoutingCurrencyId: type: integer format: int64 productId: type: integer format: int64 dayMargin: type: number format: double nightMargin: type: number format: double fullMargin: $ref: '#/components/schemas/ProductMargin' required: - productId ProductFeeParamsResponse: type: object properties: params: type: array items: $ref: '#/components/schemas/ProductFeeParams' required: - params ``` -------------------------------- ### Tradovate API: Get User Profile (GET /auth/me) Source: https://partner.tradovate.com/overview/quick-setup/first-api-call This snippet shows how to retrieve your user profile information after successfully authenticating and obtaining an access token. It details the GET /auth/me request, which requires the access token in the Authorization header. An example of the user profile response is also provided. This call is fundamental for verifying your account details. ```http GET /auth/me Host: api.tradovate.com Authorization: Bearer YOUR_ACCESS_TOKEN ``` ```json { "userId": "12345", "name": "John Doe", "email": "john.doe@example.com" } ``` -------------------------------- ### Example JSON Report Request for Tradovate Subscriptions Source: https://partner.tradovate.com/resources/admin-dashboards/reports This JSON object demonstrates how to request a 'Subscriptions' report in CSV format from Tradovate. It includes setting parameters like subscription type, start date, and end date, along with timezone information. ```json { "name": "Subscriptions", "representationType": "csv", "timezone": -240, //Eastern time "params": [ { "name": "subscriptionType", "value": "Tradovate" }, { "name": "startDate", "value": "08/01/2022" }, { "name": "endDate", "value": "09/01/2022" } ] } ``` -------------------------------- ### Implement Tradovate WebSocket Client Start Method (TypeScript) Source: https://partner.tradovate.com/overview/core-concepts/web-sockets/connection-overview Details the `start` method for the Tradovate WebSocket client. This method is responsible for initiating the client, fetching an access token using `TokenManager`, and establishing the WebSocket connection via `connectWebSocket`. It includes basic error handling and cleanup procedures. ```typescript async start(): Promise { console.log('šŸš€ Tradovate WebSocket Client - TypeScript Version'); console.log('='.repeat(50)); try { // Get access token (will fetch new one if needed) await this.tokenManager.getAccessToken(); // Connect to WebSocket await this.connectWebSocket(); } catch (error) { console.error('āŒ Error starting client:', (error as Error).message); this.cleanup(); } } ``` -------------------------------- ### Install dotenv Package for Node.js Source: https://partner.tradovate.com/overview/quick-setup/auth-overview This command installs the 'dotenv' package, which is essential for loading environment variables from a .env file into your Node.js application. This is a common practice for managing sensitive configuration data. ```bash npm install dotenv ``` -------------------------------- ### Query Data by ID using GET Request Source: https://partner.tradovate.com/overview/core-concepts/architecture-overview Demonstrates how to retrieve a specific entity using its unique ID via a GET request. This pattern is applicable for various entities like orders. The examples show the cURL command, and implementations in TypeScript and Python, requiring an access token for authorization. ```bash curl -X GET \ --header 'Accept: application/json' \ --header 'Authorization: Bearer YOUR_TOKEN' \ 'https://demo.tradovateapi.com/v1/order/item?id=1000' ``` ```typescript const response = await fetch(`${baseUrl}/order/item?id=1000`, { headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json", }, }); const order = await response.json(); ``` ```python import requests response = requests.get( f'{base_url}/order/item', params={'id': 1000}, headers={ 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } ) order = response.json() ``` -------------------------------- ### WebSocket Message Format and Example Source: https://partner.tradovate.com/overview/core-concepts/architecture-overview Demonstrates the new-line delimited format for WebSocket messages in the Tradovate API, including the structure for sending requests and an example of sending a request to retrieve account details. ```plaintext \n\n\n ``` ```javascript ws.send( 'account/items\n1\n\n{\"ids\": [123456, 234567, 345678]}' ); ``` -------------------------------- ### Tradovate API: Authenticate and Get Access Token (POST /auth/accesstokenrequest) Source: https://partner.tradovate.com/overview/quick-setup/first-api-call This snippet demonstrates how to obtain an access token, which is required for all subsequent API requests. It outlines the request structure for the POST /auth/accesstokenrequest endpoint and provides an example of the expected response containing the access token. Ensure you have your Partner API credentials before making this call. ```http POST /auth/accesstokenrequest Host: api.tradovate.com Content-Type: application/json { "apiKey": "YOUR_API_KEY", "apiSecret": "YOUR_API_SECRET" } ``` ```json { "accessToken": "YOUR_ACCESS_TOKEN", "expiresIn": 3600 } ``` -------------------------------- ### POST /auth/accesstokenrequest Source: https://partner.tradovate.com/overview/quick-setup/5-minute-quickstart Obtain an access token by sending your API credentials to the /auth/accesstokenrequest endpoint. This token is required for subsequent authenticated API calls. ```APIDOC ## POST /auth/accesstokenrequest ### Description Requests an access token using API credentials. This token is essential for authenticating subsequent API requests. ### Method POST ### Endpoint `https://live.tradovateapi.com/v1/auth/accesstokenrequest` ### Parameters #### Request Body - **name** (string) - Required - Your Tradovate username. - **password** (string) - Required - Your Tradovate password or API-dedicated password. - **appId** (string) - Required - The name of your API key. - **appVersion** (string) - Required - The version of your application, typically '1.0.0'. - **cid** (integer) - Required - Your API key ID. - **sec** (string) - Required - Your API secret key. ### Request Example ```json { "name": "", "password": "", "appId": "", "appVersion": "1.0.0", "cid": 1234, "sec": "" } ``` ### Response #### Success Response (200) - **accessToken** (string) - The generated access token. - **expiresIn** (integer) - The duration in seconds until the token expires. #### Response Example ```json { "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expiresIn": 3600 } ``` ``` -------------------------------- ### BigQuery SQL Table Join Query Source: https://partner.tradovate.com/resources/data-analytics/big-query-api Illustrates how to perform table joins in BigQuery SQL to combine data from multiple related tables. This example joins user, trading permissions, and account tables based on common IDs. ```sql select user.name, user.id, account.name, account.id from `ep_MyOrgName.users` user inner join `ep_MyOrgName.demo_tradingPermissions` tradingPermission on user.id = tradingPermission.userId inner join `ep_MyOrgName.demo_accounts` account on tradingPermission.accountId = account.id ``` -------------------------------- ### SQL: Data Filtering Example Source: https://partner.tradovate.com/resources/data-analytics/end-of-day-reports Shows how to implement data filtering using a WHERE clause with conditions based on declared variables. This example filters cash balances by trade date, user ID, and account ID. ```sql where cash.tradeDate <= endDate and (userId = -1 or a.userId = userId) and (accountId = -1 or cash.accountId = accountId) ``` -------------------------------- ### Retrieve Contract Items by IDs (Go) Source: https://partner.tradovate.com/api/rest-api-endpoints/contract-library/contract-items Fetches contract items from the Tradovate API using their IDs. This Go example demonstrates making an HTTP GET request with the necessary Authorization header. ```go package main import ( "fmt" "net/http" "io" ) func main() { url := "https://demo.tradovateapi.com/v1/contract/items?ids=%5B1%5D" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("Authorization", "Bearer ") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` -------------------------------- ### BigQuery SQL Text Search Source: https://partner.tradovate.com/resources/data-analytics/big-query-api Demonstrates how to use the `LIKE` operator in BigQuery SQL for text-based searching within a table column. This query finds all accounts whose names start with a specific prefix. ```sql select * from `ep_MyOrgName.demo_accounts` account where account.name like '%PREFIX%' ``` -------------------------------- ### GET /auth/me Source: https://partner.tradovate.com/overview/quick-setup/first-api-call Retrieve your user profile information after successful authentication. ```APIDOC ## GET /auth/me ### Description Retrieve your user profile information. This endpoint requires a valid access token in the Authorization header. ### Method GET ### Endpoint /auth/me ### Parameters #### Query Parameters - **Authorization** (string) - Required - Bearer token for authentication (e.g., "Bearer YOUR_ACCESS_TOKEN"). ### Request Example ```json { "Authorization": "Bearer YOUR_ACCESS_TOKEN" } ``` ### Response #### Success Response (200) - **userId** (string) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "userId": "user123", "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Get Product Fee Params Response (JSON) Source: https://partner.tradovate.com/api/rest-api-endpoints/contract-library/get-product-fee-params_explorer=true This is a sample JSON response from the Tradovate API's getProductFeeParams endpoint. It details various fees and margin requirements for a given product, including clearing, exchange, NFA, brokerage, and order routing fees, along with margin details. ```json { "params": [ { "productId": 1, "clearingFee": 1.1, "clearingCurrencyId": 1, "exchangeFee": 1.1, "exchangeCurrencyId": 1, "nfaFee": 1.1, "nfaCurrencyId": 1, "brokerageFee": 1.1, "brokerageCurrencyId": 1, "ipFee": 1.1, "ipCurrencyId": 1, "commission": 1.1, "commissionCurrencyId": 1, "orderRoutingFee": 1.1, "orderRoutingCurrencyId": 1, "dayMargin": 1.1, "nightMargin": 1.1, "fullMargin": { "initialMargin": 1.1, "maintenanceMargin": 1.1, "timestamp": "2024-01-15T09:30:00Z", "id": 1 } } ] } ``` -------------------------------- ### POST /v1/contract/getproductfeeparams Source: https://partner.tradovate.com/api/rest-api-endpoints/contract-library/get-product-fee-params Queries a product's fee parameters by providing a list of product IDs. ```APIDOC ## POST /v1/contract/getproductfeeparams ### Description Queries a product's fee parameters. ### Method POST ### Endpoint https://demo.tradovateapi.com/v1/contract/getproductfeeparams ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer authentication of the form `Bearer `, where token is your auth token. #### Request Body - **productIds** (array[integer]) - Required - A list of product IDs for which to retrieve fee parameters. ### Request Example ```json { "productIds": [ 123, 456 ] } ``` ### Response #### Success Response (200) - **params** (array[object]) - An array of product fee parameter objects. - **clearingFee** (number) - The clearing fee for the product. - **clearingCurrencyId** (integer) - The ID of the currency for the clearing fee. - **exchangeFee** (number) - The exchange fee for the product. - **exchangeCurrencyId** (integer) - The ID of the currency for the exchange fee. - **nfaFee** (number) - The NFA fee for the product. - **nfaCurrencyId** (integer) - The ID of the currency for the NFA fee. - **brokerageFee** (number) - The brokerage fee for the product. - **brokerageCurrencyId** (integer) - The ID of the currency for the brokerage fee. - **ipFee** (number) - The IP fee for the product. - **ipCurrencyId** (integer) - The ID of the currency for the IP fee. - **commission** (number) - The commission for the product. - **commissionCurrencyId** (integer) - The ID of the currency for the commission. - **orderRoutingFee** (number) - The order routing fee for the product. - **orderRoutingCurrencyId** (integer) - The ID of the currency for the order routing fee. - **productId** (integer) - The ID of the product. - **dayMargin** (number) - The day margin for the product. - **nightMargin** (number) - The night margin for the product. - **fullMargin** (object) - The full margin details for the product. - **initialMargin** (number) - The initial margin amount. - **maintenanceMargin** (number) - The maintenance margin amount. - **timestamp** (string) - The timestamp of the margin data. #### Response Example ```json { "params": [ { "clearingFee": 0.10, "clearingCurrencyId": 1, "exchangeFee": 0.20, "exchangeCurrencyId": 1, "nfaFee": 0.05, "nfaCurrencyId": 1, "brokerageFee": 0.02, "brokerageCurrencyId": 1, "ipFee": 0.01, "ipCurrencyId": 1, "commission": 0.50, "commissionCurrencyId": 1, "orderRoutingFee": 0.005, "orderRoutingCurrencyId": 1, "productId": 123, "dayMargin": 500.00, "nightMargin": 400.00, "fullMargin": { "initialMargin": 600.00, "maintenanceMargin": 550.00, "timestamp": "2023-10-27T10:00:00Z" } } ] } ``` ``` -------------------------------- ### GET /fill/list Source: https://partner.tradovate.com/overview/core-concepts/architecture-overview Retrieves a list of all fill entities. ```APIDOC ## GET /fill/list ### Description Retrieves a list of all fill entities. ### Method GET ### Endpoint `/v1/fill/list` ### Request Example #### cURL ```bash curl -X GET \ --header 'Accept: application/json' \ --header 'Authorization: Bearer YOUR_TOKEN' \ 'https://demo.tradovateapi.com/v1/fill/list' ``` #### TypeScript ```typescript const response = await fetch(`${baseUrl}/fill/list`, { headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json", }, }); const fills = await response.json(); ``` #### Python ```python response = requests.get( f'{base_url}/fill/list', headers={'Authorization': f'Bearer {access_token}'} ) fills = response.json() ``` #### C# ```csharp List result = apiInstance.FillList(); ``` ### Response #### Success Response (200) - A list of fill objects. The exact structure of a fill object is not detailed here but would typically include details like trade ID, quantity, price, etc. #### Response Example (Example response structure would depend on the actual Fill object definition, but would be nested within the `d` field as per the general response format.) ```json { "i": 1, "s": 200, "d": [ // Array of fill objects ] } ``` ``` -------------------------------- ### Get Product Fee Params (cURL) Source: https://partner.tradovate.com/api/rest-api-endpoints/contract-library/get-product-fee-params_explorer=true This snippet demonstrates how to fetch product fee parameters from the Tradovate API using cURL. It requires an authorization token and sends a JSON payload with product IDs. The response contains detailed fee information for the requested products. ```curl curl -X POST https://demo.tradovateapi.com/v1/contract/getproductfeeparams \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ \ "productIds": [ \ 1 \ ] \ }' ``` -------------------------------- ### WebSocket Data Streaming Source: https://partner.tradovate.com/overview/core-concepts/architecture-overview Real-time data streaming via WebSockets, including message format, examples, and response types (open, data, heartbeat, close). ```APIDOC ## WebSocket Data Streaming ### Description This section details the real-time data streaming capabilities provided by the Tradovate Partner API using WebSockets. It covers the message format for sending requests, handling different response frame types, and the structure of server event messages. ### WebSocket Message Format WebSockets use a new-line delimited format: ``` \n\n\n ``` ### Example WebSocket Message ```javascript // Get details on a list of accounts ws.send( 'account/items\n1\n\n{\"ids\": [123456, 234567, 345678]}' ); ``` ### WebSocket Response Frame Types Responses from the WebSocket server are indicated by a single character: - `o`: Open frame (sent upon session establishment). - `a`: Data frame (followed by a JSON array). - `h`: Heartbeat frame (sent periodically; client must respond with `[]`). - `c`: Close frame (sent before connection closure). ### Server Event Message Structure Data frames (`a`) can contain server events, typically in the following JSON format: ```json { "e": "props", "d": { "entityType": "order", "eventType": "Created", "entity": { ... } // Structure identical to REST API entity response } } ``` #### Event Types (`e` field): - `"props"`: Entity creation, update, or deletion notification. The `"d"` field contains `entityType`, `eventType` (`Created`, `Updated`, `Deleted`), and the `entity` object. - `"shutdown"`: Notification before graceful shutdown. The `"d"` field contains `reasonCode` and an optional `reason`. - `"md"`, `"chart"`: Used by market data feed services (details in Market Data section). - `"clock"`: Market Replay clock synchronization message. ``` -------------------------------- ### Application Startup and Fatal Error Handling (Node.js) Source: https://partner.tradovate.com/overview/core-concepts/web-sockets/connection-overview This Node.js code initiates the Tradovate WebSocket client and includes error handling for fatal startup errors. If the client fails to start, it logs the error message and exits the process with a non-zero status code. ```javascript // Start the application const client = new TradovateWebSocketClient(); client.start().catch((error) => { console.error("šŸ’„ Fatal error:", error.message); process.exit(1); }); ``` -------------------------------- ### Configure Tradovate API Credentials (.env) Source: https://partner.tradovate.com/overview/quick-setup/auth-overview Sets up environment variables for Tradovate API configuration, including the API URL. This file should be created in the project root and kept secure. It is used to specify the endpoint for authentication requests. ```bash # Tradovate API Configuration TRADOVATE_API_URL=https://live-api.staging.ninjatrader.dev/v1 # Use https://live.tradovateapi.com/v1/auth/accesstokenrequest for production ``` -------------------------------- ### Use Tradovate Access Token in JavaScript GET Requests Source: https://partner.tradovate.com/api/rest-api-endpoints/authentication/access-token-request This JavaScript snippet shows how to use a previously obtained access token to make authenticated GET requests to the Tradovate API. It demonstrates how to include the `Authorization: Bearer ` header in the `fetch` request. The example shows fetching a list of accounts using the `/account/list` endpoint. ```javascript //use the Authorization: Bearer schema in API POST and GET requests //simple /account/list endpoint requires no body or query async function getAccounts() { let response = await fetch(URL + '/account/list', { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` //Access Token use in HTTP requests } }) let result = await response.json() return result } ``` -------------------------------- ### Obtain API Credentials Payload Source: https://partner.tradovate.com/overview/quick-setup/5-minute-quickstart This JSON payload is used to request an access token from the Tradovate API. It requires your username, password, API key name, application version, API key ID, and API secret. Ensure your API credentials are kept secure and not exposed. ```json { "name": "", "password": "", //or API dedicated password "appId": "", "appVersion": "1.0.0", "cid": 1234, // use your API key ID presented when key is created "sec": "" // use the secret presented when key is created } ``` -------------------------------- ### Initialize Tradovate WebSocket Client (TypeScript) Source: https://partner.tradovate.com/overview/core-concepts/web-sockets/connection-overview Sets up the Tradovate WebSocket client, including token management, reconnection logic, and event handlers for process termination. It defines the core class structure and initializes necessary managers. The client handles authentication and connection lifecycle. ```typescript // index.ts import WebSocket from "ws"; import readline from "readline"; import { TokenManager } from "./token-manager.js"; import { ReconnectionManager } from "./reconnection-manager.js"; import { ENDPOINTS } from "./config.js"; import { SocketMessage } from "./types.js"; export class TradovateWebSocketClient { private ws: WebSocket | null = null; private tokenManager: TokenManager; private reconnectionManager: ReconnectionManager; private isAuthenticated: boolean = false; private authenticationSent: boolean = false; private heartbeatTimer: NodeJS.Timeout | null = null; private readonly heartbeatInterval: number = 2500; // 2.5 seconds private heartbeatsSent: number = 0; private lastServerMessageTime: number = Date.now(); private readonly serverTimeoutMs: number = 10000; // 10 seconds without server message = dead connection private heartbeatTimeoutTimer: NodeJS.Timeout | null = null; private requestIdCounter: number = 2; // Start at 2 (0=auth, 1=sync) private syncCompleted: boolean = false; constructor() { this.tokenManager = new TokenManager(); this.reconnectionManager = new ReconnectionManager({ maxReconnectAttempts: 10, initialReconnectDelay: 1000, // 1 second maxReconnectDelay: 60000, // 60 seconds }); // Setup reconnection callbacks this.reconnectionManager.setOnReconnect(async () => { await this.handleReconnect(); }); this.reconnectionManager.setOnMaxAttemptsReached(() => { this.cleanup(); }); } async start(): Promise {} private async connectWebSocket(): Promise { return new Promise((resolve, reject) => {}); } private async authenticate(): Promise {} private handleMessage(data: WebSocket.Data): void {} private startHeartbeat(): void {} private stopHeartbeat(): void {} private resetHeartbeatTimer(): void {} private sendHeartbeat(): void {} private resetConnectionState(): void {} private async handleReconnect(): Promise {} private cleanup(): void {} } // Handle unhandled rejections and errors process.on("unhandledRejection", (reason, promise) => { console.error("āš ļø Unhandled Rejection:", reason); // Don't exit, let reconnection logic handle it }); process.on("uncaughtException", (error) => { console.error("āš ļø Uncaught Exception:", error.message); // Don't exit, let reconnection logic handle it }); // Handle process termination process.on("SIGINT", () => { console.log("\nšŸ›‘ Received SIGINT, shutting down gracefully..."); process.exit(0); }); process.on("SIGTERM", () => { console.log("\nšŸ›‘ Received SIGTERM, shutting down gracefully..."); process.exit(0); }); // Start the application const client = new TradovateWebSocketClient(); client.start().catch((error) => { console.error("šŸ’„ Fatal error:", error.message); process.exit(1); }); ``` -------------------------------- ### Renew Access Token with Tradovate API (Ruby) Source: https://partner.tradovate.com/api/rest-api-endpoints/authentication/renew-access-token Provides a Ruby example for renewing an access token through the Tradovate API. It utilizes the Net::HTTP library to make the authenticated GET request. ```ruby require 'uri' require 'net/http' url = URI("https://demo.tradovateapi.com/v1/auth/renewaccesstoken") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Get.new(url) request["Authorization"] = 'Bearer ' response = http.request(request) puts response.read_body ``` -------------------------------- ### Fetch User Info with Access Token (TypeScript) Source: https://partner.tradovate.com/overview/quick-setup/auth-overview Demonstrates how to make an authenticated GET request to the /auth/me endpoint using an access token. It sends the token in the Authorization header as a Bearer token and handles success and error responses. Dependencies include the fetch API and a predefined TRADOVATE_API_URL. ```typescript /** * Demonstrates how to use the access token with the /auth/me endpoint */ async function getUserInfo(accessToken: string) { const ME_ENDPOINT = `${TRADOVATE_API_URL}/auth/me`; try { console.log("--- Fetching User Information ---"); const response = await fetch(ME_ENDPOINT, { method: 'GET', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' } }); if (response.ok) { const userData = await response.json(); console.log("\nāœ… SUCCESS: User data retrieved."); console.log("-----------------------------------------"); console.log(`User ID: ${userData.id}`); console.log(`Username: ${userData.name}`); console.log(`Email: ${userData.email || 'Not provided'}`); console.log("-----------------------------------------"); return userData; } else { console.error("\nāŒ ERROR: Failed to fetch user information."); console.error("Status:", response.status); const errorData = await response.json().catch(() => ({})); if (errorData.errorText) { console.error("Details:", errorData.errorText); } throw new Error(`HTTP ${response.status}: ${response.statusText}`); } } catch (error) { console.error("\nāŒ NETWORK ERROR: Could not fetch user information."); console.error("Details:", error.message); throw error; } } // Example usage combining both functions async function authenticateAndGetUserInfo() { try { // First, get the access token const authResponse = await requestAccessToken(); // Then use it to get user information if (authResponse && authResponse.accessToken) { await getUserInfo(authResponse.accessToken); } } catch (error) { console.error("Authentication flow failed:", error.message); process.exit(1); } } ``` -------------------------------- ### API Key Structure Example (JSON) Source: https://partner.tradovate.com/overview/quick-setup/api-keys Illustrates the expected JSON structure for an API key used for authentication with the Tradovate Partner API. This object contains fields like name, password, appId, appVersion, sec, and cid. ```json { "name": "string", "password": "string", "appId": "string", "appVersion": "1.0", "sec": "string", "cid": 0 } ``` -------------------------------- ### Renew Access Token with Tradovate API (C#) Source: https://partner.tradovate.com/api/rest-api-endpoints/authentication/renew-access-token Shows a C# example for renewing an access token with the Tradovate API using the RestSharp library. It demonstrates setting the Authorization header for a GET request. ```csharp var client = new RestClient("https://demo.tradovateapi.com/v1/auth/renewaccesstoken"); var request = new RestRequest(Method.GET); request.AddHeader("Authorization", "Bearer "); IRestResponse response = client.Execute(request); ``` -------------------------------- ### Renew Access Token with Tradovate API (PHP) Source: https://partner.tradovate.com/api/rest-api-endpoints/authentication/renew-access-token This PHP code example uses the GuzzleHttp client to renew an access token via the Tradovate API. It configures the necessary headers for the GET request. ```php request('GET', 'https://demo.tradovateapi.com/v1/auth/renewaccesstoken', [ 'headers' => [ 'Authorization' => 'Bearer ', ], ]); echo $response->getBody(); ``` -------------------------------- ### Configure .gitignore for Environment Variables Source: https://partner.tradovate.com/overview/quick-setup/auth-overview This snippet shows how to add '.env' to your '.gitignore' file. This is a crucial security measure to prevent your sensitive API credentials from being accidentally committed to your version control system. ```gitignore .env ``` -------------------------------- ### Use Access Token for API Calls (JavaScript) Source: https://partner.tradovate.com/api/rest-api-endpoints/authentication/access-token-request_explorer=true This JavaScript example shows how to use an obtained access token to make authenticated GET requests to the Tradovate API. It demonstrates adding the 'Authorization: Bearer ' header to the request. ```javascript //use the Authorization: Bearer schema in API POST and GET requests //simple /account/list endpoint requires no body or query async function getAccounts() { let response = await fetch(URL + '/account/list', { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` //Access Token use in HTTP requests } }) let result = await response.json() return result } ``` -------------------------------- ### Fetch User Data (Go) Source: https://partner.tradovate.com/api/rest-api-endpoints/authentication/me Illustrates fetching basic user data via the Tradovate API's /auth/me endpoint using Go's net/http package. This example requires an 'Authorization' header containing a bearer token. It prints the HTTP response and the response body. ```go package main import ( "fmt" "net/http" "io" ) func main() { url := "https://demo.tradovateapi.com/v1/auth/me" req, _ := http.NewRequest("GET", url, nil) req.Header.Add("Authorization", "Bearer ") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` -------------------------------- ### Retrieve Contract by Name using Tradovate API (PHP) Source: https://partner.tradovate.com/api/rest-api-endpoints/contract-library/contract-find This PHP example utilizes the Guzzle HTTP client to interact with the Tradovate API's /contract/find endpoint. It sends a GET request with the required Authorization header and echoes the response body. ```php request('GET', 'https://demo.tradovateapi.com/v1/contract/find?name=name', [ 'headers' => [ 'Authorization' => 'Bearer ', ], ]); echo $response->getBody(); ?> ``` -------------------------------- ### Use Tradovate Access Token in API Requests (JavaScript) Source: https://partner.tradovate.com/api/rest-api-endpoints/authentication/access-token-request This JavaScript code illustrates how to use an obtained access token to make authenticated GET requests to Tradovate API endpoints. It shows how to include the `Authorization: Bearer ` header in the `fetch` request. The example specifically demonstrates fetching account lists. ```javascript //use the Authorization: Bearer schema in API POST and GET requests //simple /account/list endpoint requires no body or query async function getAccounts(accessToken) { let response = await fetch(URL + '/account/list', { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` //Access Token use in HTTP requests } }) let result = await response.json() return result } ``` -------------------------------- ### Tradovate WebSocket Client Initialization (TypeScript) Source: https://partner.tradovate.com/overview/core-concepts/web-sockets/connection-overview This TypeScript code initializes the TradovateWebSocketClient, setting up dependencies like TokenManager and ReconnectionManager. It configures reconnection attempts, delays, and defines callbacks for reconnection events and maximum attempt handling. ```typescript // index.ts import WebSocket from "ws"; import readline from "readline"; import { TokenManager } from "./token-manager.js"; import { ReconnectionManager } from "./reconnection-manager.js"; import { ENDPOINTS } from "./config.js"; import { SocketMessage } from "./types.js"; export class TradovateWebSocketClient { private ws: WebSocket | null = null; private tokenManager: TokenManager; private reconnectionManager: ReconnectionManager; private isAuthenticated: boolean = false; private authenticationSent: boolean = false; private heartbeatTimer: NodeJS.Timeout | null = null; private readonly heartbeatInterval: number = 2500; // 2.5 seconds private heartbeatsSent: number = 0; private lastServerMessageTime: number = Date.now(); private readonly serverTimeoutMs: number = 10000; // 10 seconds without server message = dead connection private heartbeatTimeoutTimer: NodeJS.Timeout | null = null; private requestIdCounter: number = 2; // Start at 2 (0=auth, 1=sync) private syncCompleted: boolean = false; constructor() { this.tokenManager = new TokenManager(); this.reconnectionManager = new ReconnectionManager({ maxReconnectAttempts: 10, initialReconnectDelay: 1000, // 1 second maxReconnectDelay: 60000, // 60 seconds }); // Setup reconnection callbacks this.reconnectionManager.setOnReconnect(async () => { await this.handleReconnect(); }); this.reconnectionManager.setOnMaxAttemptsReached(() => { this.cleanup(); }); ``` -------------------------------- ### Start WebSocket Heartbeat - TypeScript Source: https://partner.tradovate.com/overview/core-concepts/web-sockets/connection-overview Starts a periodic heartbeat mechanism to keep the WebSocket connection alive. It sets an interval timer that calls `sendHeartbeat` and also starts a separate timer to check for server timeouts. If a heartbeat timer is already running, it is cleared first. Dependencies include `setInterval`, `clearInterval`, and custom methods `sendHeartbeat` and `startHeartbeatTimeoutChecker`. ```typescript private startHeartbeat(): void { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); } console.log("šŸ’“ Starting heartbeat timer (2.5s interval) after authentication"); this.heartbeatTimer = setInterval(() => { this.sendHeartbeat(); }, this.heartbeatInterval); // Start the timeout checker this.startHeartbeatTimeoutChecker(); } ``` -------------------------------- ### SQL: Parameterized Query Setup Source: https://partner.tradovate.com/resources/data-analytics/end-of-day-reports Demonstrates how to declare and set variables for a SQL query, allowing for flexible report generation. Parameters include the end date, user ID, and account ID, enabling dynamic filtering and customization. ```sql -- Set your parameters at the top declare endDate datetime; declare userId int64; declare accountId int64; -- Configure for your specific needs set endDate = '2024-04-04'; -- Today's date set accountId = -1; -- -1 for all accounts, or specific ID set userId = -1; -- -1 for all users, or specific ID ```