How Does Crypto Trading API Authentication Work with Mithril?
Authenticating with the Mithril crypto trading API requires two things: a Mithril API key in the x-api-key header on every request, and exchange credentials registered once through the credential manager. Public data — prices, order books, funding rates — needs only the API key. Order placement, position management, and balance queries additionally require registered exchange credentials. The full reference is at api.mithril.money/docs.
Authentication failures are the most common cause of failed API integrations across all software categories. According to the 2025 State of the API Report by Postman (n=40,000 developers), 53% of developers reported spending more than 4 hours debugging authentication issues when integrating a new API. The Mithril two-layer model — one key for API access, separate credentials per exchange — is designed to minimize this surface area while maintaining security boundaries between your Mithril account and your exchange wallets.
Layer 1: The Mithril API Key
Every request to https://api.mithril.money/api/v1 must include a Mithril API key in the request header. This key identifies your Mithril account and controls rate limits, usage tracking, and plan-based access. It does not give access to your exchange funds — it only gates access to the Mithril API itself.
Obtaining Your API Key
- Create an account at bot.mithril.money.
- Navigate to Settings → API Keys.
- Click Generate New Key. The key is shown once — copy it immediately to a secure location.
- Optionally set an IP allowlist or key label for organizational clarity.
Using the API Key in Requests
The key is passed as a custom HTTP header on every request:
POST https://api.mithril.money/api/v1
Content-Type: application/json
x-api-key: mk_live_your_key_here
{
"action": "getPrice",
"exchange": "hyperliquid",
"params": { "symbol": "BTC-USD-PERP" }
}
In Python with the requests library:
import requests
MITHRIL_KEY = "mk_live_your_key_here" # store in env, not source
API_URL = "https://api.mithril.money/api/v1"
headers = {
"Content-Type": "application/json",
"x-api-key": MITHRIL_KEY
}
response = requests.post(API_URL, headers=headers, json={
"action": "getPrice",
"exchange": "hyperliquid",
"params": {"symbol": "BTC-USD-PERP"}
})
print(response.json())
In JavaScript / Node.js:
const MITHRIL_KEY = process.env.MITHRIL_API_KEY; // never hardcode
const API_URL = "https://api.mithril.money/api/v1";
async function getPrice(exchange, symbol) {
const res = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": MITHRIL_KEY
},
body: JSON.stringify({
action: "getPrice",
exchange,
params: { symbol }
})
});
return res.json();
}
getPrice("hyperliquid", "BTC-USD-PERP").then(console.log);
Layer 2: Exchange Credentials
Trading actions — placing orders, checking balances, managing positions — require that Mithril can sign transactions on your behalf for the target exchange. Each exchange has a different signing mechanism: Hyperliquid uses EIP-712 Ethereum signatures, Paradex uses StarkNet account abstraction, Pacifica uses Solana keypairs, and so on. Mithril abstracts all of this behind a single credential registration flow.
How Exchange Credential Registration Works
You register credentials once per exchange. After registration, all trading calls for that exchange automatically use the stored credentials. The registration call itself requires your Mithril API key:
POST https://api.mithril.money/api/v1
x-api-key: mk_live_your_key_here
{
"action": "registerCredentials",
"exchange": "hyperliquid",
"params": {
"privateKey": "0xYOUR_EVM_PRIVATE_KEY",
"label": "hl-main-wallet"
}
}
A successful response returns a credential ID:
{
"success": true,
"data": {
"credentialId": "cred_hl_a3f9d2",
"exchange": "hyperliquid",
"label": "hl-main-wallet",
"address": "0xAbCd...1234",
"createdAt": "2026-04-01T10:23:45Z"
}
}
The raw private key is encrypted immediately on receipt and is never returned in any subsequent API response. Mithril uses AES-256-GCM encryption at rest with per-credential key derivation. The credential ID is what you reference in any optional credential-scoping logic.
Credential Registration by Exchange
| Exchange | Chain | Required Credential | Key Format |
|---|---|---|---|
| Hyperliquid | Hyperliquid L1 | EVM private key | 0x hex string |
| Paradex | StarkNet | StarkNet private key | Hex string |
| Pacifica | Solana | Solana keypair | Base58 string |
| Aftermath | Sui | Sui private key | Bech32 string |
| Carbon | Cosmos | Cosmos mnemonic or key | BIP-39 mnemonic |
| Hibachi | Multi-chain | EVM private key | 0x hex string |
| Polymarket | Polygon | EVM private key | 0x hex string |
| Kalshi | CFTC-regulated | Kalshi API key + secret | UUID + secret string |
Making Authenticated Trading Calls
Once credentials are registered, trading calls use the same request structure as public calls — no additional credential parameters are required in the request body. The API resolves the correct credential automatically based on your Mithril account and the specified exchange:
POST https://api.mithril.money/api/v1
x-api-key: mk_live_your_key_here
{
"action": "placeOrder",
"exchange": "hyperliquid",
"params": {
"symbol": "ETH-USD-PERP",
"side": "buy",
"type": "limit",
"size": 0.5,
"price": 3200,
"leverage": 5
}
}
Response:
{
"success": true,
"data": {
"orderId": "ord_hl_88f3c1",
"symbol": "ETH-USD-PERP",
"side": "buy",
"type": "limit",
"size": 0.5,
"price": 3200,
"status": "open",
"createdAt": "2026-04-02T08:14:22Z"
}
}
Security Best Practices
Poor API key management is responsible for the majority of crypto theft incidents involving automated trading systems. A 2025 Chainalysis report attributed $340 million in losses to compromised API keys and private keys exposed through insecure storage or transmission. The following practices are non-negotiable for any production trading system.
Never Hardcode Keys in Source Code
Both your Mithril API key and exchange private keys must be loaded from environment variables or a secrets manager — never written directly in code:
# .env file (add to .gitignore immediately)
MITHRIL_API_KEY=mk_live_your_key_here
HL_PRIVATE_KEY=0xyour_private_key
# Python
import os
MITHRIL_KEY = os.environ["MITHRIL_API_KEY"]
# Node.js
const MITHRIL_KEY = process.env.MITHRIL_API_KEY;
Use Dedicated Trading Wallets
Register only wallets created specifically for trading with the Mithril API. Never register a wallet that holds long-term holdings, NFTs, or funds you cannot afford to lose. The registered wallet should contain only the margin capital you intend to deploy — nothing more.
Rotate API Keys Regularly
Mithril API keys can be revoked and regenerated from the dashboard at any time. Rotate keys every 90 days as a baseline practice, or immediately upon any suspected exposure. Key rotation requires updating your environment variable only — no changes to the credential store are necessary.
Scope Keys by IP Where Possible
The Mithril key management dashboard supports IP allowlisting. If your trading bot runs on a fixed IP (a dedicated server or VPS), add that IP to the allowlist. Requests from any other IP will be rejected, even with a valid key. This significantly reduces the blast radius of a leaked key.
Monitor for Unexpected Activity
Use the API's audit log endpoint to verify that all recent actions match your bot's expected behavior:
{
"action": "getAuditLog",
"params": {
"limit": 50,
"since": "2026-04-01T00:00:00Z"
}
}
Run this check daily. Unexpected orders or position changes are an early indicator of credential compromise.
Error Handling for Authentication Failures
The Mithril API returns structured errors for all authentication failures. Handling these correctly prevents bots from entering undefined states when credentials expire or are revoked:
| Error Code | Meaning | Resolution |
|---|---|---|
AUTH_MISSING_KEY | x-api-key header absent | Add header to all requests |
AUTH_INVALID_KEY | Key does not exist or was revoked | Regenerate key in dashboard |
AUTH_RATE_LIMITED | Exceeded requests per minute | Implement exponential backoff |
CRED_NOT_FOUND | No credentials registered for exchange | Register credentials via registerCredentials |
CRED_SIGNING_FAILED | Transaction signing error | Re-register credentials; check key format |
CRED_INSUFFICIENT_FUNDS | Margin balance too low | Deposit funds to trading wallet |
def call_api(payload):
response = requests.post(API_URL, headers=headers, json=payload)
data = response.json()
if not data.get("success"):
error = data.get("error", {})
code = error.get("code", "UNKNOWN")
if code == "AUTH_RATE_LIMITED":
time.sleep(2 ** retry_count) # exponential backoff
return call_api(payload) # retry
elif code in ("AUTH_INVALID_KEY", "AUTH_MISSING_KEY"):
raise SystemExit(f"Authentication failed: {code}. Check MITHRIL_API_KEY.")
elif code == "CRED_NOT_FOUND":
raise ValueError(f"No credentials for exchange. Register via registerCredentials.")
else:
raise RuntimeError(f"API error: {code} — {error.get('message')}")
return data["data"]
Testing Authentication Before Going Live
Before deploying a live trading bot, verify each authentication layer independently:
- Test API key: Call
getPriceon any exchange. A valid response confirms the key works. - Test credential registration: Call
getBalanceon your target exchange. A response with your actual balance confirms credentials are registered and working. - Test order placement in paper mode: Use the
paperMode: trueflag in theparamsobject to simulate order placement without committing funds. Verify the response structure matches your parsing logic. - Run a minimal live test: Place a single minimum-size limit order well outside the market (e.g., limit buy at 10% below market). Verify it appears in
getOpenOrders, then cancel it withcancelOrder.
For the full API reference including all actions, parameters, and response schemas, see api.mithril.money/docs. For building a UI around API-authenticated trading workflows, see build.mithril.money. Additional authentication patterns and security configuration examples are published on the Mithril blog.
Frequently Asked Questions
Can I use the same Mithril API key across multiple bots?
Yes. A single Mithril API key can be used by multiple bots simultaneously. Rate limits apply per key, so high-volume deployments running many bots in parallel should use separate keys to distribute request load. Generate additional keys from the bot.mithril.money dashboard.
Is my private key ever transmitted after initial registration?
No. The private key is transmitted only once during the registerCredentials call, over HTTPS. After that, only the credential ID is used to reference it. The raw key is never returned in any API response and is never stored in plaintext.
What happens if I rotate my exchange wallet's private key?
You must re-register the new key via registerCredentials with the same label. The old credential will continue to exist until you explicitly delete it. Both credentials can coexist temporarily — useful for migrating balances between wallets without downtime.
Does Mithril support OAuth or JWT for authentication?
Currently, the Mithril API uses API key authentication via the x-api-key header only. OAuth and JWT flows are not supported at the API level. The credential management dashboard uses standard session-based authentication for the web UI.
How do I authenticate for the Mithril Builder SDK in a generated app?
Apps generated by Mithril Builder handle authentication automatically — the MithrilClient SDK uses your registered Mithril account credentials at build time. Deployed apps inherit the authentication context of the account that generated them. For custom integrations using the exported code, set the MITHRIL_API_KEY environment variable in your deployment environment.
