# Rotate the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
# Needs openssl, curl and OLYMPEX_API_KEY_ID, OLYMPEX_SECRET_KEY, OLYMPEX_PASSPHRASE.
# To retry, set IDEMPOTENCY_KEY to the value of the first attempt and keep BODY the same.
IDEMPOTENCY_KEY="${IDEMPOTENCY_KEY:-$(openssl rand -hex 16)}"
METHOD=POST
ENDPOINT=/accounts/me/keys/rotate
QUERY=''
BODY='{"gracePeriodSeconds":86400,"mode":"graceful","reason":"scheduled rotation"}'
TS="${OLYMPEX_TIMESTAMP:-$(date +%s)}"
NONCE="${OLYMPEX_NONCE:-$(openssl rand -hex 12)}"
BODY_HASH="$(printf '%s' "$BODY" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')"
VALUE_INFO="$(printf '%s\n%s\n%s' "$TS" "$NONCE" "$BODY_HASH")"
MESSAGE="$(printf 'OLPX-HMAC-SHA256-V2\n%s\n%s\n%s\n%s\n%s\n%s' "$TS" "$NONCE" "$METHOD" "/api/v1$ENDPOINT" "$QUERY" "$BODY_HASH")"
# The response holds the new secret key: it goes to a file only you can read, not to the terminal.
( umask 077
curl -sS -X "$METHOD" "https://api-rest.olympex.io/api/v1$ENDPOINT${QUERY:+?$QUERY}" \
-H "content-type: application/json" \
-H "idempotency-key: $IDEMPOTENCY_KEY" \
-H "x-api-key-id: $OLYMPEX_API_KEY_ID" \
-H "x-value-info: $(printf '%s' "$VALUE_INFO" | openssl base64 -A)" \
-H "x-passphrase: $OLYMPEX_PASSPHRASE" \
-H "x-signature: $(printf '%s' "$MESSAGE" | openssl dgst -sha256 -hmac "$OLYMPEX_SECRET_KEY" -binary | od -An -v -tx1 | tr -d ' \n')" \
--data-raw "$BODY" -o olympex-rotation-response.json )
// Node.js 18+. Rotates the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { credentialsFromEnv, olympexRequest, OlympexApiError } from "./sign-request.ts"; // /authentication/sign-requests
type Rotation = { apiKeyId: string; secretKey: string; previousApiKeyId: string; previousKeyExpiresAt: string; secretRecoverableUntil: string };
const PENDING = "olympex-rotation.pending.json"; // this rotation's Idempotency-Key and body, kept until the new key is stored
const ENV_FILE = "olympex.env.new"; // stand-in for your secrets manager
const current = credentialsFromEnv();
// One Idempotency-Key per rotation, saved with the body before the first attempt.
if (!existsSync(PENDING)) {
const body = { gracePeriodSeconds: 86400, mode: "graceful", reason: "scheduled rotation" };
writeFileSync(PENDING, JSON.stringify({ idempotencyKey: randomUUID(), body }), { mode: 0o600, flag: "wx" });
}
const { idempotencyKey, body } = JSON.parse(readFileSync(PENDING, "utf8"));
// A retry with the same Idempotency-Key, body and signing key returns the same new key.
const rotate = async (): Promise<Rotation> => {
for (let attempt = 1; ; attempt++) {
try {
return await olympexRequest<Rotation>("POST", "/accounts/me/keys/rotate", body, current, { "Idempotency-Key": idempotencyKey });
} catch (error) {
const retryable = !(error instanceof OlympexApiError) || error.status >= 500; // no response or 5xx; a 429 needs up to an hour
if (!retryable || attempt === 4) throw error; // PENDING stays: run again within 15 minutes to retry the same rotation
await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
}
}
};
const rotation = await rotate();
// Store the new key before anything else, then confirm that it signs.
writeFileSync(ENV_FILE, `OLYMPEX_API_KEY_ID=${rotation.apiKeyId}\nOLYMPEX_SECRET_KEY=${rotation.secretKey}\n`, { mode: 0o600, flag: "wx" });
rmSync(PENDING);
await olympexRequest("GET", "/accounts/me/keys", undefined, { ...current, apiKeyId: rotation.apiKeyId, secretKey: rotation.secretKey });
console.log(`New key ${rotation.apiKeyId} works and is in ${ENV_FILE}. ${rotation.previousApiKeyId} signs until ${rotation.previousKeyExpiresAt}.`);
# Python 3.8+. Rotates the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
import json
import os
import time
import uuid
import requests
from sign_request import OlympexApiError, credentials_from_env, olympex_request # /authentication/sign-requests
PENDING = "olympex-rotation.pending.json" # this rotation's Idempotency-Key and body, kept until the new key is stored
ENV_FILE = "olympex.env.new" # stand-in for your secrets manager
current = credentials_from_env()
def write_private(path, text):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as file:
file.write(text)
# One Idempotency-Key per rotation, saved with the body before the first attempt.
if not os.path.exists(PENDING):
body = {"gracePeriodSeconds": 86400, "mode": "graceful", "reason": "scheduled rotation"}
write_private(PENDING, json.dumps({"idempotency_key": str(uuid.uuid4()), "body": body}))
with open(PENDING) as file:
pending = json.load(file)
# A retry with the same Idempotency-Key, body and signing key returns the same new key.
for attempt in range(1, 5):
try:
rotation = olympex_request(
"POST", "/accounts/me/keys/rotate", pending["body"], current, headers={"Idempotency-Key": pending["idempotency_key"]}
)
break
except (OlympexApiError, requests.RequestException) as error:
status = getattr(error, "status", None) # None: no response
if (status is not None and status < 500) or attempt == 4: # a 429 needs up to an hour
raise # PENDING stays: run again within 15 minutes to retry the same rotation
time.sleep(2**attempt)
# Store the new key before anything else, then confirm that it signs.
write_private(ENV_FILE, f"OLYMPEX_API_KEY_ID={rotation['apiKeyId']}\nOLYMPEX_SECRET_KEY={rotation['secretKey']}\n")
os.remove(PENDING)
olympex_request("GET", "/accounts/me/keys", credentials={**current, "api_key_id": rotation["apiKeyId"], "secret_key": rotation["secretKey"]})
print(f"New key {rotation['apiKeyId']} works and is in {ENV_FILE}. {rotation['previousApiKeyId']} signs until {rotation['previousKeyExpiresAt']}.")
{
"success": true,
"data": {
"apiKeyId": "00000000-0000-4000-8000-000000000001",
"secretKey": "aol_DocsTestVector_notARealSecret_000000000",
"previousApiKeyId": "00000000-0000-4000-8000-000000000000",
"previousKeyExpiresAt": "2026-10-31T13:06:45.989Z",
"secretRecoverableUntil": "2026-10-30T13:21:45.989Z"
},
"meta": {
"requestId": "GDxwAjXioAMEPWA=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Idempotency-Key header is required",
"details": []
},
"meta": {
"requestId": "GDxv6g_loAMEZ7w=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "CONFLICT",
"message": "Idempotency key was reused with a different payload",
"details": []
},
"meta": {
"requestId": "GDxwCjFXIAMEZQw=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many key administration requests",
"details": []
},
"meta": {
"requestId": "GQ1D7ixyIAMEPHA=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"message": "Forbidden"
}
Rotate an API key
Replace the API key that signs the request with a new API key ID and secret key, keeping the old one valid for a grace period or revoking it at once.
# Rotate the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
# Needs openssl, curl and OLYMPEX_API_KEY_ID, OLYMPEX_SECRET_KEY, OLYMPEX_PASSPHRASE.
# To retry, set IDEMPOTENCY_KEY to the value of the first attempt and keep BODY the same.
IDEMPOTENCY_KEY="${IDEMPOTENCY_KEY:-$(openssl rand -hex 16)}"
METHOD=POST
ENDPOINT=/accounts/me/keys/rotate
QUERY=''
BODY='{"gracePeriodSeconds":86400,"mode":"graceful","reason":"scheduled rotation"}'
TS="${OLYMPEX_TIMESTAMP:-$(date +%s)}"
NONCE="${OLYMPEX_NONCE:-$(openssl rand -hex 12)}"
BODY_HASH="$(printf '%s' "$BODY" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')"
VALUE_INFO="$(printf '%s\n%s\n%s' "$TS" "$NONCE" "$BODY_HASH")"
MESSAGE="$(printf 'OLPX-HMAC-SHA256-V2\n%s\n%s\n%s\n%s\n%s\n%s' "$TS" "$NONCE" "$METHOD" "/api/v1$ENDPOINT" "$QUERY" "$BODY_HASH")"
# The response holds the new secret key: it goes to a file only you can read, not to the terminal.
( umask 077
curl -sS -X "$METHOD" "https://api-rest.olympex.io/api/v1$ENDPOINT${QUERY:+?$QUERY}" \
-H "content-type: application/json" \
-H "idempotency-key: $IDEMPOTENCY_KEY" \
-H "x-api-key-id: $OLYMPEX_API_KEY_ID" \
-H "x-value-info: $(printf '%s' "$VALUE_INFO" | openssl base64 -A)" \
-H "x-passphrase: $OLYMPEX_PASSPHRASE" \
-H "x-signature: $(printf '%s' "$MESSAGE" | openssl dgst -sha256 -hmac "$OLYMPEX_SECRET_KEY" -binary | od -An -v -tx1 | tr -d ' \n')" \
--data-raw "$BODY" -o olympex-rotation-response.json )
// Node.js 18+. Rotates the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { credentialsFromEnv, olympexRequest, OlympexApiError } from "./sign-request.ts"; // /authentication/sign-requests
type Rotation = { apiKeyId: string; secretKey: string; previousApiKeyId: string; previousKeyExpiresAt: string; secretRecoverableUntil: string };
const PENDING = "olympex-rotation.pending.json"; // this rotation's Idempotency-Key and body, kept until the new key is stored
const ENV_FILE = "olympex.env.new"; // stand-in for your secrets manager
const current = credentialsFromEnv();
// One Idempotency-Key per rotation, saved with the body before the first attempt.
if (!existsSync(PENDING)) {
const body = { gracePeriodSeconds: 86400, mode: "graceful", reason: "scheduled rotation" };
writeFileSync(PENDING, JSON.stringify({ idempotencyKey: randomUUID(), body }), { mode: 0o600, flag: "wx" });
}
const { idempotencyKey, body } = JSON.parse(readFileSync(PENDING, "utf8"));
// A retry with the same Idempotency-Key, body and signing key returns the same new key.
const rotate = async (): Promise<Rotation> => {
for (let attempt = 1; ; attempt++) {
try {
return await olympexRequest<Rotation>("POST", "/accounts/me/keys/rotate", body, current, { "Idempotency-Key": idempotencyKey });
} catch (error) {
const retryable = !(error instanceof OlympexApiError) || error.status >= 500; // no response or 5xx; a 429 needs up to an hour
if (!retryable || attempt === 4) throw error; // PENDING stays: run again within 15 minutes to retry the same rotation
await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
}
}
};
const rotation = await rotate();
// Store the new key before anything else, then confirm that it signs.
writeFileSync(ENV_FILE, `OLYMPEX_API_KEY_ID=${rotation.apiKeyId}\nOLYMPEX_SECRET_KEY=${rotation.secretKey}\n`, { mode: 0o600, flag: "wx" });
rmSync(PENDING);
await olympexRequest("GET", "/accounts/me/keys", undefined, { ...current, apiKeyId: rotation.apiKeyId, secretKey: rotation.secretKey });
console.log(`New key ${rotation.apiKeyId} works and is in ${ENV_FILE}. ${rotation.previousApiKeyId} signs until ${rotation.previousKeyExpiresAt}.`);
# Python 3.8+. Rotates the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
import json
import os
import time
import uuid
import requests
from sign_request import OlympexApiError, credentials_from_env, olympex_request # /authentication/sign-requests
PENDING = "olympex-rotation.pending.json" # this rotation's Idempotency-Key and body, kept until the new key is stored
ENV_FILE = "olympex.env.new" # stand-in for your secrets manager
current = credentials_from_env()
def write_private(path, text):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as file:
file.write(text)
# One Idempotency-Key per rotation, saved with the body before the first attempt.
if not os.path.exists(PENDING):
body = {"gracePeriodSeconds": 86400, "mode": "graceful", "reason": "scheduled rotation"}
write_private(PENDING, json.dumps({"idempotency_key": str(uuid.uuid4()), "body": body}))
with open(PENDING) as file:
pending = json.load(file)
# A retry with the same Idempotency-Key, body and signing key returns the same new key.
for attempt in range(1, 5):
try:
rotation = olympex_request(
"POST", "/accounts/me/keys/rotate", pending["body"], current, headers={"Idempotency-Key": pending["idempotency_key"]}
)
break
except (OlympexApiError, requests.RequestException) as error:
status = getattr(error, "status", None) # None: no response
if (status is not None and status < 500) or attempt == 4: # a 429 needs up to an hour
raise # PENDING stays: run again within 15 minutes to retry the same rotation
time.sleep(2**attempt)
# Store the new key before anything else, then confirm that it signs.
write_private(ENV_FILE, f"OLYMPEX_API_KEY_ID={rotation['apiKeyId']}\nOLYMPEX_SECRET_KEY={rotation['secretKey']}\n")
os.remove(PENDING)
olympex_request("GET", "/accounts/me/keys", credentials={**current, "api_key_id": rotation["apiKeyId"], "secret_key": rotation["secretKey"]})
print(f"New key {rotation['apiKeyId']} works and is in {ENV_FILE}. {rotation['previousApiKeyId']} signs until {rotation['previousKeyExpiresAt']}.")
{
"success": true,
"data": {
"apiKeyId": "00000000-0000-4000-8000-000000000001",
"secretKey": "aol_DocsTestVector_notARealSecret_000000000",
"previousApiKeyId": "00000000-0000-4000-8000-000000000000",
"previousKeyExpiresAt": "2026-10-31T13:06:45.989Z",
"secretRecoverableUntil": "2026-10-30T13:21:45.989Z"
},
"meta": {
"requestId": "GDxwAjXioAMEPWA=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Idempotency-Key header is required",
"details": []
},
"meta": {
"requestId": "GDxv6g_loAMEZ7w=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "CONFLICT",
"message": "Idempotency key was reused with a different payload",
"details": []
},
"meta": {
"requestId": "GDxwCjFXIAMEZQw=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many key administration requests",
"details": []
},
"meta": {
"requestId": "GQ1D7ixyIAMEPHA=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"message": "Forbidden"
}
POST /accounts/me/keys/rotate creates a new API key for your account and retires the key that signs the request. Olympex generates the new API key ID and secret key and returns the secret key in this response. Your passphrase doesn’t change. In graceful mode, the default, the old key keeps working for a grace period, so you can deploy the new key without downtime. In compromised mode, Olympex revokes the old key at once.
The API console doesn’t call the key endpoints: run them from your server, where your credentials live.
Choose the mode
mode | Old key after the call | Use it when |
|---|---|---|
graceful (default) | rotating: it signs requests until previousKeyExpiresAt, gracePeriodSeconds from now, then becomes expired. | You rotate on a schedule, or replace a key you have no reason to distrust. |
compromised | revoked at once. previousKeyExpiresAt is the time of the rotation. | The old secret key or passphrase may be exposed. |
gracePeriodSeconds goes from 60 to 604800 (7 days), and defaults to 86400 (24 hours). Choose a period longer than it takes you to deploy the new key everywhere, then revoke the old key as soon as your services use the new one.
Only an active key can start a rotation. A rotating key that tries gets 404 NOT_FOUND with the message "Key not found". The new key can rotate again during the grace period, which leaves more than one rotating key: list your keys and revoke the ones you no longer use.
Retry with the same Idempotency-Key
TheIdempotency-Key header identifies one rotation, not one attempt. Generate it once, for example as a UUID, and store it with the exact body before you send the first attempt. If an attempt times out or returns a 5xx, sign it again (with a new timestamp and nonce) and send it with the same Idempotency-Key, the same body and the same signing key. Olympex then returns the same new API key ID and secret key, and creates no other key.
- The window is 15 minutes. A retry returns the secret key until
secretRecoverableUntil. After that, no endpoint returns that secret key again, so store it as soon as you receive it. - Change nothing. The same
Idempotency-Keywith another body or another signing key returns409 CONFLICTwith the message"Idempotency key was reused with a different payload". Key order and whitespace don’t count: Olympex compares the canonical body. - A new rotation needs a new key. Never generate a new
Idempotency-Keyto retry an attempt whose outcome you don’t know: that starts a second rotation if the first one succeeded. On a409, list your keys first. - A graceful retry also needs the old key. It must still be
rotating, so the retry deadline is the earlier ofsecretRecoverableUntilandpreviousKeyExpiresAt. - Retries count toward the rate limit. An account can send 5 rotation requests per hour, retries with the same
Idempotency-Keyincluded, on every plan. Over that, the API answers429RATE_LIMIT_EXCEEDEDand the request doesn’t run: wait up to an hour, then send it again with the sameIdempotency-Keyand body. Don’t retry a429sooner. A503SERVICE_UNAVAILABLEmeans Olympex refused the rotation for now and changed nothing: retry it after a few seconds.
compromised rotation revokes the old key in the same call, so if you lose its response, you can’t retry it: the gateway rejects the old key with 403, and the account has no key you hold. Email partners@olympex.io with the API key IDs (never a secret key or the passphrase), and create a new account if you need to keep working.Store the new key first
The response carriesCache-Control: no-store. Keep it out of caches, logs and error reports.
- Write
apiKeyIdandsecretKeyto your secrets manager before you report success. Keep the passphrase: it signs for the new key too. - Confirm that the new key works, for example by calling
GET /accounts/me/keyswith it. - Deploy the new key to every service that signs requests.
- Revoke the old key once nothing uses it, instead of waiting for
previousKeyExpiresAt.
# Rotate the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
# Needs openssl, curl and OLYMPEX_API_KEY_ID, OLYMPEX_SECRET_KEY, OLYMPEX_PASSPHRASE.
# To retry, set IDEMPOTENCY_KEY to the value of the first attempt and keep BODY the same.
IDEMPOTENCY_KEY="${IDEMPOTENCY_KEY:-$(openssl rand -hex 16)}"
METHOD=POST
ENDPOINT=/accounts/me/keys/rotate
QUERY=''
BODY='{"gracePeriodSeconds":86400,"mode":"graceful","reason":"scheduled rotation"}'
TS="${OLYMPEX_TIMESTAMP:-$(date +%s)}"
NONCE="${OLYMPEX_NONCE:-$(openssl rand -hex 12)}"
BODY_HASH="$(printf '%s' "$BODY" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')"
VALUE_INFO="$(printf '%s\n%s\n%s' "$TS" "$NONCE" "$BODY_HASH")"
MESSAGE="$(printf 'OLPX-HMAC-SHA256-V2\n%s\n%s\n%s\n%s\n%s\n%s' "$TS" "$NONCE" "$METHOD" "/api/v1$ENDPOINT" "$QUERY" "$BODY_HASH")"
# The response holds the new secret key: it goes to a file only you can read, not to the terminal.
( umask 077
curl -sS -X "$METHOD" "https://api-rest.olympex.io/api/v1$ENDPOINT${QUERY:+?$QUERY}" \
-H "content-type: application/json" \
-H "idempotency-key: $IDEMPOTENCY_KEY" \
-H "x-api-key-id: $OLYMPEX_API_KEY_ID" \
-H "x-value-info: $(printf '%s' "$VALUE_INFO" | openssl base64 -A)" \
-H "x-passphrase: $OLYMPEX_PASSPHRASE" \
-H "x-signature: $(printf '%s' "$MESSAGE" | openssl dgst -sha256 -hmac "$OLYMPEX_SECRET_KEY" -binary | od -An -v -tx1 | tr -d ' \n')" \
--data-raw "$BODY" -o olympex-rotation-response.json )
// Node.js 18+. Rotates the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { credentialsFromEnv, olympexRequest, OlympexApiError } from "./sign-request.ts"; // /authentication/sign-requests
type Rotation = { apiKeyId: string; secretKey: string; previousApiKeyId: string; previousKeyExpiresAt: string; secretRecoverableUntil: string };
const PENDING = "olympex-rotation.pending.json"; // this rotation's Idempotency-Key and body, kept until the new key is stored
const ENV_FILE = "olympex.env.new"; // stand-in for your secrets manager
const current = credentialsFromEnv();
// One Idempotency-Key per rotation, saved with the body before the first attempt.
if (!existsSync(PENDING)) {
const body = { gracePeriodSeconds: 86400, mode: "graceful", reason: "scheduled rotation" };
writeFileSync(PENDING, JSON.stringify({ idempotencyKey: randomUUID(), body }), { mode: 0o600, flag: "wx" });
}
const { idempotencyKey, body } = JSON.parse(readFileSync(PENDING, "utf8"));
// A retry with the same Idempotency-Key, body and signing key returns the same new key.
const rotate = async (): Promise<Rotation> => {
for (let attempt = 1; ; attempt++) {
try {
return await olympexRequest<Rotation>("POST", "/accounts/me/keys/rotate", body, current, { "Idempotency-Key": idempotencyKey });
} catch (error) {
const retryable = !(error instanceof OlympexApiError) || error.status >= 500; // no response or 5xx; a 429 needs up to an hour
if (!retryable || attempt === 4) throw error; // PENDING stays: run again within 15 minutes to retry the same rotation
await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
}
}
};
const rotation = await rotate();
// Store the new key before anything else, then confirm that it signs.
writeFileSync(ENV_FILE, `OLYMPEX_API_KEY_ID=${rotation.apiKeyId}\nOLYMPEX_SECRET_KEY=${rotation.secretKey}\n`, { mode: 0o600, flag: "wx" });
rmSync(PENDING);
await olympexRequest("GET", "/accounts/me/keys", undefined, { ...current, apiKeyId: rotation.apiKeyId, secretKey: rotation.secretKey });
console.log(`New key ${rotation.apiKeyId} works and is in ${ENV_FILE}. ${rotation.previousApiKeyId} signs until ${rotation.previousKeyExpiresAt}.`);
# Python 3.8+. Rotates the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
import json
import os
import time
import uuid
import requests
from sign_request import OlympexApiError, credentials_from_env, olympex_request # /authentication/sign-requests
PENDING = "olympex-rotation.pending.json" # this rotation's Idempotency-Key and body, kept until the new key is stored
ENV_FILE = "olympex.env.new" # stand-in for your secrets manager
current = credentials_from_env()
def write_private(path, text):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as file:
file.write(text)
# One Idempotency-Key per rotation, saved with the body before the first attempt.
if not os.path.exists(PENDING):
body = {"gracePeriodSeconds": 86400, "mode": "graceful", "reason": "scheduled rotation"}
write_private(PENDING, json.dumps({"idempotency_key": str(uuid.uuid4()), "body": body}))
with open(PENDING) as file:
pending = json.load(file)
# A retry with the same Idempotency-Key, body and signing key returns the same new key.
for attempt in range(1, 5):
try:
rotation = olympex_request(
"POST", "/accounts/me/keys/rotate", pending["body"], current, headers={"Idempotency-Key": pending["idempotency_key"]}
)
break
except (OlympexApiError, requests.RequestException) as error:
status = getattr(error, "status", None) # None: no response
if (status is not None and status < 500) or attempt == 4: # a 429 needs up to an hour
raise # PENDING stays: run again within 15 minutes to retry the same rotation
time.sleep(2**attempt)
# Store the new key before anything else, then confirm that it signs.
write_private(ENV_FILE, f"OLYMPEX_API_KEY_ID={rotation['apiKeyId']}\nOLYMPEX_SECRET_KEY={rotation['secretKey']}\n")
os.remove(PENDING)
olympex_request("GET", "/accounts/me/keys", credentials={**current, "api_key_id": rotation["apiKeyId"], "secret_key": rotation["secretKey"]})
print(f"New key {rotation['apiKeyId']} works and is in {ENV_FILE}. {rotation['previousApiKeyId']} signs until {rotation['previousKeyExpiresAt']}.")
{
"success": true,
"data": {
"apiKeyId": "00000000-0000-4000-8000-000000000001",
"secretKey": "aol_DocsTestVector_notARealSecret_000000000",
"previousApiKeyId": "00000000-0000-4000-8000-000000000000",
"previousKeyExpiresAt": "2026-10-31T13:06:45.989Z",
"secretRecoverableUntil": "2026-10-30T13:21:45.989Z"
},
"meta": {
"requestId": "GDxwAjXioAMEPWA=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Idempotency-Key header is required",
"details": []
},
"meta": {
"requestId": "GDxv6g_loAMEZ7w=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "CONFLICT",
"message": "Idempotency key was reused with a different payload",
"details": []
},
"meta": {
"requestId": "GDxwCjFXIAMEZQw=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"success": false,
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many key administration requests",
"details": []
},
"meta": {
"requestId": "GQ1D7ixyIAMEPHA=",
"version": "v1",
"accountType": "integrator",
"apiKeyId": "00000000-0000-4000-8000-000000000000"
}
}
{
"message": "Forbidden"
}
Authorizations
Your API key ID (UUID). See Sign requests.
Lowercase hex HMAC-SHA256 (signature v2), keyed with your secret key string (UTF-8, not decoded), of seven lines joined with \n, with no trailing newline: OLPX-HMAC-SHA256-V2, timestamp, nonce, the uppercase method, path, canonicalQuery and bodyHash. path is the request path including /api/v1, without the query string, for example /api/v1/limit-order/<id>. canonicalQuery is the query parameters decoded (+ is a space), sorted by key and then by value, re-encoded per RFC 3986 and joined with &, or the empty string when there is no query. Headers signed for one request are rejected on any other. See Sign requests.
Headers
Identifies one rotation, not one attempt. Generate a new UUID for each rotation, store it with the body before you send the request, and send the same value on every retry of that rotation. Up to 200 characters, not empty. It isn't part of the signature.
200Body
Was this page helpful?
