Connect HashKey to ChatGPT: Analyze Market Data and Execute Trades
Learn how to connect HashKey to ChatGPT using a managed MCP server. This step-by-step guide covers handling HashKey API quirks, configuring tools, and executing trades.
If your team uses Claude, check out our guide on connecting HashKey to Claude or explore our broader architectural overview on connecting HashKey to AI Agents.
Giving a Large Language Model (LLM) read and write access to a compliant digital asset exchange like HashKey is a high-stakes engineering challenge. You want to connect HashKey to ChatGPT so your AI agents can analyze order book depth, retrieve candlestick data, adjust futures leverage, and execute spot trades based on real-time market conditions.
To bridge the gap between ChatGPT's tool-calling capabilities and HashKey's REST API, you need a Model Context Protocol (MCP) server. You can either spend weeks building, hosting, and securing a custom MCP server, or you can use a managed infrastructure layer to dynamically generate a secure, authenticated MCP server URL.
This guide breaks down exactly how to use Truto to generate a managed HashKey MCP server, connect it natively to ChatGPT, and execute complex trading and market analysis workflows using natural language.
The Engineering Reality of the HashKey API
A custom MCP server is a self-hosted integration layer that translates an LLM's tool calls into HTTP requests. While the open MCP standard provides a predictable way for models to discover tools, implementing it against financial exchange APIs introduces severe complexity. If you build a custom MCP server for HashKey, you own the entire API lifecycle.
Here are the specific integration challenges that break standard CRUD assumptions when working with HashKey:
Precision, Lot Sizes, and String Encoding
Financial exchange APIs are unforgiving when it comes to numeric precision. HashKey requires exact lot sizes and tick sizes for order placement. If an LLM calculates a trade quantity as 1.00000000001 and your MCP server passes it as a raw float, HashKey will reject the payload due to precision constraints or floating-point rounding errors. Your integration layer must enforce strict string encoding for numeric values (quantity, price) according to HashKey's specific symbol trading rules.
Strict Whitelisting and Micro-Payment Verification
HashKey is highly regulated. You cannot simply instruct an LLM to withdraw funds to an arbitrary wallet address. Withdrawal addresses must be strictly whitelisted. HashKey's API handles this through a complex challenge-response mechanism involving cryptographic signature verification or micro-payment deposits. The list_all_hash_key_whitelist_verifies endpoint requires depositing a highly specific, randomized micro-amount to verify ownership. If your server doesn't clearly expose these multi-step verification states as distinct tools, ChatGPT will hallucinate withdrawal confirmations.
Dual Account Structures (Spot vs. Futures)
HashKey segments asset management into spot accounts and futures accounts, each with different margin modes (isolated vs. cross) and endpoints. An LLM might attempt to place a futures order using a spot account balance. Your MCP server must accurately represent the boundaries between the hash_key_account_* and hash_key_futures_* domains, ensuring the LLM understands when an internal transfer is required before placing a leveraged order.
Rate Limits and 429 Passthrough
HashKey enforces strict rate limits to maintain matching engine stability. Truto does not magically absorb or retry rate limit errors. When a client hits the rate limit and HashKey returns an HTTP 429 status code, Truto passes that 429 directly to the caller. However, Truto normalizes the upstream rate limit information into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). The caller - whether that is a custom AI agent or ChatGPT - is responsible for reading these headers and implementing its own exponential backoff.
The Managed MCP Approach
Instead of forcing your engineering team to build custom JSON-RPC routers and maintain hundreds of JSON schemas for HashKey's API, Truto dynamically derives MCP tools directly from HashKey's documentation and resource definitions.
Tools are only exposed if they have matching documentation records. This acts as a quality gate, ensuring ChatGPT only sees well-documented endpoints with explicitly defined parameters. When an LLM makes a tool call, Truto maps the flat argument object into the correct query parameters and body payloads required by HashKey.
Step 1: Generating the HashKey MCP Server
To connect HashKey to ChatGPT, you first need to generate a secure MCP server URL scoped to a specific HashKey account.
Method A: Via the Truto UI
For ad-hoc configurations and testing, you can generate an MCP server directly from the dashboard:
- Log into Truto and navigate to your connected HashKey Integrated Account.
- Click the MCP Servers tab.
- Click Create MCP Server.
- Select your desired configuration - name your server, choose allowed methods (e.g.,
readonly), and specify any resource tags. - Copy the generated MCP server URL (e.g.,
https://api.truto.one/mcp/a1b2c3d4...).
Method B: Via the API
For automated deployments or multi-tenant architectures, you can generate MCP servers programmatically. Submit a POST request to the /integrated-account/:id/mcp endpoint.
const response = await fetch(
'https://api.truto.one/integrated-account/<hashkey_account_id>/mcp',
{
method: 'POST',
headers: {
'Authorization': 'Bearer <YOUR_TRUTO_API_KEY>',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: "HashKey Trading Agent",
config: {
methods: ["read", "write"], // Allow both market data and execution
tags: ["trading", "market_data"]
},
expires_at: "2026-12-31T23:59:59Z"
})
}
)
const mcpServer = await response.json();
console.log(mcpServer.url);
// Output: https://api.truto.one/mcp/a1b2c3d4e5f6...This API call securely hashes the configuration, stores it in edge KV storage, and returns the unique URL you will feed into ChatGPT.
Step 2: Connecting the MCP Server to ChatGPT
Once you have the HashKey MCP URL, you must register it with your LLM client.
Method A: Via the ChatGPT UI
If you are using ChatGPT Plus, Enterprise, or Pro accounts with Developer Mode enabled:
- In ChatGPT, navigate to Settings -> Apps -> Advanced settings.
- Enable the Developer mode toggle.
- Under MCP servers / Custom connectors, click Add a new server.
- Name the connection (e.g., "HashKey Market Data").
- Paste the Truto MCP URL into the Server URL field.
- Click Save.
ChatGPT will immediately ping the server, execute the MCP initialize handshake, and list the available HashKey tools.
Method B: Via Manual Config File (Claude Desktop / Cursor)
If you are using environments that rely on local configuration files (like Claude Desktop or Cursor), you connect the server using a Server-Sent Events (SSE) proxy command.
Add the following to your mcp_config.json file:
{
"mcpServers": {
"hashkey_truto": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-sse",
"--url",
"https://api.truto.one/mcp/<YOUR_TOKEN_HERE>"
]
}
}
}Restart your client, and the agent will discover all authorized HashKey endpoints.
HashKey Hero Tools for AI Agents
Truto exposes the entirety of the HashKey REST API as tools. Here are the highest-leverage operations for building trading and analysis agents.
hash_key_market_data_get_klines
Retrieves candlestick (Kline) data for a specific trading pair. This is the foundational tool for any technical analysis agent. It returns open, high, low, close, and volume metrics.
Usage Note: Ensure the agent passes valid interval strings (e.g., 1m, 1h, 1d). HashKey limits responses to 1000 bars per request.
"Fetch the 4-hour K-lines for BTCUSDT from HashKey over the last 7 days. Calculate the moving average and tell me if we are in an uptrend."
hash_key_market_data_get_merged_depth
Gets the aggregated order book depth for a trading pair. It returns an array of current bids and asks with their respective quantities.
Usage Note: Use this over the raw depth endpoint when you want the LLM to gauge overall market liquidity and slippage without being overwhelmed by micro-ticks.
"Check the merged order book depth for ETHUSDT. What is the total quantity of bids within 1% of the current top-of-book price?"
hash_key_account_get_account_info
Retrieves the core spot account information, including balances for all held assets.
Usage Note: The response contains an array of balances. Instruct the LLM to filter out assets with a zero balance to save context window space during subsequent reasoning steps.
"Audit my HashKey spot account. List all assets that have an available balance greater than zero."
create_a_hash_key_spot_order
Executes a spot trade on HashKey Exchange. Requires the symbol, side (BUY/SELL), type (LIMIT/MARKET), and quantity.
Usage Note: If placing a LIMIT order, the price parameter becomes mandatory. Required funds are ringfenced immediately upon execution.
"I have 500 USDT available. Place a market buy order for SOLUSDT using the maximum available quantity."
hash_key_futures_set_leverage
Adjusts the leverage multiplier for a specific futures contract. Returns the updated position configuration.
Usage Note: Leverage dictates liquidation risk. This tool is heavily utilized by risk-management agents that monitor volatility and scale back leverage dynamically.
"Check our current leverage on the BTCUSDT-PERPETUAL contract. If it is higher than 5x, set the leverage down to 3x immediately."
hash_key_wallet_get_deposit_address
Retrieves the system-generated deposit address for a specific asset and blockchain network.
Usage Note: This tool requires both the coin (e.g., ETH) and chainType (e.g., Arbitrum, Optimism). It is essential for orchestrating inbound treasury transfers.
"I need to fund our account. Get the HashKey deposit address for USDC on the Solana network."
For the complete inventory of HashKey tools, including fiat withdrawals, RFQ (Request for Quote) management, and webhook subscriptions, view the HashKey integration page.
Workflows in Action
Here is how ChatGPT orchestrates these tools to execute real-world trading operations autonomously.
Use Case 1: Automated Market Analysis and Execution
A quant trader wants to execute a momentum strategy without writing manual API scripts. They instruct ChatGPT to evaluate recent price action and execute a trade if conditions are met.
"Analyze the 1-hour K-lines for BTCUSDT. If the closing price has risen over the last 3 consecutive periods, and the merged order book shows strong bid support, check my spot balance and execute a market buy for 0.05 BTC."
Execution Steps:
hash_key_market_data_get_klines: The agent fetches the 1-hour candles and confirms the 3-period uptrend.hash_key_market_data_get_merged_depth: The agent analyzes thebidsarray to confirm liquidity support.hash_key_account_get_account_info: The agent checks the USDT balance to ensure sufficient funds exist for 0.05 BTC.create_a_hash_key_spot_order: The agent submits the MARKET BUY payload.
graph TD
A["User Prompt<br>Trigger Momentum Trade"] --> B["hash_key_market_data_get_klines<br>Fetch 1H Candles"]
B --> C{Uptrend Confirmed?}
C -- Yes --> D["hash_key_market_data_get_merged_depth<br>Check Bids"]
C -- No --> E["Abort Workflow<br>Report to User"]
D --> F{Strong Liquidity?}
F -- Yes --> G["hash_key_account_get_account_info<br>Check USDT Balance"]
G --> H["create_a_hash_key_spot_order<br>Execute 0.05 BTC Buy"]Result: The agent replies with the executed orderId, average fill price, and remaining USDT balance.
Use Case 2: Futures Risk Mitigation
A treasury manager needs to ensure their institutional futures account isn't over-leveraged during a volatile weekend trading session.
"Audit our open futures positions. If the leverage on ETHUSDT-PERPETUAL is above 10x, reduce it to 5x to lower liquidation risk. Then, report our current futures account balance."
Execution Steps:
hash_key_futures_get_positions: The agent retrieves all active positions and filters forETHUSDT-PERPETUAL.hash_key_futures_set_leverage: Discovering the leverage is at 15x, the agent calls this tool withsymbol: "ETHUSDT-PERPETUAL"andleverage: 5.hash_key_futures_get_balance: The agent fetches the latest margin balance to confirm account health.
sequenceDiagram
participant ChatGPT as ChatGPT
participant Truto as Truto MCP Server
participant HashKey as HashKey API
ChatGPT->>Truto: Call hash_key_futures_get_positions
Truto->>HashKey: GET /api/v1/futures/positions
HashKey-->>Truto: Return Positions (ETHUSDT @ 15x)
Truto-->>ChatGPT: Return JSON
ChatGPT->>Truto: Call hash_key_futures_set_leverage (5x)
Truto->>HashKey: POST /api/v1/futures/leverage (5)
HashKey-->>Truto: Success Response
Truto-->>ChatGPT: Leverage Updated
ChatGPT->>Truto: Call hash_key_futures_get_balance
Truto->>HashKey: GET /api/v1/futures/balance
HashKey-->>Truto: Return Balances
Truto-->>ChatGPT: Final SummaryResult: The LLM successfully de-risks the portfolio and provides a clean status report of the futures treasury.
Security and Access Control
Exposing financial execution APIs to an LLM requires strict boundary enforcement. Truto provides several mechanisms to lock down your HashKey MCP server:
- Method Filtering: Restrict a server to safe operations by setting
config.methods: ["read"]. The LLM can retrieve balances and market data but cannot execute trades or withdrawals. - Tag Filtering: Scope the server to specific operational domains. Use
config.tags: ["market_data"]to expose only ticker, depth, and kline tools, entirely hiding wallet and execution endpoints. - Time-to-Live (TTL): Set an
expires_attimestamp. Once the time passes, edge storage automatically evicts the token and a distributed alarm cleans up the database record, instantly revoking LLM access. - API Token Auth Layer: Enable
require_api_token_auth. When set, possession of the MCP URL is not enough; the client (or developer) must also pass a valid Truto API token in the headers, adding a secondary authentication layer against unauthorized discovery.
Scale Your AI Trading Operations
Connecting HashKey to ChatGPT using a managed MCP server removes the heavy lifting of API maintenance. Instead of writing custom JSON-RPC handlers, mapping complex order schemas, and fighting with signature challenges, you generate a secure URL and start prompting.
Truto handles the API lifecycle, meaning when HashKey updates an endpoint or modifies a required field, the generated MCP tools update dynamically based on the latest documentation records.
FAQ
- How does Truto handle HashKey API rate limits?
- Truto passes HashKey HTTP 429 rate limit errors directly to the caller and normalizes upstream rate limit info into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). The calling AI agent must handle retries.
- Can I restrict ChatGPT from executing trades on HashKey?
- Yes. By configuring the MCP server with method filtering (e.g., config.methods: ["read"]), ChatGPT can view balances and market data but cannot place orders or initiate withdrawals.
- Does Truto support HashKey wallet whitelisting processes?
- Yes. Truto exposes HashKey's native whitelist verification endpoints, including micro-payment deposit generation and cryptographic signature flows, as distinct LLM tools.
- How do I connect the MCP server to ChatGPT?
- If you have Developer Mode enabled in ChatGPT, navigate to Settings > Apps > Advanced settings, add a new custom connector, and paste your Truto-generated MCP URL.