### GET / Source: https://docs.derive.xyz/docs/getting-started This is a basic GET request example to the root endpoint. ```APIDOC ## GET / ### Description This endpoint is a placeholder and demonstrates a basic GET request. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "curl --request GET --url https://example.com/" } ``` ### Response #### Success Response (200) - **message** (string) - A success message. #### Response Example ```json { "message": "Hello from the API!" } ``` ``` -------------------------------- ### Make a GET Request using cURL Source: https://docs.derive.xyz/docs/getting-started This snippet demonstrates how to make a GET request to a specified URL using the cURL command-line tool. It's a common way to interact with REST APIs and test endpoints. Ensure you have cURL installed on your system. ```shell curl --request GET \ --url https://example.com/ ``` -------------------------------- ### GET / Source: https://docs.derive.xyz/reference/getting-started This endpoint is the root of the API, likely used for health checks or basic information. ```APIDOC ## GET / ### Description This is the root endpoint of the API. It is typically used for basic health checks or to retrieve general information about the API. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl --request GET \ --url https://example.com/ ``` ### Response #### Success Response (200) This response will vary depending on the API's implementation. It might return a simple status message or basic API information. #### Response Example ```json { "message": "API is running successfully" } ``` ``` -------------------------------- ### Example JSON Response Structure Source: https://docs.derive.xyz/reference/public-create_subaccount_debug This is an example of the JSON structure expected as a response to the provided example commands. It illustrates the format and fields of the data that will be returned. ```json { "response_example_json" } ``` -------------------------------- ### Example Request and Response across Shell, JavaScript, and Python Source: https://docs.derive.xyz/reference/private-withdraw This snippet demonstrates how to make a request to a service using shell, JavaScript, and Python, and illustrates the expected JSON response format. It serves as a practical guide for users interacting with the API. ```shell {request_example_shell} ``` ```javascript {request_example_javascript} ``` ```python {request_example_python} ``` ```json {response_example_json} ``` -------------------------------- ### Request Example - JavaScript Source: https://docs.derive.xyz/reference/margin-watch This JavaScript snippet demonstrates an example request, likely for subscribing to data or making a query. It includes parameters such as action, symbol, and subscriptions. ```javascript { "action": "subscribe", "symbol": "sample.json", "subscriptions": [ { "name": "Derivativeticker", "id": "12345" } ] } ``` -------------------------------- ### Response Example (JSON) Source: https://docs.derive.xyz/reference/private-cancel-all This is an example of the JSON structure returned by the Derive XYZ project. It outlines the expected format for successful responses. ```json {response_example_json} ``` -------------------------------- ### API Request Examples (Shell, JavaScript, Python) Source: https://docs.derive.xyz/reference/private-order Demonstrates how to make API requests using shell, JavaScript, and Python. These examples show the structure of a typical request and the expected JSON response format. ```shell #!/bin/bash curl -X POST \ http://localhost:8080/api/v1/data \ -H 'Content-Type: application/json' \ -d '{ "key1": "value1", "key2": "value2" }' ``` ```javascript const fetchData = async () => { try { const response = await fetch('http://localhost:8080/api/v1/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key1: 'value1', key2: 'value2' }) }); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); ``` ```python import requests import json url = "http://localhost:8080/api/v1/data" headers = {"Content-Type": "application/json"} data = { "key1": "value1", "key2": "value2" } response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 200: print(response.json()) else: print(f"Error: {response.status_code}") ``` -------------------------------- ### JavaScript WebSocket Request Example Source: https://docs.derive.xyz/reference/auctions-watch This JavaScript code snippet demonstrates how to make a request for subscription data via websockets. It shows the structure of a typical request object. Ensure you have a WebSocket client library installed and configured. ```javascript { "method": "SUBSCRIBE", "params": [ "symbol:BTC-USD" ], "id": 1 } ``` -------------------------------- ### Example JSON Response Structure Source: https://docs.derive.xyz/reference/private-get_subaccounts Illustrates the expected JSON structure for a successful API response, as indicated by the comment. ```json { response_example_json } ``` -------------------------------- ### Complete RFQ Workflow Example Source: https://docs.derive.xyz/reference/rfq-quoting-and-execution Demonstrates a complete RFQ workflow: sending an RFQ, polling for responses, sending quotes (buy and sell), polling for quote results, and executing one side of the quote. This serves as an end-to-end example of platform interaction. ```typescript async function completeRfq() { await sendRfq(createRfqObject()) const rfq_response = await pollRfq(); console.log(rfq_response); const buy_response = await sendQuote(rfq_response, 'buy'); console.log(buy_response); const sell_response = await sendQuote(rfq_response, 'sell'); console.log(sell_response); const quotes = await pollQuotes(rfq_response.rfq_id); console.log(quotes); const buyQuote = quotes.find((quote) => quote.direction === 'buy') as QuoteResultPublicSchema; console.log(buyQuote); const sellQuote = quotes.find((quote) => quote.direction === 'sell') as QuoteResultPublicSchema; console.log(sellQuote); const executeAsSeller = await sendExecute(buyQuote); console.log(executeAsSeller); // NOTE optionally execute as buyer instead, but only one side can execute // const executeAsBuyer = await sendExecute(sellQuote); // console.log(executeAsBuyer); } ``` -------------------------------- ### JSON Response Example Source: https://docs.derive.xyz/reference/private-poll_rfqs Provides an example of a JSON response structure, as indicated by the comment. ```json { /*- A pretty-formated json saved to string -*/ response_example_json } ``` -------------------------------- ### Websocket Subscription Request Examples (JavaScript, Python) Source: https://docs.derive.xyz/reference/trades-instrument_type-currency-tx_status This snippet demonstrates how to initiate a subscription via websockets. It includes examples for both JavaScript and Python, illustrating the request structure required to connect and subscribe to data channels. Ensure the correct request format is used for your chosen language. ```javascript { "request_example_javascript": "true" } ``` ```python { "request_example_python": "true" } ``` -------------------------------- ### Response Example - JSON Source: https://docs.derive.xyz/reference/margin-watch This JSON snippet illustrates the structure of an example response message, likely received via a websocket subscription. It contains details about the tick, symbol, and various price-related data points. ```json { "tick": "12345", "symbol": "sample.json", "symbol_details": { "display_name": "Sample Symbol", "exchange": "Local Exchange", "market_close": "23:30:00", "market_open": "00:00:00", "sector": "Technology", "sub_category": "Software", "time_zone": "UTC" }, "subscription_id": "12345", "timestamp": 1587190937, "underlying": "Sample Underlying", "echo_req": { "action": "subscribe", "symbol": "sample.json", "subscriptions": [ { "name": "Derivativeticker", "id": "12345" } ] } } ``` -------------------------------- ### JavaScript Request Example Source: https://docs.derive.xyz/reference/trades-instrument_type-currency This JavaScript code snippet demonstrates an example request structure, likely for a WebSocket subscription. It specifies the event type and parameters for initiating a subscription. ```javascript { "event_type": "SUBSCRIBE", "data": { "channel": "notifications" } } ``` -------------------------------- ### JSON Response Structure Example Source: https://docs.derive.xyz/reference/private-order An example of the expected JSON structure returned by the API. This format is consistent across all request methods. ```json { "message": "Success", "data": { "id": "123e4567-e89b-12d3-a456-426614174000", "result": "processed data" } } ``` -------------------------------- ### Setup Constants and Wallet for RFQ Execution Source: https://docs.derive.xyz/reference/rfq-quoting-and-execution Initializes necessary constants, wallet, and provider for interacting with the RFQ protocol. It loads environment variables for private keys and defines addresses for protocol contracts and API endpoints. This setup is crucial for all subsequent RFQ operations. ```typescript import { ethers } from 'ethers'; import axios from 'axios'; import dotenv from 'dotenv'; dotenv.config(); const PRIVATE_KEY = process.env.OWNER_PRIVATE_KEY as string; const PROVIDER_URL = 'https://l2-prod-testnet-0eakp60405.t.conduit.xyz'; const HTTP_ADDRESS = 'https://api-demo.lyra.finance'; const ACTION_TYPEHASH = '0x4d7a9f27c403ff9c0f19bce61d76d82f9aa29f8d6d4b0c5474607d9770d1af17'; const DOMAIN_SEPARATOR = '0x9bcf4dc06df5d8bf23af818d5716491b995020f377d3b7b64c29ed14e3dd1105'; const OPTION_ADDRESS = '0xBcB494059969DAaB460E0B5d4f5c2366aab79aa1'; const RFQ_ADDRESS = '0x4E4DD8Be1e461913D9A5DBC4B830e67a8694ebCa' const PROVIDER = new ethers.JsonRpcProvider(PROVIDER_URL); const wallet = new ethers.Wallet(PRIVATE_KEY, PROVIDER); const encoder = ethers.AbiCoder.defaultAbiCoder(); const subaccount_id_rfq = 23525 const subaccount_id_maker = 8 const LEG_1_NAME = 'ETH-20240329-2400-C' const LEG_2_NAME = 'ETH-20240329-2600-C' // can retreive with public/get_instrument const LEGS_TO_SUB_ID: any = { 'ETH-20240329-2400-C': '39614082287924319838483674368', 'ETH-20240329-2600-C': '39614082373823665758483674368' } ``` -------------------------------- ### Example API Request and Response Source: https://docs.derive.xyz/reference/private-change_subaccount_label Demonstrates an example API request in shell, JavaScript, and Python, along with the expected JSON response structure. This helps users understand how to interact with the API and what data format to expect. ```shell {request_example_shell} ``` ```javascript {request_example_javascript} ``` ```python {request_example_python} ``` ```json { response_example_json } ``` -------------------------------- ### Build Register Session Key Tx - Python Example Source: https://docs.derive.xyz/reference/ws-public Example demonstrating how to use the build_register_session_key_tx API with Python. This code illustrates making the API call and processing the returned transaction parameters, often used in backend services. ```python import requests def build_register_session_key_tx(params): url = "https://rpc.example.com" payload = { "method": "public/build_register_session_key_tx", "params": [params], "id": 1 } response = requests.post(url, json=payload) return response.json() # Usage: tx_params = build_register_session_key_tx({ "expiry_sec": 1800, "gas": 100000, "nonce": 1, "public_session_key": "0x...", "wallet": "0x..." }) print(tx_params) ``` -------------------------------- ### Build Register Session Key Tx - Shell Example Source: https://docs.derive.xyz/reference/ws-public Example of how to call the build_register_session_key_tx API endpoint using a shell command. This demonstrates the request structure for obtaining transaction parameters. ```shell curl -X POST https://rpc.example.com \ --data '{"method": "public/build_register_session_key_tx", "params": [[{"expiry_sec": 1800, "gas": 100000, "nonce": 1, "public_session_key": "0x...", "wallet": "0x..."}]], "id": 1}' ``` -------------------------------- ### Example JSON Response Structure Source: https://docs.derive.xyz/reference/public-register_session_key Illustrates the expected JSON structure for an API response. This example is useful for understanding the data format returned by the API. ```json { "response_example_json" } ``` -------------------------------- ### JSON Response Example Source: https://docs.derive.xyz/reference/trades-instrument_type-currency This JSON code snippet represents an example notification message received through a channel. It includes event details, a timestamp, and the message content. ```json { "event_type": "NOTIFICATION", "data": { "timestamp": "2023-10-27T10:00:00Z", "message": "Your request has been processed successfully." } } ``` -------------------------------- ### Build Register Session Key Tx - JavaScript Example Source: https://docs.derive.xyz/reference/ws-public Example of calling the build_register_session_key_tx API using JavaScript. This snippet shows how to construct the request payload and handle the API response in a typical web application context. ```javascript async function buildRegisterSessionKeyTx(params) { const response = await fetch('https://rpc.example.com', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ method: 'public/build_register_session_key_tx', params: [params], id: 1 }) }); return await response.json(); } // Usage: const txParams = await buildRegisterSessionKeyTx({ expiry_sec: 1800, gas: 100000, nonce: 1, public_session_key: '0x...', wallet: '0x...' }); console.log(txParams); ``` -------------------------------- ### Request Examples: Shell, JavaScript, Python Source: https://docs.derive.xyz/reference/private-cancel_by_nonce Demonstrates how to make requests to the derive_xyz service using different programming languages and shell commands. These snippets show the basic structure for initiating a request and can be adapted for specific use cases. No external dependencies are explicitly mentioned, but it's assumed the environment has the necessary interpreters or shell capabilities. ```shell {request_example_shell} ``` ```javascript {request_example_javascript} ``` ```python {request_example_python} ``` -------------------------------- ### Get Account API Request (PHP) Source: https://docs.derive.xyz/reference/private A PHP example for calling the Get Account API. This code uses cURL to send a POST request to the Lyra Finance API, including the necessary JSON body and headers for authentication and content type. ```php $wallet_address]); $options = [ CURLOPT_URL => $url, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'accept: application/json', 'content-type: application/json' ] ]; $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpcode >= 200 && $httpcode < 300) { return json_decode($response, true); } else { // Handle error return null; } } // Example usage: // $account_details = get_account('0x...'); // print_r($account_details); ?> ``` -------------------------------- ### TypeScript: Derive Liquidation API Setup Source: https://docs.derive.xyz/reference/liquidation-api Sets up constants and initializes necessary libraries for interacting with the Derive Liquidation API. Includes API endpoints, WebSocket address, RPC provider URL, signing wallet, and encoding utilities. Requires environment variables for private keys. ```typescript import { ethers } from 'ethers'; import axios from 'axios'; import dotenv from 'dotenv'; import { WebSocket } from 'ws'; dotenv.config(); const PRIVATE_KEY = process.env.SESSION_PRIVATE_KEY as string; const WS_ADDRESS = 'wss://api-demo.lyra.finance/ws'; const PROVIDER_URL = 'https://rpc-prod-testnet-0eakp60405.t.conduit.xyz/'; const HTTP_ADDRESS = 'https://api-demo.lyra.finance'; const ACTION_TYPEHASH = '0x4d7a9f27c403ff9c0f19bce61d76d82f9aa29f8d6d4b0c5474607d9770d1af17'; const DOMAIN_SEPARATOR = '0x9bcf4dc06df5d8bf23af818d5716491b995020f377d3b7b64c29ed14e3dd1105'; const LIQUIDATE_ADDRESS = '0x3e2a570B915fEDAFf6176A261d105A4A68a0EA8D'; const PROVIDER = new ethers.JsonRpcProvider(PROVIDER_URL); const SIGNER = new ethers.Wallet(PRIVATE_KEY, PROVIDER); /// if using UI: "Funding Wallet Address" under https://testnet.lyra.finance/settings const ACCOUNT = '0x2225F2B33AA18a48EAbb675f918E950878C53BE6' const ENCODER = ethers.AbiCoder.defaultAbiCoder(); const subaccountIdLiquidator = 36919 const AUCTIONS_CHANNEL = "auctions.watch" ``` -------------------------------- ### GET /websites/derive_xyz/event-history Source: https://docs.derive.xyz/reference/post_private-get-erc20-transfer-history Retrieves the event history for a given subaccount, with options to filter by start and end timestamps. ```APIDOC ## GET /websites/derive_xyz/event-history ### Description Retrieves the event history for a given subaccount, with options to filter by start and end timestamps. ### Method GET ### Endpoint /websites/derive_xyz/event-history ### Parameters #### Query Parameters - **subaccount_id** (integer) - Required - The ID of the subaccount. - **start_timestamp** (integer) - Optional - The start timestamp of the event history (default 0). - **end_timestamp** (integer) - Optional - The end timestamp of the event history (default current time). ### Request Example ```json { "query": { "subaccount_id": 12345, "start_timestamp": 1678886400, "end_timestamp": 1678972800 } } ``` ### Response #### Success Response (200) - **events** (array) - A list of event objects. - **event_timestamp** (integer) - The timestamp of the event. - **event_type** (string) - The type of the event. - **details** (object) - Additional details about the event. #### Response Example ```json { "events": [ { "event_timestamp": 1678886400, "event_type": "transfer", "details": { "from": "0xabc", "to": "0xdef", "amount": "1000" } } ] } ``` ``` -------------------------------- ### GET /websites/derive_xyz/private/get_liquidation_history Source: https://docs.derive.xyz/reference/post_private-get-liquidation-history Retrieves the liquidation history for a given subaccount. You can specify a start and end timestamp to filter the results. ```APIDOC ## GET /websites/derive_xyz/private/get_liquidation_history ### Description Retrieves the liquidation history for a given subaccount. You can specify a start and end timestamp to filter the results. ### Method GET ### Endpoint `/websites/derive_xyz/private/get_liquidation_history` ### Parameters #### Query Parameters - **subaccount_id** (integer) - Required - Subaccount id - **start_timestamp** (integer) - Optional - Start timestamp of the event history (default 0) - **end_timestamp** (integer) - Optional - End timestamp of the event history (default current time) ### Request Example ```json { "subaccount_id": 12345, "start_timestamp": 1678886400, "end_timestamp": 1678972800 } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the liquidation event. - **result** (object) - Details of the liquidation result. #### Response Example ```json { "id": "liq_123abc", "result": { "some_field": "some_value" } } ``` ``` -------------------------------- ### Get Account API Request (Node.js) Source: https://docs.derive.xyz/reference/private Example of retrieving account details using the Lyra Finance API with Node.js. This code snippet requires the 'axios' library for making HTTP requests and demonstrates setting up the request with the necessary headers and payload. ```javascript const axios = require('axios'); const getAccount = async (walletAddress) => { try { const response = await axios.post('https://api.lyra.finance/private/get_account', { wallet: walletAddress }, { headers: { 'accept': 'application/json', 'content-type': 'application/json' } }); return response.data; } catch (error) { console.error('Error fetching account details:', error); throw error; } }; // Example usage: // getAccount('0x...').then(data => console.log(data)); ``` -------------------------------- ### Make Request Example (Shell) Source: https://docs.derive.xyz/reference/private-cancel-all This snippet shows how to make a request using the shell. It requires the '{request_example_shell}' placeholder to be replaced with actual request data. ```shell {request_example_shell} ``` -------------------------------- ### Get Funding Rate History Source: https://docs.derive.xyz/reference/public-get_funding_rate_history Retrieves the funding rate history for a given time range. The start timestamp is limited to a maximum of 30 days ago, and the end timestamp is capped at the current time. A zero start timestamp defaults to 30 days prior to the end timestamp. ```APIDOC ## GET /public/get_funding_rate_history ### Description Get funding rate history. Start timestamp is restricted to at most 30 days ago. End timestamp greater than current time will be truncated to current time. Zero start timestamp is allowed and will default to 30 days from the end timestamp. ### Method GET ### Endpoint /public/get_funding_rate_history ### Parameters #### Query Parameters - **start_ts** (integer) - Optional - The start timestamp for the funding rate history. Defaults to 30 days before the end timestamp if zero or not provided. - **end_ts** (integer) - Optional - The end timestamp for the funding rate history. Defaults to the current time if not provided. ### Request Example ```json { "start_ts": 1678886400, "end_ts": 1678972800 } ``` ### Response #### Success Response (200) - **data** (array) - An array of funding rate history objects. - **timestamp** (integer) - The timestamp of the funding rate entry. - **funding_rate** (string) - The funding rate at the specified timestamp. #### Response Example ```json { "data": [ { "timestamp": 1678886400, "funding_rate": "0.0001" }, { "timestamp": 1678972800, "funding_rate": "0.00015" } ] } ``` ``` -------------------------------- ### GET /private/linear/history/liquidator Source: https://docs.derive.xyz/reference/post_private-get-liquidator-history Retrieves the historical auction bid data for liquidations. You can filter the results by specifying start and end timestamps, as well as pagination parameters. ```APIDOC ## GET /private/linear/history/liquidator ### Description Retrieves the historical auction bid data for liquidations. This endpoint allows filtering by time range and pagination. ### Method GET ### Endpoint `/private/linear/history/liquidator` ### Query Parameters - **start_timestamp** (integer) - Optional - Start timestamp of the event history (default 0) - **end_timestamp** (integer) - Optional - End timestamp of the event history (default current time) - **page** (integer) - Optional - Page number of results to return (default 1, returns last if above `num_pages`) - **page_size** (integer) - Optional - Number of results per page (default 100, max 1000) - **subaccount_id** (integer) - Optional - Subaccount ID to filter results by. ### Response #### Success Response (200) - **id** (string) - Unique identifier for the request. - **result** (object) - Contains the liquidation history data. - **bids** (array) - List of auction bid events. - **amounts_liquidated** (string) - The amount of collateral liquidated. - **cash_received** (string) - The cash received from the liquidation. - **discount_pnl** (string) - The profit or loss from the discount. - **percent_liquidated** (string) - The percentage of the position liquidated. - **positions_realized_pnl** (string) - The realized profit or loss from positions, including fees. - **positions_realized_pnl_excl_fees** (string) - The realized profit or loss from positions, excluding fees. - **realized_pnl** (string) - The realized profit or loss of the auction bid, assuming positions are closed at mark price, including fees. - **realized_pnl_excl_fees** (string) - The realized profit or loss of the auction bid, excluding fees, assuming positions are closed at mark price. - **timestamp** (integer) - Timestamp of the bid (in ms since UNIX epoch). - **tx_hash** (string) - Hash of the bid transaction. - **pagination** (object) - Pagination information. - **count** (integer) - Total number of items, across all pages. - **num_pages** (integer) - Number of pages. #### Response Example ```json { "id": "some-uuid", "result": { "bids": [ { "amounts_liquidated": "100.50", "cash_received": "95.20", "discount_pnl": "5.30", "percent_liquidated": "0.10", "positions_realized_pnl": "-2.10", "positions_realized_pnl_excl_fees": "-1.90", "realized_pnl": "-2.50", "realized_pnl_excl_fees": "-2.20", "timestamp": 1678886400000, "tx_hash": "0xabc123..." } ], "pagination": { "count": 50, "num_pages": 1 } } } ``` ``` -------------------------------- ### GET /websites/derive_xyz/funding_history Source: https://docs.derive.xyz/reference/post_private-get-funding-history Fetches the funding history for a given subaccount. You can filter the results by specifying start and end timestamps, an instrument name, and pagination parameters. ```APIDOC ## GET /websites/derive_xyz/funding_history ### Description Retrieves the funding history for a specified subaccount. This endpoint supports filtering by time range, instrument name, and pagination. ### Method GET ### Endpoint `/websites/derive_xyz/funding_history` ### Parameters #### Query Parameters - **subaccount_id** (integer) - Required - The ID of the subaccount for which to retrieve funding history. - **start_timestamp** (integer) - Optional - The start timestamp (in Unix milliseconds) of the event history. Defaults to 0. - **end_timestamp** (integer) - Optional - The end timestamp (in Unix milliseconds) of the event history. Defaults to the current time. - **instrument_name** (string) - Optional - The name of the instrument. If not provided, history for all perpetuals is returned. - **page** (integer) - Optional - The page number of results to return. Defaults to 1. If the page number exceeds the total number of pages, the last page is returned. - **page_size** (integer) - Optional - The number of results per page. Defaults to 100, with a maximum of 1000. ### Request Example ``` GET /websites/derive_xyz/funding_history?subaccount_id=12345&instrument_name=BTC-PERPETUAL&start_timestamp=1678886400000&end_timestamp=1678972800000&page=1&page_size=50 ``` ### Response #### Success Response (200) - **funding_rate** (number) - The funding rate for the instrument. - **timestamp** (integer) - The timestamp of the funding event. - **instrument_name** (string) - The name of the instrument. - **total_amount** (number) - The total amount associated with the funding event. - **pnl** (number) - The profit and loss for the funding event. - **estimated_rate** (number) - The estimated funding rate. - **realized_pnl** (number) - The realized profit and loss for the funding event. #### Response Example ```json { "funding_rate": 0.0005, "timestamp": 1678900000000, "instrument_name": "BTC-PERPETUAL", "total_amount": 100000, "pnl": 50, "estimated_rate": 0.00048, "realized_pnl": 45 } ``` ``` -------------------------------- ### Make Request Example (JavaScript) Source: https://docs.derive.xyz/reference/private-cancel-all This snippet demonstrates how to construct and send a request using JavaScript. Ensure '{request_example_javascript}' is replaced with the specific request payload. ```javascript {request_example_javascript} ``` -------------------------------- ### Get Account API Request (cURL) Source: https://docs.derive.xyz/reference/private This snippet demonstrates how to make a POST request to the Get Account API endpoint using cURL. It includes setting the URL, request method, and necessary headers for JSON content. ```shell curl --request POST \ --url https://api.lyra.finance/private/get_account \ --header 'accept: application/json' \ --header 'content-type: application/json' ``` -------------------------------- ### Get Account API Request (Python) Source: https://docs.derive.xyz/reference/private Python code to interact with the Lyra Finance Get Account API. It utilizes the 'requests' library to perform a POST request, sending the wallet address in the JSON body and specifying the required headers. ```python import requests def get_account(wallet_address): url = 'https://api.lyra.finance/private/get_account' headers = { 'accept': 'application/json', 'content-type': 'application/json' } payload = { 'wallet': wallet_address } try: response = requests.post(url, headers=headers, json=payload) response.raise_for_status() # Raise an exception for bad status codes return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching account details: {e}") return None # Example usage: # account_details = get_account('0x...') # if account_details: # print(account_details) ``` -------------------------------- ### Make Request Example (Python) Source: https://docs.derive.xyz/reference/private-cancel-all This Python code illustrates how to formulate a request. The '{request_example_python}' variable should contain the request body. ```python {request_example_python} ``` -------------------------------- ### JavaScript WebSocket Subscription Request Example Source: https://docs.derive.xyz/reference/spot_feed-currency This JavaScript code demonstrates how to make a subscription request via websockets for the Derive XYZ project. It assumes a pre-existing websocket connection. ```javascript { "request_example_javascript" } ``` -------------------------------- ### JavaScript WebSocket Request Example Source: https://docs.derive.xyz/reference/subaccount_id-trades-tx_status Demonstrates an example request payload for a WebSocket subscription in JavaScript. This is used to initiate real-time data streams. ```javascript { "type": "subscribe", "channel": "trades", "symbol": "XYZ" } ``` -------------------------------- ### Order Placement API Source: https://docs.derive.xyz/reference/post_private-get-all-portfolios This section details the parameters required for placing various types of orders on the Derive XYZ platform. It covers order details, pricing, signature, and time-in-force options. ```APIDOC ## POST /websites/derive_xyz/orders ### Description Allows users to place new orders on the Derive XYZ platform. This endpoint supports various order types and configurations. ### Method POST ### Endpoint /websites/derive_xyz/orders ### Parameters #### Request Body - **order_type** (string) - Required - Enum: ["limit", "market"] - Type of order. - **time_in_force** (string) - Required - Enum: ["gtc", "post_only", "fok", "ioc"] - Time in force policy. - **price** (string) - Optional - Format: decimal - The price at which to place the order (required for limit orders). - **trigger_price** (string) - Optional - Format: decimal - Required for trigger orders. Index or Market price to trigger order at. - **trigger_price_type** (string) - Optional - Type of trigger price. - **amount** (string) - Required - Format: decimal - The amount of the asset to trade. - **expiry_duration** (integer) - Optional - Order expiry duration in seconds. - **signature** (string) - Required - Ethereum signature of the order. - **nonce** (string) - Required - Unique nonce defined as (e.g. 1695836058725001). - **signer** (string) - Required - Owner wallet address or registered session key that signed order. - **signature_expiry_sec** (integer) - Required - Signature expiry timestamp. - **subaccount_id** (integer) - Optional - Subaccount ID. - **order_fee** (string) - Optional - Format: decimal - Total order fee paid so far. - **order_id** (string) - Optional - Order ID. - **quote_id** (string) - Optional - Format: uuid - Quote ID if the trade was executed via RFQ. - **replaced_order_id** (string) - Optional - Format: uuid - If replaced, ID of the order that was replaced. ### Request Example ```json { "order_type": "limit", "time_in_force": "gtc", "price": "100.50", "amount": "10.75", "signature": "0xabc...", "nonce": "1695836058725001", "signer": "0x123...", "signature_expiry_sec": 1700000000, "subaccount_id": 1 } ``` ### Response #### Success Response (200) - **order_id** (string) - The ID of the newly placed order. - **order_status** (string) - The status of the order (e.g., "open"). #### Response Example ```json { "order_id": "ord_12345abc", "order_status": "open" } ``` ``` -------------------------------- ### GET /websites/derive_xyz - Get Auction Bid Data Source: https://docs.derive.xyz/reference/private-get_liquidation_history Retrieves detailed information about auction bids, including liquidation amounts, realized PnL, and transaction hashes. ```APIDOC ## GET /websites/derive_xyz ### Description Retrieves detailed information about auction bids, including liquidation amounts, realized PnL, and transaction hashes. ### Method GET ### Endpoint /websites/derive_xyz ### Parameters #### Query Parameters - **project** (string) - Required - The project identifier, e.g., "derive_xyz". ### Response #### Success Response (200) - **result** (array) - Array of auction bid results. - **result[].bids** (array) - Array of bids within the auction. - **result[].bids[].realized_pnl_excl_fees** (string) - Realized PnL of the auction bid, excluding fees from total cost basis, assuming positions are closed at mark price at the time of the liquidation. - **result[].bids[].timestamp** (integer) - Timestamp of the bid (in ms since UNIX epoch). - **result[].bids[].tx_hash** (string) - Hash of the bid transaction. - **result[].bids[].amounts_liquidated** (object) - Amounts of each asset that were closed. - **result[].bids[].positions_realized_pnl** (object) - Realized PnL of each position that was closed. - **result[].bids[].positions_realized_pnl_excl_fees** (object) - Realized PnL of each position that was closed, excluding fees from total cost basis. #### Response Example ```json { "result": [ { "bids": [ { "realized_pnl_excl_fees": "100.50", "timestamp": 1678886400000, "tx_hash": "0xabc123...", "amounts_liquidated": { "ETH": "5.2", "BTC": "0.1" }, "positions_realized_pnl": { "ETH-PERP": "120.00", "BTC-PERP": "80.00" }, "positions_realized_pnl_excl_fees": { "ETH-PERP": "130.00", "BTC-PERP": "90.00" } } ] } ] } ``` ``` -------------------------------- ### Public Get All Instruments Source: https://docs.derive.xyz/reference/post_public-get-all-instruments Retrieves a list of all available instruments, optionally filtered by currency and expiration status. This endpoint is useful for getting an overview of tradable assets. ```APIDOC ## GET /api/v1/instruments ### Description Retrieves a list of all available instruments, optionally filtered by currency and expiration status. This endpoint is useful for getting an overview of tradable assets. ### Method GET ### Endpoint /api/v1/instruments ### Parameters #### Query Parameters - **currency** (string) - Optional - Underlying currency of asset (`ETH`, `BTC`, etc) - **expired** (boolean) - Optional - If `True`: include expired instruments. - **instrument_type** (string) - Optional - Type of instrument to retrieve. Possible values are `PERPETUAL`, `OPTION`, `FUTURE`. ### Request Example ```json { "currency": "BTC", "expired": false, "instrument_type": "PERPETUAL" } ``` ### Response #### Success Response (200) - **instruments** (array) - An array of instrument objects, each containing detailed information about a specific instrument. - **pagination** (object) - An object containing pagination details, including the total count of items and the number of pages. #### Response Example ```json { "instruments": [ { "amount_step": "0.0001", "base_asset_address": null, "base_asset_sub_id": null, "base_currency": "BTC", "base_fee": "0.0005", "erc20_details": null, "fifo_min_allocation": "0.000000000000000000", "instrument_name": "BTC-PERPETUAL", "instrument_type": "PERPETUAL", "is_active": true, "maker_fee_rate": "0.0002", "maximum_amount": "1000000", "minimum_amount": "0.000001", "option_details": null, "perp_details": { "contract_size": "10", "funding_rate_8h": "0.000000000000000000", "initial_margin_rate": "0.025", "interest_rate": "0.000000000000000000", "maintenance_margin_rate": "0.0125", "max_funding_rate": "0.0005", "max_leverage": "100", "min_funding_rate": "-0.0005", "settlement_period": "8H" }, "pro_rata_amount_step": "0.000000000000000000", "pro_rata_fraction": "0", "quote_currency": "USD", "scheduled_activation": null, "scheduled_deactivation": null, "taker_fee_rate": "0.0005", "tick_size": "0.01" } ], "pagination": { "count": 100, "num_pages": 10 } } ``` ``` -------------------------------- ### Get Maker Programs Source: https://docs.derive.xyz/reference/post_public-get-maker-programs Retrieves all maker programs, including historical ones. This endpoint allows you to get information about available maker programs on Lyra Finance. ```APIDOC ## POST /public/get_maker_programs ### Description Get all maker programs, including past / historical ones. ### Method POST ### Endpoint https://api.lyra.finance/public/get_maker_programs ### Parameters #### Query Parameters None #### Request Body This endpoint does not expect a request body. ### Request Example ```json { "example": "No request body needed for this endpoint." } ``` ### Response #### Success Response (200) - **id** (one of string, integer) - Identifier for the response. - **result** (array) - A list of maker programs. - **asset_types** (array) - List of asset types covered by the program. - **currencies** (array) - List of currencies covered by the program. - **end_timestamp** (integer) - End timestamp of the epoch. - **min_notional** (string) - Minimum dollar notional to quote for eligibility. - **name** (string) - Name of the program. - **rewards** (object) - Rewards for the program as a token -> total reward amount mapping. - **start_timestamp** (integer) - Start timestamp of the epoch. #### Response Example ```json { "id": 1, "result": [ { "asset_types": ["ETH"], "currencies": ["USD"], "end_timestamp": 1678886400, "min_notional": "10000.0", "name": "Example Program", "rewards": { "LYRA": "5000.0" }, "start_timestamp": 1678281600 } ] } ``` ``` -------------------------------- ### Order Placement API Source: https://docs.derive.xyz/reference/post_private-replace This section details the parameters required for placing orders on the Derive XYZ platform. It covers various order types, time-in-force options, and signature details. ```APIDOC ## POST /websites/derive_xyz/orders ### Description Allows users to place various types of orders on the Derive XYZ platform, including limit, market, and trigger orders. ### Method POST ### Endpoint /websites/derive_xyz/orders ### Parameters #### Request Body - **signer** (string) - Required - Owner wallet address or registered session key that signed order - **signature** (string) - Required - Ethereum signature of the order - **order_type** (string) - Required - Enum: "limit", "market" - Order type - **time_in_force** (string) - Required - Enum: "gtc", "post_only", "fok", "ioc" - Time in force - **order_id** (string) - Required - Order ID - **subaccount_id** (integer) - Required - Subaccount ID - **signature_expiry_sec** (integer) - Required - Signature expiry timestamp - **trigger_price** (string) - Optional - (Required for trigger orders) Index or Market price to trigger order at - **trigger_price_type** (string) - Optional - (Required for trigger orders) Enum: "mark", "index" - Trigger with Index or Mark Price - **trigger_reject_message** (string) - Optional - (Required for trigger orders) Error message if error occured during trigger ### Request Example ```json { "signer": "0x123abc...", "signature": "0x456def...", "order_type": "limit", "time_in_force": "gtc", "order_id": "ORD12345", "subaccount_id": 1, "signature_expiry_sec": 1678886400 } ``` ### Response #### Success Response (200) - **order_status** (string) - The current status of the order (e.g., "open", "filled", "cancelled") - **order_id** (string) - The unique identifier for the placed order #### Response Example ```json { "order_status": "open", "order_id": "ORD12345" } ``` ```