### Cache-Control Header Example Source: https://docs.valr.com/ An example of an HTTP response header indicating caching directives. 'max-age' specifies the cache duration in seconds, and 'public' allows any cache to store the response. ```http cache-control: max-age=60,public ``` -------------------------------- ### Postman Environment Setup Source: https://docs.valr.com/ To facilitate API calls using Postman, set up a new environment with 'yourApiKey' and 'yourApiSecret' variables. Optionally, define 'yourSubAccountId' for impersonation. ```APIDOC ## Run in Postman ### Environment Variables 1. Create a new `Environment` in Postman. 2. Add the following variables: - `yourApiKey`: Your Valr API Key. - `yourApiSecret`: Your Valr API Secret. - `yourSubAccountId` (Optional): Your Valr Sub Account ID for impersonation. 3. Enable this environment while running requests. ``` -------------------------------- ### Postman Environment Setup for Valr API Source: https://docs.valr.com/ Configure your Postman environment with API Key and Secret. The optional subaccount ID can also be set here. ```postman Environment Variables: yourApiKey: Your API Key yourApiSecret: Your API Secret yourSubAccountId (Optional): Your Subaccount ID ``` -------------------------------- ### Generate HMAC SHA512 Signature for GET Request Source: https://docs.valr.com/ Use this test data to verify your HMAC SHA512 signature generation for a GET request. Ensure your API Secret is used correctly. ```text timestamp: 1558014486185 verb: GET path: /v1/account/balances API Secret: 4961b74efac86b25cce8fbe4c9811c4c7a787b7a5996660afcc2e287ad864363 ``` ```text 9d52c181ed69460b49307b7891f04658e938b21181173844b5018b2fe783a6d4c62b8e67a03de4d099e7437ebfabe12c56233b73c6a0cc0f7ae87e05f6289928 ``` -------------------------------- ### Cached GET Endpoints and Max-Age Source: https://docs.valr.com/ Lists of GET endpoints that are cached by default, along with their respective 'max-age' in seconds. This includes public and authenticated routes. ```plaintext *Public Routes* =============== /marketsummary (60) /:currencypair/marketsummary (10) /currencies (60) /pairs(60) /:currencyPair/orderbook (30) /:currencyPair/orderbook/full (30) /:currencyPair/trades (30) /ordertypes (60) /:currencypair/ordertypes (60) *Authenticated Routes* ====================== /marketdata (1) /fiat/:currency/banks (600) /fiat/:currency/auto-buy (60) /portfolio (1) ``` -------------------------------- ### Generate Request Signature in C# Source: https://docs.valr.com/ This C# code provides a method to sign API requests using HMAC-SHA512. It includes a helper function to convert the byte hash to a hex string and a utility to get the current Unix timestamp in milliseconds. ```csharp using System; using System.Text; using System.Security.Cryptography; public static string signRequest(string apiKeySecret, string timestamp, string verb, string path, string body = "") { var payload = timestamp + verb.ToUpper() + path + body; byte[] payloadBytes = Encoding.UTF8.GetBytes(payload); using (HMACSHA512 hmac = new HMACSHA512(Encoding.UTF8.GetBytes(apiKeySecret))) { byte[] hash = hmac.ComputeHash(payloadBytes); return toHexString(hash); } } private static string toHexString(byte[] hash) { StringBuilder result = new StringBuilder(hash.Length * 2); foreach(var b in hash) { result.Append(b.ToString("x2")); } return result.ToString(); } /* Timestamp in milliseconds. * The same timestamp should be used to generate request signature * as well as sent along in the X-VALR-TIMESTAMP header of the request */ private static string getTimestamp() { return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(); } ``` -------------------------------- ### Specific API Route Rate Limits Source: https://docs.valr.com/ Per-second rate limits applied on certain API routes to ensure higher throughput for placing and canceling orders. These limits reset at the start of each second and do not apply per IP or key. ```APIDOC ## Specific API Route Rate Limits ### Description Per-second rate limits are applied on certain API routes to ensure users can place and cancel orders at a higher rate. These limits reset at the start of the next second, and per IP/key limits do not apply. ### Routes - **Public calls v1** - Route: `/v1/public/*` - Method: `GET` - Rate limit: 30/m - **Public time v1** - Route: `/v1/public/time` - Method: `GET` - Rate limit: 20/s - **Public status v1** - Route: `/v1/public/status` - Method: `GET` - Rate limit: 20/s - **Public buckets v1** - Route: `/v1/public/*/buckets` - Method: `GET` - Rate limit: 20/s - **Batch orders v1** - Route: `/v1/batch/orders` - Method: `POST` - Rate limit: 400/s - **Delete orders v1** - Route: `/v1/orders` - Method: `DELETE` - Rate limit: 450/s - **Post orders v1** - Route: `/v1/orders` - Method: `POST` - Rate limit: 400/s - **Batch orders v2** - Route: `/v2/orders/modify` - Method: `PUT` - Rate limit: 400/s - **Loans v1** - Route: `/v1/loans/*` - Method: `POST, PUT, DELETE` - Rate limit: 1/s - **Create sub account v1** - Route: `/v1/account/subaccount` - Method: `POST` - Rate limit: 1/s - **Sub account transfer v1** - Route: `/v1/account/subaccount/transfer` - Method: `POST` - Rate limit: 20/s - **WebSocket new clients** - Route: `/ws` - Rate limit: 60/m - **WebSocket account write** - Route: `/ws/account` - Place: 400 p/s - Cancel: 450p/s - Batch: 400p/s - Modify: 400p/s ``` -------------------------------- ### Caching Directives Source: https://docs.valr.com/ GET requests are cached by default to improve latency and reduce server load. The Cache-Control header, including max-age and public directives, determines caching behavior. ```APIDOC ## Caching Directives ### Description To improve latency and reduce server load, some GET requests are cached by default using the HTTP Cache-Control Header. Directives like `max-age` and `public` determine caching duration and scope. ### Example Header `cache-control: max-age=60,public` ### Cached GET Endpoints and Max-Age (seconds) *Public Routes* ====================== - `/marketsummary` (60) - `/:currencypair/marketsummary` (10) - `/currencies` (60) - `/pairs` (60) - `/:currencyPair/orderbook` (30) - `/:currencyPair/orderbook/full` (30) - `/:currencyPair/trades` (30) - `/ordertypes` (60) - `/:currencypair/ordertypes` (60) *Authenticated Routes* ====================== - `/marketdata` (1) - `/fiat/:currency/banks` (600) - `/fiat/:currency/auto-buy` (60) - `/portfolio` (1) ``` -------------------------------- ### WebSocket API Authentication Source: https://docs.valr.com/ For WebSocket connections, pass the same authentication headers (X-VALR-API-KEY, X-VALR-SIGNATURE, X-VALR-TIMESTAMP) to the initial connection establishment call. ```APIDOC ## WebSocket API Authentication Pass the same three headers (**X-VALR-API-KEY**, **X-VALR-SIGNATURE**, **X-VALR-TIMESTAMP**) to the first call that establishes the WebSocket connection. ``` -------------------------------- ### REST API Authentication Headers Source: https://docs.valr.com/ To make authenticated REST API calls, include the following headers in your request. The X-VALR-SIGNATURE and X-VALR-TIMESTAMP headers are generated based on your request details and API secret. ```APIDOC ## Making an authenticated API call ### Headers - **X-VALR-API-KEY** : Your API Key - **X-VALR-SIGNATURE** : The `request signature` generated for your request. - **X-VALR-TIMESTAMP** : The same timestamp used to generate the `request signature`. - **X-VALR-SUB-ACCOUNT-ID** (Optional): Used to impersonate a subaccount. This value must also be included in the request signature generation. ### Request Signing Create a SHA512 HMAC hash using your API Secret and the values pertaining to your request (timestamp, HTTP verb, API path, body, subaccountId - when impersonating a subaccount). ``` -------------------------------- ### Valr API Authentication Headers Source: https://docs.valr.com/ Include these headers in your API requests for authentication. The signature is generated using your API Secret and request details. ```http X-VALR-API-KEY: Your API Key X-VALR-SIGNATURE: The generated request signature X-VALR-TIMESTAMP: The timestamp used for signature generation X-VALR-SUB-ACCOUNT-ID (Optional): Subaccount ID for impersonation ``` -------------------------------- ### Generate HMAC SHA512 Signature for POST Request Source: https://docs.valr.com/ Use this test data to verify your HMAC SHA512 signature generation for a POST request. Include the request body in the signature calculation. ```text timestamp: 1558017528946 verb: POST path: /v1/orders/market body: {"customerOrderId":"ORDER-000001","pair":"BTCUSDC","side":"BUY","quoteAmount":"80000"} API Secret: 4961b74efac86b25cce8fbe4c9811c4c7a787b7a5996660afcc2e287ad864363 ``` ```text 09f536e3dfdad58443f16010a97a0a21ad27486b7b8d6d4103170d885410ed77f037f1fa628474190d4f5c08ca12c1acc850901f1c2e75c6d906ec3b32b008d0 ``` -------------------------------- ### Valr API Pre-request Script for Postman Source: https://docs.valr.com/ This script generates request signatures and timestamps for Valr API requests in Postman. Ensure your API key and secret are set in the environment. It also handles subaccount impersonation via headers or environment variables. ```javascript /* Pre-requisite ================== 1) Create a new Environment in Postman. 2) Add two variables: "yourApiKey" and "yourApiSecret" to the Environment. Provide appropriate initial values for these variables. That is, the Api Key and Api Secret for your account. 3) Enable this environment for your requests. 4) For each request, this script generates the following two new environment variables: * requestSignature * requestTimestamp 5) Ensure that the following three headers are sent with every request: X-VALR-API-KEY: b9fb68df5485639d03c3171cf6e49b89e52fd78d5c313819b9c592b59c689f33 X-VALR-SIGNATURE: {{requestSignature}} X-VALR-TIMESTAMP: {{requestTimestamp}} Subaccounts ================== To perform a request impersonating a specific subaccount, the subaccount ID must be provided. The ID can be determined by using `Account/Subaccounts/Retrieve Subaccounts`. Once the ID is determined, it can be added to the request by either adding the `X-VALR-SUB-ACCOUNT-ID` header, with the ID as value, to the request directly, or by adding the variable {{yourSubAccountId}} to the Postman Environment. If both are provided, the header has precedence. If the variable is provided it will be added to every request. Please note: Requests that may only be performed on the Primary account will fail with a "401: Unauthorized" response if the subaccount ID is included. */ var YOUR_API_KEY = postman.getEnvironmentVariable('yourApiKey'); var YOUR_API_SECRET = postman.getEnvironmentVariable('yourApiSecret'); var subAccountHeader = pm.request.headers.find((header) => header.key === 'X-VALR-SUB-ACCOUNT-ID' && !header.disabled) var YOUR_SUB_ACCOUNT_ID = subAccountHeader ? subAccountHeader.value : postman.getEnvironmentVariable('yourSubAccountId'); var requestTimestamp = (new Date()).getTime(); function getPath(url) { var pathRegex = /(?:.+?\:\/\/.+?)?(\/.+)/; var result = url.match(pathRegex); return result && result.length > 1 ? result[1] : ''; } function getHmacDigest(httpMethod, requestUrl, requestBody) { var requestPath = getPath(requestUrl.toString()); if (httpMethod == 'GET' || !requestBody) { requestBody = ''; } var requestData = [requestTimestamp, httpMethod.toUpperCase(), requestPath, requestBody, YOUR_SUB_ACCOUNT_ID].join(""); var hmacDigest = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA512(requestData, YOUR_API_SECRET)); return hmacDigest; } postman.setEnvironmentVariable('requestSignature', getHmacDigest(pm.request.method, pm.request.url, pm.request.body)); postman.setEnvironmentVariable('requestTimestamp', requestTimestamp); if (YOUR_SUB_ACCOUNT_ID && YOUR_SUB_ACCOUNT_ID > 0 && !subAccountHeader) { pm.request.headers.add({ key: 'X-VALR-SUB-ACCOUNT-ID', value: `${YOUR_SUB_ACCOUNT_ID}` }); } ``` -------------------------------- ### REST API Rate Limits Source: https://docs.valr.com/ REST requests are limited by both API key and IP address. Both limits apply concurrently and reset every minute. ```APIDOC ## REST API Rate Limits ### Description REST requests are limited by both API key and IP address. Both limits apply at the same time and reset every minute. ### Limits - **Per API Key**: 2000 requests per minute - **Per IP Address**: 1200 requests per minute ### Error Response If either limit is exceeded, the request is rejected with HTTP Status Code 429 Too Many Requests. ``` -------------------------------- ### WebSocket Rate Limits Source: https://docs.valr.com/ WebSocket rate limits are enforced per IP address only. API key limits do not apply, and all connections from the same IP share a single limit pool. ```APIDOC ## WebSocket Rate Limits ### Description WebSocket rate limits are enforced per IP address only. API key limits do not apply. All connections from the same IP share a single limit pool. Multiple bots or accounts on the same server will not increase throughput. ### Error Response If the WebSocket rate limit is exceeded, the server will send a JSON response: ```json { "type": "RATE_LIMIT_EXCEEDED" } ``` ``` -------------------------------- ### Generate HMAC-SHA512 Digest Source: https://docs.valr.com/ This snippet shows how to update an HMAC-SHA512 instance with request body bytes and finalize the digest. It includes error handling for algorithm or key issues. Ensure the `hmacSHA512` object is properly initialized before use. ```java hmacSHA512.update(body.getBytes()); byte[] digest = hmacSHA512.doFinal(); return toHexString(digest); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException("Unable to sign request", e); } ``` -------------------------------- ### Generate Request Signature in Golang Source: https://docs.valr.com/ This Golang function generates a SHA512 HMAC signature for API requests. It correctly formats the timestamp and concatenates the verb, path, and body before hashing. ```go import ( "crypto/hmac" "crypto/sha512" "encoding/hex" "strconv" "strings" "time" ) func signRequest(apiSecret string, timestamp time.Time, verb string, path string, body string) string { // Create a new Keyed-Hash Message Authentication Code (HMAC) using SHA512 and API Secret mac := hmac.New(sha512.New, []byte(apiSecret)) // Convert timestamp to nanoseconds then divide by 1000000 to get the milliseconds timestampString := strconv.FormatInt(timestamp.UnixNano()/1000000, 10) mac.Write([]byte(timestampString)) mac.Write([]byte(strings.ToUpper(verb))) mac.Write([]byte(path)) mac.Write([]byte(body)) // Gets the byte hash from HMAC and converts it into a hex string return hex.EncodeToString(mac.Sum(nil)) } ``` -------------------------------- ### Generate Request Signature in Python 3.x Source: https://docs.valr.com/ This Python 3 function signs API requests using HMAC-SHA512. It concatenates the timestamp, verb, path, and body to create the payload for hashing. ```python import time import hashlib import hmac def sign_request(api_key_secret, timestamp, verb, path, body = ""): """Signs the request payload using the api key secret api_key_secret - the api key secret timestamp - the unix timestamp of this request e.g. int(time.time()*1000) verb - Http verb - GET, POST, PUT or DELETE path - path excluding host name, e.g. '/v1/withdraw body - http request body as a string, optional """ payload = "{}{}{}{}".format(timestamp,verb.upper(),path,body) message = bytearray(payload,'utf-8') signature = hmac.new( bytearray(api_key_secret,'utf-8'), message, digestmod=hashlib.sha512).hexdigest() return signature ``` -------------------------------- ### Convert Byte Array to Hex String Source: https://docs.valr.com/ Utility method to convert a byte array into its hexadecimal string representation. This is commonly used for displaying cryptographic digests. ```java public static String toHexString(byte[] a) { StringBuilder sb = new StringBuilder(a.length * 2); for (byte b : a) sb.append(String.format("x", b)); return sb.toString(); } ``` -------------------------------- ### Generate Request Signature in Java Source: https://docs.valr.com/ This Java method generates a SHA512 HMAC signature for API requests. It requires the API key secret, timestamp, HTTP verb, path, and an optional request body. ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.time.Clock; /** * Signs the request payload using the api key secret * * @param apiKeySecret - the api key secret * @param timestamp - the unix timestamp of this request e.g. Clock.systemUTC().millis() * @param verb - Http verb - GET, POST, PUT or DELETE * @param path - path excluding host name, e.g. '/v1/withdraw' * @param body - http request body as a string, optional * @return the signature of the request */ public static String signRequest(String apiKeySecret, String timestamp, String verb, String path, String body) { try { Mac hmacSHA512 = Mac.getInstance("HmacSHA512"); SecretKeySpec secretKeySpec = new SecretKeySpec(apiKeySecret.getBytes(), "HmacSHA512"); hmacSHA512.init(secretKeySpec); hmacSHA512.update(timestamp.getBytes()); hmacSHA512.update(verb.toUpperCase().getBytes()); hmacSHA512.update(path.getBytes()); // The body is optional and should only be included if it exists if (!body.isEmpty()) { hmacSHA512.update(body.getBytes()); } byte[] rawHmac = hmacSHA512.doFinal(); return bytesToHex(rawHmac); } catch (InvalidKeyException | NoSuchAlgorithmException e) { // Handle exceptions appropriately in a real application e.printStackTrace(); return null; } } /** * Converts a byte array to a hexadecimal string. * @param bytes The byte array to convert. * @return The hexadecimal string representation. */ private static String bytesToHex(byte[] bytes) { StringBuilder hexString = new StringBuilder(2 * bytes.length); for (byte b : bytes) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } // Example of how to get the timestamp in milliseconds public static String getTimestamp() { return String.valueOf(Clock.systemUTC().millis()); } } ``` -------------------------------- ### Generate Request Signature in Node.js Source: https://docs.valr.com/ Use this Node.js function to generate a SHA512 HMAC signature for your API requests. Ensure the timestamp, verb, path, and body are concatenated in the correct order. ```javascript const crypto = require('crypto'); function signRequest(apiSecret, timestamp, verb, path, body = '') { return crypto .createHmac("sha512", apiSecret) .update(timestamp.toString()) .update(verb.toUpperCase()) .update(path) .update(body) .digest("hex"); } ``` -------------------------------- ### WebSocket Rate Limit Exceeded Message Source: https://docs.valr.com/ This JSON object is sent by the server when a WebSocket rate limit is exceeded. API key limits do not apply to WebSockets. ```json { "type": "RATE_LIMIT_EXCEEDED" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.