NAV
shell javascript rust

Introduction

Welcome to the Twilight Relayer API! You can utilize our API to access Relayer API endpoints, which provide information on various operations within our relayer.

Public API

Endpoint URL

API_ENDPOINT_PRODUCTION = https://relayer.twilight.rest

API_ENDPOINT_STAGING = https://app.twilight.rest

Request Structure

All public API requests must be sent to:

API_ENDPOINT/api

For example:

Request Format

Component Description
URL API_ENDPOINT/api
Method POST
Content-Type application/json
Body JSON-RPC 2.0 formatted request

Market Data

Market data endpoints provide OHLCV candles, real-time and historical prices, funding rates, and fee information. Use them for charting, backtesting, and monitoring market conditions. No authentication required.

Candle Data

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "candle_data",
  id: 123,
  params: {
    interval: "ONE_DAY",
    since: "2023-09-25T00:01:00.0Z",
    limit: 20,
    offset: 0,
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "btc_volume": "234549776",
      "close": "42988.8099999999976716935634613037109375",
      "end": "2024-01-31T00:00:59.907514Z",
      "high": "43867.3799999999973806552588939666748046875",
      "low": "42686",
      "open": "43493.2600000000020372681319713592529296875",
      "resolution": "1 day",
      "start": "2024-01-30T11:00:17.892660Z",
      "trades": 27,
      "usd_volume": "1172748.880000000048312358558177947998046875"
    },
    {
      "btc_volume": "173740820",
      "close": "42507.33999999999650754034519195556640625",
      "end": "2024-01-31T10:51:37.281376Z",
      "high": "43107.7699999999967985786497592926025390625",
      "low": "42462.639999999999417923390865325927734375",
      "open": "42990.6200000000026193447411060333251953125",
      "resolution": "1 day",
      "start": "2024-01-31T00:01:00.908144Z",
      "trades": 20,
      "usd_volume": "868704.100000000034924596548080444335937500"
    }
  ],
  "id": 123
}

Description: Retrieves OHLCV (Open, High, Low, Close, Volume) candle data for technical analysis and chart visualization of BTC-USD perpetual contracts.

Use Cases:

Candle data (Kline data: 1min, 5min, 15min, 30min, 1hr, 4hr, 8hr, 12hr, 24hr, daily change)

HTTP Method

POST

RPC Method

candle_data

Message Parameters
Params Data_Type Values
interval string ONE_MINUTE, FIVE_MINUTE, FIFTEEN_MINUTE, THIRTY_MINUTE, ONE_HOUR, FOUR_HOUR, EIGHT_HOUR, TWELVE_HOUR, ONE_DAY, ONE_DAY_CHANGE
since datetime Start time (ISO 8601)
limit integer Number of entries (max 5000)
offset integer Page offset
Response Fields
Field Data_Type Description
btc_volume string BTC trading volume for the period
close string Closing price for the period
end string End timestamp of the candle period (ISO 8601)
high string Highest price during the period
low string Lowest price during the period
open string Opening price for the period
resolution string Time interval resolution (e.g., "1 day", "1 hour")
start string Start timestamp of the candle period (ISO 8601)
trades integer Number of trades executed during the period
usd_volume string USD trading volume for the period

BTC USD Price

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "btc_usd_price",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 45551,
    "price": "42447.0400000000008731149137020111083984375",
    "timestamp": "2024-01-31T11:01:30.907388Z"
  },
  "id": 123
}

Description: Returns the current BTC-USD price from the perpetual contract, providing real-time price information for trading and valuation.

Use Cases:

BTC USD Price

HTTP Method

POST

RPC Method

btc_usd_price

Message Parameters
Params Data_Type Values
N/A null No parameters required
Response Fields
Field Data_Type Description
id integer Internal price record ID
price string Current BTC-USD price
timestamp string Price timestamp (ISO 8601 format)

Historical Price

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "historical_price",
  id: 123,
  params: {
    from: "2024-01-14T00:00:00Z",
    to: "2024-01-31T01:00:00Z",
    limit: 3,
    offset: 0,
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "id": 1,
      "price": "43493.2600000000020372681319713592529296875",
      "timestamp": "2024-01-30T11:00:17.892660Z"
    },
    {
      "id": 2,
      "price": "43493.2699999999967985786497592926025390625",
      "timestamp": "2024-01-30T11:00:18.894869Z"
    },
    {
      "id": 3,
      "price": "43493.2600000000020372681319713592529296875",
      "timestamp": "2024-01-30T11:00:19.895641Z"
    }
  ],
  "id": 123
}

Description: Retrieves historical BTC-USD price data for backtesting, analysis, and research purposes across specified time ranges.

Use Cases:

Historical BTC price

HTTP Method

POST

RPC Method

historical_price

Message Parameters

Params Data_Type Values
from datetime Start time (ISO 8601)
to datetime End time (ISO 8601)
limit integer Number of entries (max 5000)
offset integer Page offset

Response Fields

Field Data_Type Description
id integer Internal price record ID
price string Historical BTC-USD price
timestamp string Price timestamp (ISO 8601 format)

Get Funding Rate

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "get_funding_rate",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 23,
    "price": "42643.9899999999979627318680286407470703125",
    "rate": "0",
    "timestamp": "2024-01-31T10:00:00.075603Z"
  },
  "id": 123
}

Description: Retrieves the current funding rate for BTC-USD perpetual contracts, essential for understanding the cost of holding positions and market sentiment.

Use Cases:

Current funding rate

HTTP Method

POST

RPC Method

get_funding_rate

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
id integer Internal funding rate record ID
price string BTC-USD price at funding time
rate string Current funding rate
timestamp string Funding rate timestamp (ISO 8601 format)

Historical Funding Rate

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "historical_funding_rate",
  id: 123,
  params: {
    from: "2024-01-13T00:00:00Z",
    to: "2024-02-15T01:00:00Z",
    limit: 3,
    offset: 0,
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "id": 1,
      "price": "43537.7399999999979627318680286407470703125",
      "rate": "0.125",
      "timestamp": "2024-01-30T12:00:00.027626Z"
    },
    {
      "id": 2,
      "price": "43436.860000000000582076609134674072265625",
      "rate": "0.125",
      "timestamp": "2024-01-30T13:00:00.026145Z"
    },
    {
      "id": 3,
      "price": "43287.610000000000582076609134674072265625",
      "rate": "0.125",
      "timestamp": "2024-01-30T14:00:00.070450Z"
    }
  ],
  "id": 123
}

Description: Provides historical funding rate data for analyzing past market conditions and developing predictive models for funding rate movements.

Use Cases:

Historical funding rate

HTTP Method

POST

RPC Method

historical_funding_rate

Message Parameters

Params Data_Type Values
from datetime Start time (ISO 8601)
to datetime End time (ISO 8601)
limit integer Number of entries (max 5000)
offset integer Page offset

Response Fields

Field Data_Type Description
id integer Internal funding rate record ID
price string BTC-USD price at funding time
rate string Funding rate for the period
timestamp string Funding rate timestamp (ISO 8601 format)

Get Fee Rate

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "get_fee_rate",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 42,
    "order_filled_on_market": "0.0005",
    "order_filled_on_limit": "0.00025",
    "order_settled_on_market": "0.00075",
    "order_settled_on_limit": "0.0005",
    "timestamp": "2024-02-27T12:00:00Z"
  },
  "id": 123
}

Description: Returns the current trading fee structure for different order types and execution scenarios on the Relayer-matchbook.

Use Cases:

Current fee rate

HTTP Method

POST

RPC Method

get_fee_rate

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
id integer Internal fee rate record ID
order_filled_on_market string Fee rate for market orders when filled
order_filled_on_limit string Fee rate for limit orders when filled
order_settled_on_market string Fee rate for market orders when settled
order_settled_on_limit string Fee rate for limit orders when settled
timestamp string Fee rate timestamp (ISO 8601 format)

Historical Fee Rate

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "historical_fee_rate",
  id: 123,
  params: {
    from: "2024-01-01T00:00:00Z",
    to: "2024-02-01T00:00:00Z",
    limit: 3,
    offset: 0,
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "id": 40,
      "order_filled_on_market": "0.0005",
      "order_filled_on_limit": "0.00025",
      "order_settled_on_market": "0.00075",
      "order_settled_on_limit": "0.0005",
      "timestamp": "2024-01-28T12:00:00Z"
    },
    {
      "id": 41,
      "order_filled_on_market": "0.0005",
      "order_filled_on_limit": "0.00025",
      "order_settled_on_market": "0.00075",
      "order_settled_on_limit": "0.0005",
      "timestamp": "2024-01-29T12:00:00Z"
    },
    {
      "id": 42,
      "order_filled_on_market": "0.0005",
      "order_filled_on_limit": "0.00025",
      "order_settled_on_market": "0.00075",
      "order_settled_on_limit": "0.0005",
      "timestamp": "2024-01-30T12:00:00Z"
    }
  ],
  "id": 123
}

Description: Provides historical trading fee data for analyzing fee trends and optimizing trading strategies over time.

Use Cases:

Historical fee rate

HTTP Method

POST

RPC Method

historical_fee_rate

Message Parameters

Params Data_Type Values
from datetime Start time (ISO 8601)
to datetime End time (ISO 8601)
limit integer Number of entries (max 5000)
offset integer Page offset

Response Fields

Field Data_Type Description
id integer Internal fee rate record ID
order_filled_on_market string Fee rate for market orders when filled
order_filled_on_limit string Fee rate for limit orders when filled
order_settled_on_market string Fee rate for market orders when settled
order_settled_on_limit string Fee rate for limit orders when settled
timestamp string Fee rate timestamp (ISO 8601 format)

Market Analytics

These endpoints provide aggregate market metrics such as position sizes, order book depth, pool information, APY, and open interest. They help you assess liquidity, market sentiment, and risk before placing orders or building trading strategies.

Position Size

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "position_size",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "total": "17374082",
    "total_long": "17374082",
    "total_short": "0"
  },
  "id": 123
}

Description: Provides aggregate position size information across all market participants, showing total open interest and market exposure distribution.

Use Cases:

Position Size

HTTP Method

POST

RPC Method

position_size

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
total string Total open position size
total_long string Total long position size
total_short string Total short position size

Open Limit Orders

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "open_limit_orders",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "ask": [
      { "positionsize": 5000000, "price": 45000.50 }
    ],
    "bid": [
      { "positionsize": 3000000, "price": 44500.25 }
    ]
  },
  "id": 123
}

Description: Displays the current order book with open limit orders from Redis cache, showing market depth and liquidity for both buy (bid) and sell (ask) sides. Limited to top 10 entries per side.

Use Cases:

Open Limit Orders

HTTP Method

POST

RPC Method

open_limit_orders

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
ask array Array of ask (sell) orders in the order book
bid array Array of bid (buy) orders in the order book

Each order in ask/bid arrays contains:

Field Data_Type Description
positionsize number Size of the limit order
price number Price of the limit order

Recent Trade Orders

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "recent_trade_orders",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "order_id": "a2369fcf-489b-4ddf-85f6-78ec076401d0",
      "side": "LONG",
      "price": "35000",
      "positionsize": "8686710",
      "timestamp": "2024-01-30T11:13:23.386791Z"
    },
    {
      "order_id": "b3468eda-612a-4eef-96f7-89fc186502b1",
      "side": "LONG",
      "price": "35000",
      "positionsize": "8687372",
      "timestamp": "2024-01-30T12:42:59.466955Z"
    }
  ],
  "id": 123
}

Description: Retrieves the latest executed trades from the Redis cache (last 24 hours, limited to 25 most recent). Shows real-time market activity and price discovery.

Use Cases:

Recent Trade Orders

HTTP Method

POST

RPC Method

recent_trade_orders

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
order_id string Unique identifier for the executed trade
side string Trade direction ("LONG" or "SHORT")
price string Execution price of the trade
positionsize string Size of the executed trade
timestamp string Trade execution timestamp (ISO 8601 format)

Pool Share Value

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "pool_share_value",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": 1.0253,
  "id": 123
}

Description: Returns the current value of lending pool shares, calculated as total_locked_value / total_pool_share. Essential for yield farming and liquidity provision calculations.

Use Cases:

Current pool share value

HTTP Method

POST

RPC Method

pool_share_value

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
result number Current value per pool share

Lend Pool Info

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "lend_pool_info",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 1,
    "sequence": 100,
    "nonce": 50,
    "total_pool_share": "1000000",
    "total_locked_value": "1025300",
    "pending_orders": 2,
    "aggregate_log_sequence": 150,
    "last_snapshot_id": 45
  },
  "id": 123
}

Description: Returns complete lending pool information including total pool shares, total locked value, and operational state.

Use Cases:

Lend Pool Info

HTTP Method

POST

RPC Method

lend_pool_info

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
id integer Internal pool record ID
sequence integer Pool sequence number
nonce integer Pool nonce
total_pool_share string Total outstanding pool shares
total_locked_value string Total value locked in the pool
pending_orders integer Number of pending orders in the pool
aggregate_log_sequence integer Aggregate log sequence number
last_snapshot_id integer ID of the last pool snapshot

Last Day APY

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "last_day_apy",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": 12.45,
  "id": 123
}

Description: Returns the annualized percentage yield (APY) computed from the lending pool's share price change over the last 24 hours.

Use Cases:

Last 24-hour APY

HTTP Method

POST

RPC Method

last_day_apy

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
result number or null Annualized percentage yield for the last 24h

APY Chart

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "apy_chart",
  id: 123,
  params: {
    range: "1d",
    step: "5m",
    lookback: "24h",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "bucket_ts": "2024-02-27T00:00:00Z",
      "apy": "12.34"
    },
    {
      "bucket_ts": "2024-02-27T00:05:00Z",
      "apy": "12.56"
    },
    {
      "bucket_ts": "2024-02-27T00:10:00Z",
      "apy": "11.89"
    }
  ],
  "id": 123
}

Description: Returns a time series of APY data points for charting, computed from the lending pool's share price changes using the SQL apy_series() function. Supports configurable chart range, step interval, and lookback window.

Use Cases:

APY Chart

HTTP Method

POST

RPC Method

apy_chart

Message Parameters

Params Data_Type Values
range string Chart range: "1d", "7d", "30d", "24 hours", "7 days", "30 days"
step string (Optional) Step interval: "1m", "5m", "15m", "30m", "1h", "2h", "4h", "12h". Default varies by range
lookback string (Optional) Trailing APY lookback window: "24h", "7d", "30d". Default "24 hours"

Response Fields

Field Data_Type Description
bucket_ts string Bucket timestamp (ISO 8601 format)
apy string Annualized percentage yield at this point

Open Interest

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "open_interest",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "long_exposure": "1250000.50",
    "short_exposure": "980000.25",
    "last_order_timestamp": "2024-02-27T15:30:00Z"
  },
  "id": 123
}

Description: Returns the current open interest data including long and short exposure (computed as initial_margin * leverage for active filled orders), along with the most recent order timestamp.

Use Cases:

Open Interest

HTTP Method

POST

RPC Method

open_interest

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
long_exposure string Total long exposure (margin * leverage)
short_exposure string Total short exposure (margin * leverage)
last_order_timestamp string Timestamp of last order (ISO 8601, nullable)

Market Stats

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "get_market_stats",
  id: 123,
  params: null,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "pool_equity_btc": 10.5,
    "total_long_btc": 3.2,
    "total_short_btc": 2.8,
    "total_pending_long_btc": 0.5,
    "total_pending_short_btc": 0.3,
    "open_interest_btc": 6.0,
    "net_exposure_btc": 0.4,
    "long_pct": 0.5333,
    "short_pct": 0.4667,
    "utilization": 0.5714,
    "max_long_btc": 2.5,
    "max_short_btc": 2.9,
    "status": "HEALTHY",
    "status_reason": null,
    "params": {
      "max_oi_mult": 4.0,
      "max_net_mult": 0.8,
      "max_position_pct": 0.02,
      "min_position_btc": 0.0,
      "max_leverage": 50.0,
      "mm_ratio": 0.4
    }
  },
  "id": 123
}

Description: Returns comprehensive market risk statistics computed from the cached RiskState (Redis) and lending pool equity. Includes open interest, net exposure, utilization ratio, maximum allowed position sizes, and market status (HEALTHY, CLOSE_ONLY, or HALT).

Use Cases:

Market Stats

HTTP Method

POST

RPC Method

get_market_stats

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
pool_equity_btc number Total pool equity in BTC
total_long_btc number Total long positions in BTC
total_short_btc number Total short positions in BTC
total_pending_long_btc number Total pending long positions in BTC
total_pending_short_btc number Total pending short positions in BTC
open_interest_btc number Total open interest (long + short) in BTC
net_exposure_btc number Net exposure (long - short) in BTC
long_pct number Percentage of OI that is long (0-1)
short_pct number Percentage of OI that is short (0-1)
utilization number OI / pool equity ratio (0-1)
max_long_btc number Maximum additional long position allowed in BTC
max_short_btc number Maximum additional short position allowed in BTC
status string Market status: "HEALTHY", "CLOSE_ONLY", or "HALT"
status_reason string Reason for non-healthy status (nullable). E.g. "MANUAL_HALT", "POOL_EQUITY_INVALID"
params object Risk parameters object (see below)

Risk params object:

Field Data_Type Description
max_oi_mult number Maximum OI multiplier relative to pool equity
max_net_mult number Maximum net exposure multiplier relative to pool
max_position_pct number Maximum single position as percentage of pool equity
min_position_btc number Minimum position size in BTC
max_leverage number Maximum allowed leverage
mm_ratio number Maintenance margin ratio

Account Analytics

Account analytics endpoints return trading activity summaries for a given Twilight address over a date range. They show settled, filled, and liquidated positions and counts, useful for portfolio tracking, reporting, and compliance.

Account Summary by Twilight Address

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "account_summary_by_twilight_address",
  id: 123,
  params: {
    t_address: "twilight1abc123...",
    from: "2024-01-01T00:00:00Z",
    to: "2024-02-01T00:00:00Z",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "from": "2024-01-01T00:00:00Z",
    "to": "2024-02-01T00:00:00Z",
    "settled_positionsize": "5000000",
    "filled_positionsize": "12000000",
    "liquidated_positionsize": "500000",
    "settled_count": 3,
    "filled_count": 8,
    "liquidated_count": 1
  },
  "id": 123
}

Description: Returns a trading activity summary for a specific Twilight address, including aggregated position sizes and order counts by status (settled, filled, liquidated). Dates must be at least 7 days in the past (configurable via MAX_DELAYED_DAYS).

Use Cases:

Account Summary by Twilight Address

HTTP Method

POST

RPC Method

account_summary_by_twilight_address

Message Parameters

Params Data_Type Values
t_address string Twilight address to query
from datetime (Optional) Start time (ISO 8601). Must be >= 7 days in the past
to datetime (Optional) End time (ISO 8601). Capped to 7 days ago if in recent range
since datetime (Optional) Alternative to from/to. Must be >= 7 days in the past

Note: Either since or from must be provided. to cannot be provided without from.

Response Fields

Field Data_Type Description
from string Effective start time (ISO 8601)
to string Effective end time (ISO 8601)
settled_positionsize string Total position size of settled orders
filled_positionsize string Total position size of filled orders
liquidated_positionsize string Total position size of liquidated orders
settled_count integer Number of settled orders
filled_count integer Number of filled orders
liquidated_count integer Number of liquidated orders

All Account Summaries

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "all_account_summaries",
  id: 123,
  params: {
    from: "2024-01-01T00:00:00Z",
    to: "2024-02-01T00:00:00Z",
    limit: 50,
    offset: 0,
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "from": "2024-01-01T00:00:00Z",
    "to": "2024-02-01T00:00:00Z",
    "limit": 50,
    "offset": 0,
    "summaries": [
      {
        "twilight_address": "twilight1abc123...",
        "settled_positionsize": "5000000",
        "filled_positionsize": "12000000",
        "liquidated_positionsize": "500000",
        "settled_count": 3,
        "filled_count": 8,
        "liquidated_count": 1
      }
    ]
  },
  "id": 123
}

Description: Returns paginated trading activity summaries for all Twilight addresses within a time range. Dates must be at least 7 days in the past. Supports pagination with configurable limit (max 500) and offset.

Use Cases:

All Account Summaries

HTTP Method

POST

RPC Method

all_account_summaries

Message Parameters

Params Data_Type Values
from datetime (Optional) Start time (ISO 8601). Must be >= 7 days in the past
to datetime (Optional) End time (ISO 8601). Capped to 7 days ago if in recent range
since datetime (Optional) Alternative to from/to. Must be >= 7 days in the past
limit integer (Optional) Number of results per page (1-500, default 50)
offset integer (Optional) Page offset (default 0)

Note: Either since or from must be provided. to cannot be provided without from.

Response Fields

Field Data_Type Description
from string Effective start time (ISO 8601)
to string Effective end time (ISO 8601)
limit integer Applied page limit
offset integer Applied page offset
summaries array Array of account summary objects

Each summary object:

Field Data_Type Description
twilight_address string Twilight address
settled_positionsize string Total position size of settled orders
filled_positionsize string Total position size of filled orders
liquidated_positionsize string Total position size of liquidated orders
settled_count integer Number of settled orders
filled_count integer Number of filled orders
liquidated_count integer Number of liquidated orders

System Information

System information endpoints provide server time and basic status. Use them for client-server time synchronization, request timestamp validation, and audit trail consistency.

Server Time

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "server_time",
  id: 123,
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": "2024-01-31T11:05:37.546616309Z",
  "id": 123
}

Description: Returns the current server timestamp for time synchronization and ensuring accurate order timestamping.

Use Cases:

Server time

HTTP Method

POST

RPC Method

server_time

Message Parameters

Params Data_Type Values
N/A null No parameters required

Response Fields

Field Data_Type Description
result string Current server timestamp (ISO 8601 format)

Authentication

Authentication endpoints let you obtain API credentials (api_key and api_secret) by signing a message with your wallet. Use these credentials to authenticate requests to order management and account endpoints.

Login

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  account_address: "twilight1l03j8j5nwegy9fkz9p0whkxch2e2zqcq6lvfda",
  data: "hello",
  signature: {
    pub_key: {
      type: "tendermint/PubKeySecp256k1",
      value: "AkNImdlt3/+4axILXJsyiBigMWheg8i8npwTX/AzBrSC",
    },
    signature:
      "waaVXJnXIYQd2BG4rVA12q5OTuctzcDt7BLyHw7Yx/1b2iDFrl4kOcC/VlvE3tvLZq7Dd/qSiMEdYK1DvDPmZw==",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/register", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "api_key": "7d4fd427-ab9f-4a4d-8163-7faddb0c50e2",
  "api_secret": "dab81c56-2cb1-4bfb-b58d-26e14d1262d6"
}

Description: Authentication endpoint that generates API credentials for accessing private trading and account management functions.

Use Cases:

Endpoint to get api_key and api_secret for private API endpoints.

HTTP Method

POST

Message Body

Params Data_Type Values
account_address string Twilight address
data string Message string
signature object {"pub_key": {"type": "tendermint/PubKeySecp256k1", "value": string}, "signature": string}

Response Fields

Field Data_Type Description
api_key string Generated API key for accessing private endpoints
api_secret string Generated API secret for request signature generation

Order Management

Order management endpoints let you submit, settle, and cancel trading and lending orders. They support manual and automated trading flows, portfolio rebalancing, and risk management. Authentication required.

Submit Trade Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "submit_trade_order",
  id: 123,
  params: {
    data: "hex_encoded_transaction_data",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "message": "Order request submitted successfully",
    "id": "unique_request_id"
  },
  "id": 123
}

Description: Submits a new perpetual contract trading order to the Relayer-matchbook orderbook. The hex-encoded data contains a serialized CreateTraderOrderClientZkos struct with ZK proof data and order parameters.

Use Cases:

Submit a new trade order to the Relayer-matchbook

HTTP Method

POST

RPC Method

submit_trade_order

Message Parameters

Params Data_Type Values
data string Hex-encoded transaction data for the trade order

Response Fields

Field Data_Type Description
message string Success message confirming order submission
id string Unique request identifier for tracking purposes

Submit Lend Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "submit_lend_order",
  id: 123,
  params: {
    data: "hex_encoded_transaction_data",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "message": "Order request submitted successfully",
    "id": "unique_request_id"
  },
  "id": 123
}

Description: Submits a new lending order to participate in the lending pool and earn yield on deposited assets. The hex-encoded data contains a serialized CreateLendOrderZkos struct.

Use Cases:

Submit a new lend order to the lending pool

HTTP Method

POST

RPC Method

submit_lend_order

Message Parameters

Params Data_Type Values
data string Hex-encoded transaction data for the lend order

Response Fields

Field Data_Type Description
message string Success message confirming order submission
id string Unique request identifier for tracking purposes

Settle Trade Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "settle_trade_order",
  id: 123,
  params: {
    data: "hex_encoded_settlement_data",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "message": "Order request submitted successfully",
    "id": "unique_request_id"
  },
  "id": 123
}

Description: Executes the settlement process for filled trade orders, finalizing the trade and updating account balances. The hex-encoded data contains a serialized ExecuteTraderOrderZkos struct.

Use Cases:

Settle an existing trade order

HTTP Method

POST

RPC Method

settle_trade_order

Message Parameters

Params Data_Type Values
data string Hex-encoded settlement data for the trade order

Response Fields

Field Data_Type Description
message string Success message confirming order settlement
id string Unique request identifier for tracking purposes

Settle Lend Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "settle_lend_order",
  id: 123,
  params: {
    data: "hex_encoded_settlement_data",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "message": "Order request submitted successfully",
    "id": "unique_request_id"
  },
  "id": 123
}

Description: Executes the settlement process for lending orders, finalizing the lending position and updating pool shares. The hex-encoded data contains a serialized ExecuteLendOrderZkos struct.

Use Cases:

Settle an existing lend order

HTTP Method

POST

RPC Method

settle_lend_order

Message Parameters

Params Data_Type Values
data string Hex-encoded settlement data for the lend order

Response Fields

Field Data_Type Description
message string Success message confirming order settlement
id string Unique request identifier for tracking purposes

Cancel Trader Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "cancel_trader_order",
  id: 123,
  params: {
    data: "hex_encoded_cancellation_data",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "message": "Order request submitted successfully",
    "id": "unique_request_id"
  },
  "id": 123
}

Description: Cancels an existing unfilled or partially filled trading order, removing it from the orderbook. The hex-encoded data contains a serialized CancelTraderOrderZkos struct. Only orders with a cancelable status can be cancelled.

Use Cases:

Cancel an existing trader order

HTTP Method

POST

RPC Method

cancel_trader_order

Message Parameters

Params Data_Type Values
data string Hex-encoded cancellation data for the trader order

Response Fields

Field Data_Type Description
message string Success message confirming order cancellation
id string Unique request identifier for tracking purposes

Order Information & Chain Data

These endpoints let you query order details, historical orders, funding history, and blockchain transaction hashes. Use them for order tracking, compliance reporting, and verification of on-chain settlement.

Trader Order Info

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "trader_order_info",
  id: 123,
  params: {
    data: "hex_encoded_data_string",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 50,
    "uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
    "account_id": "0c08ed4f0daeec9b...",
    "position_type": "LONG",
    "order_status": "FILLED",
    "order_type": "MARKET",
    "entryprice": "42508.71",
    "execution_price": "30000",
    "positionsize": "4250871",
    "leverage": "10",
    "initial_margin": "10",
    "available_margin": "10",
    "timestamp": "2024-01-31T11:14:45.575359Z",
    "bankruptcy_price": "38644.28",
    "bankruptcy_value": "110",
    "maintenance_margin": "0.5375",
    "liquidation_price": "38834.04",
    "unrealized_pnl": "0",
    "settlement_price": "0",
    "entry_nonce": 0,
    "exit_nonce": 0,
    "entry_sequence": 1,
    "fee_filled": "0",
    "fee_settled": "0"
  },
  "id": 123
}

Description: Retrieves the latest trader order for an account using encrypted account data (hex-encoded QueryTraderOrderZkos). The request is verified via verify_query_order before querying the database.

Use Cases:

Get trader order information by account ID

HTTP Method

POST

RPC Method

trader_order_info

Message Parameters

Params Data_Type Values
data string Hex-encoded query data for trader order

Response Fields

Field Data_Type Description
id integer Internal order ID
uuid string Unique order identifier
account_id string Account public key associated with the order
position_type string Position direction ("LONG" or "SHORT")
order_status string Current order status ("FILLED", "PENDING", "CANCELLED", "SETTLED", "LIQUIDATE")
order_type string Order type ("MARKET", "LIMIT")
entryprice string Entry price for the position
execution_price string Actual execution price
positionsize string Position size in base currency
leverage string Leverage multiplier
initial_margin string Initial margin requirement
available_margin string Available margin for the position
timestamp string Order creation timestamp (ISO 8601 format)
bankruptcy_price string Price at which position becomes bankrupt
bankruptcy_value string Value at bankruptcy price
maintenance_margin string Maintenance margin requirement
liquidation_price string Price at which position gets liquidated
unrealized_pnl string Current unrealized profit/loss
settlement_price string Settlement price if order is settled
entry_nonce integer Entry transaction nonce
exit_nonce integer Exit transaction nonce
entry_sequence integer Entry sequence number
fee_filled string Fee paid when order was filled
fee_settled string Fee paid when order was settled

Trader Order Info V1

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "trader_order_info_v1",
  id: 123,
  params: {
    data: "hex_encoded_data_string",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 50,
    "uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
    "account_id": "0c08ed4f0daeec9b...",
    "position_type": "LONG",
    "order_status": "FILLED",
    "order_type": "MARKET",
    "entryprice": "42508.71",
    "execution_price": "30000",
    "positionsize": "4250871",
    "leverage": "10",
    "initial_margin": "10",
    "available_margin": "10",
    "timestamp": "2024-01-31T11:14:45.575359Z",
    "bankruptcy_price": "38644.28",
    "bankruptcy_value": "110",
    "maintenance_margin": "0.5375",
    "liquidation_price": "38834.04",
    "unrealized_pnl": "0",
    "settlement_price": "0",
    "entry_nonce": 0,
    "exit_nonce": 0,
    "entry_sequence": 1,
    "fee_filled": "0",
    "fee_settled": "0",
    "settle_limit": {
      "uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
      "position_type": "LONG",
      "price": "45000.00"
    },
    "funding_applied": "0.0025"
  },
  "id": 123
}

Description: Enhanced version of trader_order_info that includes additional fields: settle_limit (the latest close limit price for non-settled/non-liquidated orders) and funding_applied (the cumulative funding payment applied to the order, computed as initial_margin - available_margin - fee_filled).

Use Cases:

Get enhanced trader order information by account ID

HTTP Method

POST

RPC Method

trader_order_info_v1

Message Parameters

Params Data_Type Values
data string Hex-encoded query data for trader order

Response Fields

All fields from trader_order_info plus:

Field Data_Type Description
settle_limit object Latest close limit details (null if settled/liquidated or no limit set)
funding_applied string Cumulative funding payment applied (null if no funding updates recorded)

settle_limit object (when present):

Field Data_Type Description
uuid string Order UUID
position_type string Position direction
price string Close limit price

Lend Order Info

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "lend_order_info",
  id: 123,
  params: {
    data: "hex_encoded_data_string",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 25,
    "uuid": "6fb4f910-ceb4-432d-995b-79eddb8c4c83",
    "account_id": "0c08ed4f0daeec9b...",
    "balance": "153620",
    "order_status": "FILLED",
    "order_type": "MARKET",
    "entry_nonce": 0,
    "exit_nonce": 0,
    "deposit": "153620",
    "new_lend_state_amount": "153620",
    "timestamp": "2024-02-28T04:59:44.020048Z",
    "npoolshare": "100",
    "nwithdraw": "0",
    "payment": "0",
    "tlv0": "0",
    "tps0": "0",
    "tlv1": "0",
    "tps1": "0",
    "tlv2": "0",
    "tps2": "0",
    "tlv3": "0",
    "tps3": "0",
    "entry_sequence": 10
  },
  "id": 123
}

Description: Retrieves detailed lending order information using encrypted account data (hex-encoded QueryLendOrderZkos). The request is verified via verify_query_order before querying the database.

Use Cases:

Get lend order information by account ID

HTTP Method

POST

RPC Method

lend_order_info

Message Parameters

Params Data_Type Values
data string Hex-encoded query data for lend order

Response Fields

Field Data_Type Description
id integer Internal lend order ID
uuid string Unique lend order identifier
account_id string Account public key associated with the lend order
balance string Current balance in the lend order
order_status string Current order status ("FILLED", "PENDING", "CANCELLED", "SETTLED")
order_type string Order type ("MARKET", "LIMIT")
entry_nonce integer Entry transaction nonce
exit_nonce integer Exit transaction nonce
deposit string Initial deposit amount
new_lend_state_amount string Updated lend state amount
timestamp string Order creation timestamp (ISO 8601 format)
npoolshare string Number of pool shares
nwithdraw string Withdrawal amount
payment string Payment amount
tlv0 string Total locked value tier 0
tps0 string Total pool shares tier 0
tlv1 string Total locked value tier 1
tps1 string Total pool shares tier 1
tlv2 string Total locked value tier 2
tps2 string Total pool shares tier 2
tlv3 string Total locked value tier 3
tps3 string Total pool shares tier 3
entry_sequence integer Entry sequence number

Historical Trader Order Info

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "historical_trader_order_info",
  id: 123,
  params: {
    data: "hex_encoded_data_string",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "id": 50,
      "uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
      "account_id": "0c08ed4f0daeec9b...",
      "position_type": "LONG",
      "order_status": "SETTLED",
      "order_type": "MARKET",
      "entryprice": "42508.71",
      "execution_price": "30000",
      "positionsize": "4250871",
      "leverage": "10",
      "initial_margin": "10",
      "available_margin": "9.85",
      "timestamp": "2024-01-31T11:14:45.575359Z",
      "bankruptcy_price": "38644.28",
      "bankruptcy_value": "110",
      "maintenance_margin": "0.5375",
      "liquidation_price": "38834.04",
      "unrealized_pnl": "1.25",
      "settlement_price": "43500.00",
      "entry_nonce": 0,
      "exit_nonce": 1,
      "entry_sequence": 1,
      "fee_filled": "0.05",
      "fee_settled": "0.075"
    }
  ],
  "id": 123
}

Description: Retrieves the full history of trader orders for an account (up to 500 most recent). Uses the same hex-encoded QueryTraderOrderZkos format as trader_order_info but returns an array of all historical orders instead of just the latest.

Use Cases:

Get historical trader order information by account ID

HTTP Method

POST

RPC Method

historical_trader_order_info

Message Parameters

Params Data_Type Values
data string Hex-encoded query data for trader order

Response Fields

Returns an array of trader order objects. Each object has the same fields as the trader_order_info response.

Historical Lend Order Info

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "historical_lend_order_info",
  id: 123,
  params: {
    data: "hex_encoded_data_string",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "id": 25,
      "uuid": "6fb4f910-ceb4-432d-995b-79eddb8c4c83",
      "account_id": "0c08ed4f0daeec9b...",
      "balance": "153620",
      "order_status": "SETTLED",
      "order_type": "MARKET",
      "entry_nonce": 0,
      "exit_nonce": 1,
      "deposit": "153620",
      "new_lend_state_amount": "155000",
      "timestamp": "2024-02-28T04:59:44.020048Z",
      "npoolshare": "100",
      "nwithdraw": "155000",
      "payment": "1380",
      "tlv0": "0",
      "tps0": "0",
      "tlv1": "0",
      "tps1": "0",
      "tlv2": "0",
      "tps2": "0",
      "tlv3": "0",
      "tps3": "0",
      "entry_sequence": 10
    }
  ],
  "id": 123
}

Description: Retrieves the full history of lending orders for an account. Uses the same hex-encoded QueryLendOrderZkos format as lend_order_info but returns an array of all historical orders.

Use Cases:

Get historical lend order information by account ID

HTTP Method

POST

RPC Method

historical_lend_order_info

Message Parameters

Params Data_Type Values
data string Hex-encoded query data for lend order

Response Fields

Returns an array of lend order objects. Each object has the same fields as the lend_order_info response.

Order Funding History

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "order_funding_history",
  id: 123,
  params: {
    data: "hex_encoded_data_string",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "time": "2024-01-31T17:35:14.662529Z",
      "position_side": "LONG",
      "payment": "0.0042",
      "funding_rate": "0.0001",
      "order_id": "3374714d-8a95-4096-855f-7e2675fe0dc8"
    }
  ],
  "id": 123
}

Description: Retrieves the funding payment history for a trader order using encrypted account data (hex-encoded QueryTraderOrderZkos). The request is verified via verify_query_order before querying the database. For each funding update on the order, the endpoint returns the cumulative payment delta and the corresponding funding rate.

Use Cases:

Get order funding history by account ID

HTTP Method

POST

RPC Method

order_funding_history

Message Parameters

Params Data_Type Values
data string Hex-encoded query data for trader order

Response Fields

Returns an array of funding history entries:

Field Data_Type Description
time string Funding update timestamp (ISO 8601 format)
position_side string Position direction ("LONG" or "SHORT")
payment string Funding payment delta since previous update
funding_rate string Funding rate applied at this update
order_id string Order UUID associated with the funding update

Transaction Hashes

The transaction_hashes method supports three different parameter types for querying transaction data:

1. Query by Account ID

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "transaction_hashes",
  id: 123,
  params: {
    AccountId: {
      id: "0c3eb16783ccdbee855e0babf6d130101e7d66089bac20484606e52bf507d90e3a5049a3379b8afc47068d2508dfd71fe92adab7a5ad682fbbbb9b401158e62d42aa64cb22",
      status: "FILLED",
      limit: 100,
      offset: 0,
    },
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

2. Query by Transaction/Order ID

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "transaction_hashes",
  id: 123,
  params: {
    TxId: {
      id: "83216790-d1c6-40d9-a70e-712d5d81cecd",
      status: "SETTLED",
      limit: 100,
      offset: 0,
    },
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

3. Query by Request ID

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "transaction_hashes",
  id: 123,
  params: {
    RequestId: {
      id: "REQIDFCE62EB3F784D832BB59ABF8AD67D84DA502248B95B7F613F00820879478F325",
      status: "FILLED",
      limit: 100,
      offset: 0,
    },
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "account_id": "0c3eb16783ccdbee...",
      "datetime": "1708363831398559",
      "id": 4,
      "order_id": "83216790-d1c6-40d9-a70e-712d5d81cecd",
      "order_status": "FILLED",
      "order_type": "MARKET",
      "output": "01000000...",
      "request_id": "REQIDFCE62EB3F784D832BB59ABF8AD67D84DA502248B95B7F613F00820879478F325",
      "tx_hash": "8E291447D61EBC7E0AF5BB006576190E117516CA9A29358554C108718586FF58"
    }
  ],
  "id": 123
}

Description: Retrieves blockchain transaction hashes and details for order execution verification and audit trail purposes. Supports querying by Account ID, Transaction/Order ID, or Request ID, with optional status filtering and pagination.

Use Cases:

Transaction Hashes

HTTP Method

POST

RPC Method

transaction_hashes

Message Parameters

The transaction_hashes method accepts one of three parameter variants:

Variant 1: Query by Account ID

Params Data_Type Required Values
AccountId.id string Yes Account public key/identifier
AccountId.status string No Optional order status filter ("FILLED", "SETTLED", "PENDING", "CANCELLED")
AccountId.limit integer No Number of results (default 500, max 500)
AccountId.offset integer No Page offset (default 0)

Variant 2: Query by Transaction/Order ID

Params Data_Type Required Values
TxId.id string Yes Transaction/Order UUID
TxId.status string No Optional order status filter ("FILLED", "SETTLED", "PENDING", "CANCELLED")
TxId.limit integer No Number of results (default 500, max 500)
TxId.offset integer No Page offset (default 0)

Variant 3: Query by Request ID

Params Data_Type Required Values
RequestId.id string Yes Unique request identifier
RequestId.status string No Optional order status filter ("FILLED", "SETTLED", "PENDING", "CANCELLED")
RequestId.limit integer No Number of results (default 500, max 500)
RequestId.offset integer No Page offset (default 0)

Response Fields

Field Data_Type Description
id integer Internal transaction record ID
order_id string Order UUID associated with the transaction
account_id string Account ID associated with the transaction
tx_hash string Blockchain transaction hash
order_type string Order type ("MARKET", "LIMIT")
order_status string Order status at transaction time
datetime string Transaction timestamp (Unix timestamp in microseconds)
output string Hex-encoded transaction output data (nullable)
request_id string Unique request identifier (nullable)

Private API

Endpoint URL

API_ENDPOINT_PRODUCTION = https://relayer.twilight.rest

API_ENDPOINT_STAGING = https://app.twilight.rest

Request Structure

All private API requests must be sent to:

API_ENDPOINT/api/private

For example:

Authentication

Authentication is required for all private API methods using the following headers:

Header Name Description Required
relayer-api-key Your unique API key obtained from the /register endpoint Yes
signature HMAC-SHA256 signature of the request body using your API secret Yes
datetime Unix timestamp in milliseconds Yes

JavaScript Methods Used in Examples

const CryptoJS = require("crypto-js");

function generateSignature(body, secret) {
  return CryptoJS.HmacSHA256(body, secret).toString();
}

function getCurrentTimestamp() {
  return Date.now().toString();
}

Request Format

All private API requests follow this structure:

Component Description
URL API_ENDPOINT/api/private
Method POST
Content-Type application/json
Body JSON-RPC 2.0 formatted request

Authentication Process

  1. Obtain api_key and api_secret from the /register endpoint
  2. Create JSON-RPC request body
  3. Generate HMAC-SHA256 signature of the body using your api_secret
  4. Include required headers in your request
  5. Send POST request to the private API endpoint

Getting API Credentials

Before you can use any private API methods, you must first obtain your API credentials (api_key and api_secret) by calling the Login method available in the Public API.

Step 1: Call the Login Method

The login method is available in the Public API (Click Here) and requires your Twilight account signature for authentication. Here's how to use it:

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  account_address: "twilight1l03j8j5nwegy9fkz9p0whkxch2e2zqcq6lvfda",
  data: "hello",
  signature: {
    pub_key: {
      type: "tendermint/PubKeySecp256k1",
      value: "AkNImdlt3/+4axILXJsyiBigMWheg8i8npwTX/AzBrSC",
    },
    signature:
      "waaVXJnXIYQd2BG4rVA12q5OTuctzcDt7BLyHw7Yx/1b2iDFrl4kOcC/VlvE3tvLZq7Dd/qSiMEdYK1DvDPmZw==",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/register", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

Step 2: Receive Your API Credentials

The login method will return your API credentials:

{
  "api_key": "7d4fd427-ab9f-4a4d-8163-7faddb0c50e2",
  "api_secret": "dab81c56-2cb1-4bfb-b58d-26e14d1262d6"
}

Step 3: Use Credentials in Private API Calls

Once you have your api_key and api_secret, include them in all private API requests as shown in the authentication headers above.


Submit Lend Order zkos

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "submit_lend_order",
  id: 123,
  params: {
    data: "0a000000000000006163636f756e745f696400000000010000000000000000002440000000000000244000000000000024400400000000000000004cdd4000000000004cdd400000000000000000000000000000000000000000000000000000000000000000000000000000000000f67459dae1fc1557f4d04329b55ff99f93f0181c520feae7d2b36d107d6573492c7f1847780e5e00628e6c03daa79d09ec7068e17af8fb458267aacfc9f2902f8a000000000000003063343264383661616637393037306532303235653363353139303461336565393162643065663262643631383064393363643633316265613963373166313636636532633263333936393131356362333238333238363062353631653762636664366433396533313238643732663936343632386562653839616434326466343163626639653036620001000000010000008a000000000000003063343264383661616637393037306532303235653363353139303461336565393162643065663262643631383064393363643633316265613963373166313636636532633263333936393131356362333238333238363062353631653762636664366433396533313238643732663936343632386562653839616434326466343163626639653036628a0000000000000030633432643836616166373930373065323032356533633531393034613365653931626430656632626436313830643933636436333162656139633731663136366365326332633339363931313563623332383332383630623536316537626366643664333965333132386437326639363436323865626538396164343264663431636266396530366201000000000000000a0000000000000000000000000000006ad54205ef1a2c17a85534583b763f7e66856273cfc4792cb787295d563afb0100000000004000000000000000606052ed69a939d6cef060fe417eae2da1ff94bf9c3191818eab27f9cd767d662ab4767e1a103969e3ec8c29486970657062e6f821d82f29693c82b110eb2006010000000100000000000000ab01deb6e24b2810fbc5648cd99875c659530ec11dc7826ba49e3b04f6db130201000000000000004ace5f3aeccc847fcd24ebce3b026ea2b764b825a4b4a1c98ba8e42d31ffbc070000000000000000379cebd51a20359852e8f0ef04fca9c878c9d747c0a606c23f67dab160d2480d",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "msg": "Order request submitted successfully",
    "id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
  },
  "id": 123
}

Description: Submits a new lending order to participate in the lending pool and earn yield on deposited assets using zero-knowledge proofs.

Use Cases:

HTTP Method

POST

RPC Method

submit_lend_order

Message Parameters

Params Data_Type Required Values
data string Yes Hex-encoded zkos transaction data for the lend order

Response Fields

Field Data_Type Description
msg string Success message confirming order submission
id_key string Unique request identifier for tracking purposes

Submit Trade Order zkos

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "submit_trade_order",
  id: 123,
  params: {
    data: "0a000000000000006163636f756e745f69640000000001000000000000000000344000000000006af84000000000006af84004000000000000000017e140000000000017e140000000000000000060a86ee9d8da7e431b707fb1e344eea721fab8fe2b1ba9461a23182bf9b6d51e005a0cfa6cb6d5149e4d1602863014a1411fdda83ee83c6ef8b9e9934a4211ad4c62cb8729fda0d937220b11650d2eb063b7dfc5e26ee867597a2d69f52749b3118a000000000000003063376363666332356563306335333561383233326537383564646563333939373264633438653235616535373065333638623933383464633631343765633633396234656137313138623030303238393463396432643962666361663732643437613061343938393335313861346366623330613065383162613334613531363834653266303565390001000000010000002a000000000000003138663265626461313733666663366164326533623464336133383634613936616538613666376533308a000000000000003063376363666332356563306335333561383233326537383564646563333939373264633438653235616535373065333638623933383464633631343765633633396234656137313138623030303238393463396432643962666361663732643437613061343938393335313861346366623330613065383162613334613531363834653266303565390100000000000000a0860100000000000000000000000000b899875f246706825d9a849a195da763b3718fc2bdf44cc4eccbb447fe484d010104000000000000000300000001000000003c534c1000000000000000000000000000000000000000000000000000000002000000010000000000000014000000000000000000000000000000b899875f246706825d9a849a195da763b3718fc2bdf44cc4eccbb447fe484d010300000001000000b888000000000000000000000000000000000000000000000000000000000000030000000100000001000000000000000000000000000000000000000000000000000000000000000000000040000000000000004ea572adc412934d369e32e695dbc3eb00d2179cc725365a22e222a6d8f1b254cfb35aa583cd29e1d60d80fc632b557c8388ddd80d9c65d1e0f7547914608a05010000000100000000000000708bceb6fb2e6b61320047c873243ec510e3da990436e6e51884a226ba8fe30a010000000000000075bc2d792cbe4f8852a58874a3f58301f82c1dd82916076e7da1f805dd88cb070000000000000000c6d6a65205e48547a1baa04fa2a0cbd918957b952ee56eb19eb88cd6a5c47106",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "msg": "Order request submitted successfully",
    "id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
  },
  "id": 123
}

Description: Submits a new perpetual contract trading order using zero-knowledge proofs for privacy-preserving execution.

Use Cases:

HTTP Method

POST

RPC Method

submit_trade_order

Message Parameters

Params Data_Type Required Values
data string Yes Hex-encoded zkos transaction data for the trade order

Response Fields

Field Data_Type Description
msg string Success message confirming order submission
id_key string Unique request identifier for tracking purposes

Settle Trade Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "settle_trade_order",
  id: 123,
  params: {
    data: "0x48656c6c6f576f726c64",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "msg": "Order request submitted successfully",
    "id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
  },
  "id": 123
}

Description: Executes the settlement process for filled trade orders, finalizing the trade and updating account balances with cryptographic verification.

Use Cases:

HTTP Method

POST

RPC Method

settle_trade_order

Message Parameters

Params Data_Type Required Values
data string Yes Hex-encoded zkos settlement data for the trade order

Response Fields

Field Data_Type Description
msg string Success message confirming order submission
id_key string Unique request identifier for tracking purposes

Settle Lend Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "settle_lend_order",
  id: 123,
  params: {
    data: "0x48656c6c6f576f726c64",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "msg": "Order request submitted successfully",
    "id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
  },
  "id": 123
}

Description: Executes the settlement process for lending orders, finalizing the lending position and updating pool shares with yield calculations.

Use Cases:

HTTP Method

POST

RPC Method

settle_lend_order

Message Parameters

Params Data_Type Required Values
data string Yes Hex-encoded zkos settlement data for the lend order

Response Fields

Field Data_Type Description
msg string Success message confirming order submission
id_key string Unique request identifier for tracking purposes

Cancel Trader Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "cancel_trader_order",
  id: 123,
  params: {
    data: "0x48656c6c6f576f726c64",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "msg": "Order request submitted successfully",
    "id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
  },
  "id": 123
}

Description: Cancels an existing unfilled or partially filled trading order, removing it from the orderbook with cryptographic verification.

Use Cases:

HTTP Method

POST

RPC Method

cancel_trader_order

Message Parameters

Params Data_Type Required Values
data string Yes Hex-encoded zkos cancellation data for the trader order

Response Fields

Field Data_Type Description
msg string Success message confirming order submission
id_key string Unique request identifier for tracking purposes

Submit Bulk Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "submit_bulk_order",
  id: 123,
  params: [
    {
      data: "0x48656c6c6f576f726c64",
    },
    {
      data: "0x48656c6c6f576f726c65",
    },
  ],
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": "OK",
  "id": 123
}

Description: Submits multiple trading orders in a single request for efficient batch processing and reduced latency.

Use Cases:

HTTP Method

POST

RPC Method

submit_bulk_order

Message Parameters

Params Data_Type Required Values
Array of orders array Yes Array of order objects with hex-encoded zkos data

Response Fields

Field Data_Type Description
result string Status confirmation ("OK" indicates successful bulk submission)

Open Order

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "open_orders",
  id: 123,
  params: {},
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "id": 50,
      "uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
      "account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
      "position_type": "LONG",
      "order_status": "FILLED",
      "order_type": "MARKET",
      "entryprice": "42508.71",
      "execution_price": "30000",
      "positionsize": "4250871",
      "leverage": "10",
      "initial_margin": "10",
      "available_margin": "10",
      "timestamp": "2024-01-31T11:14:45.575359Z",
      "bankruptcy_price": "38644.28",
      "bankruptcy_value": "110",
      "maintenance_margin": "0.5375",
      "liquidation_price": "38834.04",
      "unrealized_pnl": "0",
      "settlement_price": "0",
      "entry_nonce": 0,
      "exit_nonce": 0,
      "entry_sequence": 1,
      "fee_filled": "0",
      "fee_settled": "0"
    }
  ],
  "id": 123
}

Description: Retrieves all open trading orders for the authenticated account, showing unfilled and partially filled positions.

Use Cases:

HTTP Method

POST

RPC Method

open_orders

Message Parameters

Params Data_Type Required Values
N/A null No No parameters required

Response Fields

Field Data_Type Description
id integer Internal order ID
uuid string Unique order identifier
account_id string Account public key associated with the order
position_type string Position direction ("LONG" or "SHORT")
order_status string Current order status ("FILLED", "PENDING", "CANCELLED")
order_type string Order type ("MARKET", "LIMIT")
entryprice string Entry price for the position (2 decimal places)
execution_price string Actual execution price (2 decimal places)
positionsize string Position size in base currency (2 decimal places)
leverage string Leverage multiplier (2 decimal places)
initial_margin string Initial margin requirement (2 decimal places)
available_margin string Available margin for the position (2 decimal places)
timestamp string Order creation timestamp (ISO 8601 format)
bankruptcy_price string Price at which position becomes bankrupt (2 decimal places)
bankruptcy_value string Value at bankruptcy price (2 decimal places)
maintenance_margin string Maintenance margin requirement (4 decimal places)
liquidation_price string Price at which position gets liquidated (2 decimal places)
unrealized_pnl string Current unrealized profit/loss (2 decimal places)
settlement_price string Settlement price if order is settled (2 decimal places)
entry_nonce integer Entry transaction nonce
exit_nonce integer Exit transaction nonce
entry_sequence integer Entry sequence number
fee_filled string Fee paid when order was filled (4 decimal places)
fee_settled string Fee paid when order was settled (4 decimal places)

Order History By Id

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "order_history",
  id: 123,
  params: {
    limit: 10,
    offset: 0,
    from: "2024-01-01T00:00:00Z",
    to: "2024-12-31T23:59:59Z",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "id": 50,
      "uuid": "7c9a959b-2ae2-461b-b199-125e1cb5c9c6",
      "account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
      "position_type": "LONG",
      "order_status": "FILLED",
      "order_type": "MARKET",
      "entryprice": "42508.71",
      "execution_price": "30000",
      "positionsize": "4250871",
      "leverage": "10",
      "initial_margin": "10",
      "available_margin": "10",
      "timestamp": "2024-01-31T11:14:45.575359Z",
      "bankruptcy_price": "38644.28",
      "bankruptcy_value": "110",
      "maintenance_margin": "0.5375",
      "liquidation_price": "38834.04",
      "unrealized_pnl": "0",
      "settlement_price": "0",
      "entry_nonce": 0,
      "exit_nonce": 0,
      "entry_sequence": 1,
      "fee_filled": "0",
      "fee_settled": "0"
    }
  ],
  "id": 123
}

Description: Retrieves historical trading order data for the authenticated account with filtering and pagination options.

Use Cases:

HTTP Method

POST

RPC Method

order_history

Message Parameters

Params Data_Type Required Values
limit integer No Number of records to return (default: 50)
offset integer No Number of records to skip (default: 0)
from datetime No Start date for filtering
to datetime No End date for filtering

Response Fields

Field Data_Type Description
id integer Internal order ID
uuid string Unique order identifier
account_id string Account public key associated with the order
position_type string Position direction ("LONG" or "SHORT")
order_status string Current order status ("FILLED", "PENDING", "CANCELLED", "SETTLED")
order_type string Order type ("MARKET", "LIMIT")
entryprice string Entry price for the position (2 decimal places)
execution_price string Actual execution price (2 decimal places)
positionsize string Position size in base currency (2 decimal places)
leverage string Leverage multiplier (2 decimal places)
initial_margin string Initial margin requirement (2 decimal places)
available_margin string Available margin for the position (2 decimal places)
timestamp string Order creation timestamp (ISO 8601 format)
bankruptcy_price string Price at which position becomes bankrupt (2 decimal places)
bankruptcy_value string Value at bankruptcy price (2 decimal places)
maintenance_margin string Maintenance margin requirement (4 decimal places)
liquidation_price string Price at which position gets liquidated (2 decimal places)
unrealized_pnl string Current unrealized profit/loss (2 decimal places)
settlement_price string Settlement price if order is settled (2 decimal places)
entry_nonce integer Entry transaction nonce
exit_nonce integer Exit transaction nonce
entry_sequence integer Entry sequence number
fee_filled string Fee paid when order was filled (4 decimal places)
fee_settled string Fee paid when order was settled (4 decimal places)

Order History By Client

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "order_history",
  id: 123,
  params: {
    limit: 5,
    offset: 10,
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "id": 45,
      "uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
      "account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
      "position_type": "LONG",
      "order_status": "SETTLED",
      "order_type": "MARKET",
      "entryprice": "42508.71",
      "execution_price": "43000",
      "positionsize": "4250871",
      "leverage": "10",
      "initial_margin": "10",
      "available_margin": "10",
      "timestamp": "2024-01-30T11:14:45.575359Z",
      "bankruptcy_price": "38644.28",
      "bankruptcy_value": "110",
      "maintenance_margin": "0.5375",
      "liquidation_price": "38834.04",
      "unrealized_pnl": "0",
      "settlement_price": "43000",
      "entry_nonce": 0,
      "exit_nonce": 0,
      "entry_sequence": 1,
      "fee_filled": "12.75",
      "fee_settled": "19.13"
    }
  ],
  "id": 123
}

Description: Retrieves paginated order history for client-specific analysis and reporting with customizable filtering options.

Use Cases:

HTTP Method

POST

RPC Method

order_history

Message Parameters

Params Data_Type Required Values
limit integer No Number of records to return
offset integer No Pagination offset

Response Fields

Field Data_Type Description
id integer Internal order ID
uuid string Unique order identifier
account_id string Account public key associated with the order
position_type string Position direction ("LONG" or "SHORT")
order_status string Current order status ("FILLED", "PENDING", "CANCELLED", "SETTLED")
order_type string Order type ("MARKET", "LIMIT")
entryprice string Entry price for the position (2 decimal places)
execution_price string Actual execution price (2 decimal places)
positionsize string Position size in base currency (2 decimal places)
leverage string Leverage multiplier (2 decimal places)
initial_margin string Initial margin requirement (2 decimal places)
available_margin string Available margin for the position (2 decimal places)
timestamp string Order creation timestamp (ISO 8601 format)
bankruptcy_price string Price at which position becomes bankrupt (2 decimal places)
bankruptcy_value string Value at bankruptcy price (2 decimal places)
maintenance_margin string Maintenance margin requirement (4 decimal places)
liquidation_price string Price at which position gets liquidated (2 decimal places)
unrealized_pnl string Current unrealized profit/loss (2 decimal places)
settlement_price string Settlement price if order is settled (2 decimal places)
entry_nonce integer Entry transaction nonce
exit_nonce integer Exit transaction nonce
entry_sequence integer Entry sequence number
fee_filled string Fee paid when order was filled (4 decimal places)
fee_settled string Fee paid when order was settled (4 decimal places)

Trade Volume

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "trade_volume",
  id: 123,
  params: {
    from: "2024-01-01T00:00:00Z",
    to: "2024-12-31T23:59:59Z",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "total_usd_volume": "1234567.89",
    "total_btc_volume": "28.456789",
    "order_count": 42,
    "average_order_size": "29418.28"
  },
  "id": 123
}

Description: Calculates total trading volume statistics for the authenticated account over specified time periods.

Use Cases:

HTTP Method

POST

RPC Method

trade_volume

Message Parameters

Params Data_Type Required Values
from datetime No Start date for volume calculation
to datetime No End date for volume calculation

Response Fields

Field Data_Type Description
total_usd_volume string Total trading volume in USD (2 decimal places)
total_btc_volume string Total trading volume in BTC (6 decimal places)
order_count integer Total number of orders executed
average_order_size string Average order size in USD (2 decimal places)

Get Funding Payment

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "get_funding_payment",
  id: 123,
  params: {
    id: "a4340b19-cd90-411e-adfc-a3695109d7a2",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "order_id": "a4340b19-cd90-411e-adfc-a3695109d7a2",
    "funding_payment": "12.45",
    "funding_rate": "0.001",
    "position_size": "1000000",
    "timestamp": "2024-02-28T12:00:00Z"
  },
  "id": 123
}

Description: Retrieves funding payment information for a specific order, showing the cost or income from holding perpetual positions.

Use Cases:

HTTP Method

POST

RPC Method

get_funding_payment

Message Parameters

Params Data_Type Required Values
id string Yes Order UUID for funding payment lookup

Response Fields

Field Data_Type Description
order_id string Order UUID that was queried
funding_payment string Funding payment amount (2 decimal places)
funding_rate string Applied funding rate (4 decimal places)
position_size string Position size for calculation (2 decimal places)
timestamp string Timestamp of funding payment (ISO 8601 format)

Last Order Detail

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "last_order_detail",
  id: 123,
  params: {},
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 42,
    "uuid": "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
    "account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
    "position_type": "LONG",
    "order_status": "FILLED",
    "order_type": "MARKET",
    "entryprice": "42508.71",
    "execution_price": "30000",
    "positionsize": "4250871",
    "leverage": "10",
    "initial_margin": "10",
    "available_margin": "10",
    "timestamp": "2024-01-31T11:14:45.575359Z",
    "bankruptcy_price": "38644.28",
    "bankruptcy_value": "110",
    "maintenance_margin": "0.5375",
    "liquidation_price": "38834.04",
    "unrealized_pnl": "0",
    "settlement_price": "0",
    "entry_nonce": 0,
    "exit_nonce": 0,
    "entry_sequence": 1,
    "fee_filled": "0",
    "fee_settled": "0"
  },
  "id": 123
}

Description: Retrieves details of the most recent trading order for the authenticated account.

Use Cases:

HTTP Method

POST

RPC Method

last_order_detail

Message Parameters

Params Data_Type Required Values
N/A null No No parameters required

Response Fields

Field Data_Type Description
id integer Internal order ID
uuid string Unique order identifier
account_id string Account public key associated with the order
position_type string Position direction ("LONG" or "SHORT")
order_status string Current order status ("FILLED", "PENDING", "CANCELLED")
order_type string Order type ("MARKET", "LIMIT")
entryprice string Entry price for the position (2 decimal places)
execution_price string Actual execution price (2 decimal places)
positionsize string Position size in base currency (2 decimal places)
leverage string Leverage multiplier (2 decimal places)
initial_margin string Initial margin requirement (2 decimal places)
available_margin string Available margin for the position (2 decimal places)
timestamp string Order creation timestamp (ISO 8601 format)
bankruptcy_price string Price at which position becomes bankrupt (2 decimal places)
bankruptcy_value string Value at bankruptcy price (2 decimal places)
maintenance_margin string Maintenance margin requirement (4 decimal places)
liquidation_price string Price at which position gets liquidated (2 decimal places)
unrealized_pnl string Current unrealized profit/loss (2 decimal places)
settlement_price string Settlement price if order is settled (2 decimal places)
entry_nonce integer Entry transaction nonce
exit_nonce integer Exit transaction nonce
entry_sequence integer Entry sequence number
fee_filled string Fee paid when order was filled (4 decimal places)
fee_settled string Fee paid when order was settled (4 decimal places)

Lend Pool Info

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "lend_pool_info",
  id: 123,
  params: {},
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "sequence": 43566,
    "nonce": 8,
    "total_pool_share": "2300000",
    "total_locked_value": "20048615383",
    "pending_orders": 5,
    "aggregate_log_sequence": 123423,
    "last_snapshot_id": 8765
  },
  "id": 123
}

Description: Retrieves comprehensive information about the lending pool including total value locked, pool shares, and operational metrics.

Use Cases:

HTTP Method

POST

RPC Method

lend_pool_info

Message Parameters

Params Data_Type Required Values
N/A null No No parameters required

Response Fields

Field Data_Type Description
sequence integer Current pool sequence number
nonce integer Pool operation nonce
total_pool_share string Total pool shares issued (2 decimal places)
total_locked_value string Total value locked in the pool (2 decimal places)
pending_orders integer Number of pending lending orders
aggregate_log_sequence integer Aggregate log sequence for pool operations
last_snapshot_id integer ID of the last pool snapshot

Trade Order Info

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "trader_order_info",
  id: 123,
  params: {
    id: "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 50,
    "uuid": "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
    "account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
    "position_type": "LONG",
    "order_status": "FILLED",
    "order_type": "MARKET",
    "entryprice": "42508.71",
    "execution_price": "30000",
    "positionsize": "4250871",
    "leverage": "10",
    "initial_margin": "10",
    "available_margin": "10",
    "timestamp": "2024-01-31T11:14:45.575359Z",
    "bankruptcy_price": "38644.28",
    "bankruptcy_value": "110",
    "maintenance_margin": "0.5375",
    "liquidation_price": "38834.04",
    "unrealized_pnl": "0",
    "settlement_price": "0",
    "entry_nonce": 0,
    "exit_nonce": 0,
    "entry_sequence": 1,
    "fee_filled": "0",
    "fee_settled": "0"
  },
  "id": 123
}

Description: Retrieves detailed information for a specific trading order by its unique identifier.

Use Cases:

HTTP Method

POST

RPC Method

trader_order_info

Message Parameters

Params Data_Type Required Values
id string Yes Order UUID for the specific trader order

Response Fields

Field Data_Type Description
id integer Internal order ID
uuid string Unique order identifier
account_id string Account public key associated with the order
position_type string Position direction ("LONG" or "SHORT")
order_status string Current order status ("FILLED", "PENDING", "CANCELLED")
order_type string Order type ("MARKET", "LIMIT")
entryprice string Entry price for the position (2 decimal places)
execution_price string Actual execution price (2 decimal places)
positionsize string Position size in base currency (2 decimal places)
leverage string Leverage multiplier (2 decimal places)
initial_margin string Initial margin requirement (2 decimal places)
available_margin string Available margin for the position (2 decimal places)
timestamp string Order creation timestamp (ISO 8601 format)
bankruptcy_price string Price at which position becomes bankrupt (2 decimal places)
bankruptcy_value string Value at bankruptcy price (2 decimal places)
maintenance_margin string Maintenance margin requirement (4 decimal places)
liquidation_price string Price at which position gets liquidated (2 decimal places)
unrealized_pnl string Current unrealized profit/loss (2 decimal places)
settlement_price string Settlement price if order is settled (2 decimal places)
entry_nonce integer Entry transaction nonce
exit_nonce integer Exit transaction nonce
entry_sequence integer Entry sequence number
fee_filled string Fee paid when order was filled (4 decimal places)
fee_settled string Fee paid when order was settled (4 decimal places)

Lend Order Info

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "lend_order_info",
  id: 123,
  params: {
    id: "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "id": 25,
    "uuid": "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
    "account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
    "balance": "153620",
    "order_status": "FILLED",
    "order_type": "LEND",
    "entry_nonce": 0,
    "exit_nonce": 0,
    "deposit": "153620",
    "new_lend_state_amount": "153620",
    "timestamp": "2024-02-28T04:59:44.020048Z",
    "npoolshare": "100",
    "nwithdraw": "0",
    "payment": "0",
    "tlv0": "0",
    "tps0": "0",
    "tlv1": "0",
    "tps1": "0",
    "tlv2": "0",
    "tps2": "0",
    "tlv3": "0",
    "tps3": "0",
    "entry_sequence": 10
  },
  "id": 123
}

Description: Retrieves detailed information for a specific lending order including pool share calculations and yield metrics.

Use Cases:

HTTP Method

POST

RPC Method

lend_order_info

Message Parameters

Params Data_Type Required Values
id string Yes Order UUID for the specific lend order

Response Fields

Field Data_Type Description
id integer Internal lend order ID
uuid string Unique lend order identifier
account_id string Account public key associated with the lend order
balance string Current balance in the lend order (2 decimal places)
order_status string Current order status ("FILLED", "PENDING", "CANCELLED")
order_type string Order type ("LEND")
entry_nonce integer Entry transaction nonce
exit_nonce integer Exit transaction nonce
deposit string Initial deposit amount (2 decimal places)
new_lend_state_amount string Updated lend state amount (2 decimal places)
timestamp string Order creation timestamp (ISO 8601 format)
npoolshare string Number of pool shares (2 decimal places)
nwithdraw string Withdrawal amount (2 decimal places)
payment string Payment amount (2 decimal places)
tlv0 string Total locked value tier 0 (2 decimal places)
tps0 string Total pool shares tier 0 (2 decimal places)
tlv1 string Total locked value tier 1 (2 decimal places)
tps1 string Total pool shares tier 1 (2 decimal places)
tlv2 string Total locked value tier 2 (2 decimal places)
tps2 string Total pool shares tier 2 (2 decimal places)
tlv3 string Total locked value tier 3 (2 decimal places)
tps3 string Total pool shares tier 3 (2 decimal places)
entry_sequence integer Entry sequence number

Unrealized PnL Pubkey

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "unrealized_pnl",
  id: 123,
  params: {
    pubkey:
      "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "total_unrealized_pnl": "245.67",
    "position_count": 3,
    "total_position_value": "15000.00"
  },
  "id": 123
}

Description: Calculates unrealized profit and loss for all open positions associated with a specific public key.

Use Cases:

HTTP Method

POST

RPC Method

unrealized_pnl

Message Parameters

Params Data_Type Required Values
pubkey string No Account public key for PnL calculation

Response Fields

Field Data_Type Description
total_unrealized_pnl string Total unrealized PnL across all positions (2 decimal places)
position_count integer Number of open positions
total_position_value string Total value of all positions (2 decimal places)

Unrealized PnL OrderId

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "unrealized_pnl",
  id: 123,
  params: {
    order_id: "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
  },
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "unrealized_pnl": "125.34",
    "order_id": "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
    "current_price": "43500.00",
    "entry_price": "42508.71",
    "position_size": "4250871"
  },
  "id": 123
}

Description: Calculates unrealized profit and loss for a specific order by its unique identifier.

Use Cases:

HTTP Method

POST

RPC Method

unrealized_pnl

Message Parameters

Params Data_Type Required Values
order_id string No Specific order UUID for PnL calculation

Response Fields

Field Data_Type Description
unrealized_pnl string Unrealized PnL for the specific order (2 decimal places)
order_id string Order UUID that was queried
current_price string Current market price (2 decimal places)
entry_price string Order entry price (2 decimal places)
position_size string Position size (2 decimal places)

Unrealized PnL All

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());

var raw = JSON.stringify({
  jsonrpc: "2.0",
  method: "unrealized_pnl",
  id: 123,
  params: {},
});

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("API_ENDPOINT/api/private", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "result": {
    "total_unrealized_pnl": "342.15",
    "position_count": 5,
    "total_position_value": "25000.00",
    "account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b"
  },
  "id": 123
}

Description: Calculates total unrealized profit and loss for all open positions in the authenticated account.

Use Cases:

HTTP Method

POST

RPC Method

unrealized_pnl

Message Parameters

Params Data_Type Required Values
N/A null No No parameters required (returns all positions)

Response Fields

Field Data_Type Description
total_unrealized_pnl string Total unrealized PnL across all positions (2 decimal places)
position_count integer Number of open positions
total_position_value string Total value of all positions (2 decimal places)
account_id string Account public key associated with the positions

WebSocket API

Endpoint URL

WEBSOCKET_ENDPOINT_PRODUCTION = wss://relayer.twilight.rest/ws

WEBSOCKET_ENDPOINT_STAGING = wss://app.twilight.rest/ws


Subscribe Live Price Data

Description: Establishes a real-time WebSocket connection to receive live BTC-USD price updates as they occur in the market.

Use Cases:

const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});

const subscriptionPayload = {
  jsonrpc: "2.0",
  method: "subscribe_live_price_data",
  id: 123,
  params: null,
};

socket.onopen = () => {
  socket.send(JSON.stringify(subscriptionPayload));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received live price update:", data);
};

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "method": "s_live_price_data",
  "params": {
    "subscription": 8760936935364034,
    "result": [57198.36, "2024-02-28T05:03:14.455674475Z"]
  }
}

Description

Subscribe Live Price Data

Parameters

Parameter Data Type Required Description
jsonrpc string Yes JSON-RPC protocol version (must be "2.0")
method string Yes The method name to invoke
id number Yes Unique identifier for the request
params null Yes No additional parameters required

Method

subscribe_live_price_data

Response Fields

Field Data_Type Description
subscription integer Unique subscription ID for this WebSocket connection
result array Array containing [price, timestamp]
result[0] number Current BTC-USD price (2 decimal places)
result[1] string Price timestamp (ISO 8601 format)

Subscribe Order Book

Description: Provides real-time updates of the order book changes, showing bid and ask orders as they are placed, modified, or filled.

Use Cases:

const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});

const subscriptionPayload = {
  jsonrpc: "2.0",
  method: "subscribe_order_book",
  id: 123,
  params: null,
};

socket.onopen = () => {
  socket.send(JSON.stringify(subscriptionPayload));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received live order book update:", data);
};

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "method": "s_order_book",
  "params": {
    "subscription": 7957441702917313,
    "result": {
      "bid": {
        "id": "",
        "positionsize": 4250871.0,
        "price": 42508.71
      }
    }
  }
}

Description

Subscribe Order Book

Parameters

Parameter Data Type Required Description
jsonrpc string Yes JSON-RPC protocol version (must be "2.0")
method string Yes The method name to invoke
id number Yes Unique identifier for the request
params null Yes No additional parameters required

Method

subscribe_order_book

Response Fields

Field Data_Type Description
subscription integer Unique subscription ID for this WebSocket connection
result object Order book update data
bid object Bid (buy) order information (when present)
ask object Ask (sell) order information (when present)
id string Order ID (may be empty)
positionsize number Order size (2 decimal places)
price number Order price (2 decimal places)

Subscribe Candle Data

Description: Streams real-time candlestick data updates for specified time intervals, providing OHLCV data as new candles form.

Use Cases:

const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});

const subscriptionPayload = {
  jsonrpc: "2.0",
  method: "subscribe_candle_data",
  id: 123,
  params: { interval: "ONE_HOUR" },
};

socket.onopen = () => {
  socket.send(JSON.stringify(subscriptionPayload));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received live candle data update:", data);
};

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "method": "s_candle_data",
  "params": {
    "subscription": 7957441702917313,
    "result": [
      {
        "btc_volume": "0",
        "close": "57207.50",
        "end": "2024-02-28T04:59:44.020048Z",
        "high": "57271.44",
        "low": "57174.00",
        "open": "57215.20",
        "resolution": "1 hour",
        "start": "2024-02-28T04:54:46.242852Z",
        "trades": 1,
        "usd_volume": "0"
      }
    ]
  }
}

Description

Subscribe Candle Data

Parameters

Parameter Data Type Required Description
jsonrpc string Yes JSON-RPC protocol version (must be "2.0")
method string Yes The method name to invoke
id number Yes Unique identifier for the request
params object Yes Must include interval field with values: ONE_MINUTE, FIVE_MINUTE, FIFTEEN_MINUTE, THIRTY_MINUTE, ONE_HOUR, FOUR_HOUR, EIGHT_HOUR, TWELVE_HOUR, ONE_DAY, ONE_DAY_CHANGE

Method

subscribe_candle_data

Response Fields

Field Data_Type Description
subscription integer Unique subscription ID for this WebSocket connection
result array Array of candle data objects
btc_volume string BTC trading volume for the candle period (6 decimal places)
close string Closing price for the candle (2 decimal places)
end string End timestamp of the candle period (ISO 8601)
high string Highest price during the candle period (2 decimal places)
low string Lowest price during the candle period (2 decimal places)
open string Opening price for the candle (2 decimal places)
resolution string Time interval resolution (e.g., "1 hour", "1 day")
start string Start timestamp of the candle period (ISO 8601)
trades integer Number of trades executed during the candle period
usd_volume string USD trading volume for the candle period (2 decimal places)

Subscribe Recent Trades

Description: Streams real-time trade execution data, showing completed trades as they happen on the Relayer-matchbook.

Use Cases:

const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});

const subscriptionPayload = {
  jsonrpc: "2.0",
  method: "subscribe_recent_trades",
  id: 123,
  params: null,
};

socket.onopen = () => {
  socket.send(JSON.stringify(subscriptionPayload));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received live recent trades update:", data);
};

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "method": "s_recent_trades",
  "params": {
    "subscription": 5213914976941873,
    "result": {
      "order_id": "a2369fcf-489b-4ddf-85f6-78ec076401d0",
      "side": "SHORT",
      "price": 51959.0,
      "positionsize": 7981941580.0,
      "timestamp": "2024-02-28T05:00:00.025776783+00:00"
    }
  }
}

Description

Subscribe Recent Trades

Parameters

Parameter Data Type Required Description
jsonrpc string Yes JSON-RPC protocol version (must be "2.0")
method string Yes The method name to invoke
id number Yes Unique identifier for the request
params null Yes No additional parameters required

Method

subscribe_recent_trades

Response Fields

Field Data_Type Description
subscription integer Unique subscription ID for this WebSocket connection
result object Recent trade data
order_id string Unique identifier for the executed trade
side string Trade direction ("LONG" or "SHORT")
price number Execution price of the trade (2 decimal places)
positionsize number Size of the executed trade (2 decimal places)
timestamp string Trade execution timestamp (ISO 8601 format)

Subscribe Heartbeat

Description: Establishes a heartbeat connection to monitor WebSocket connection health and ensure real-time connectivity.

Use Cases:

const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});

const subscriptionPayload = {
  jsonrpc: "2.0",
  method: "subscribe_heartbeat",
  id: 123,
  params: null,
};

socket.onopen = () => {
  socket.send(JSON.stringify(subscriptionPayload));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received live recent trades update:", data);
};

The result from the above endpoint looks like this:

{
  "jsonrpc": "2.0",
  "method": "s_heartbeat",
  "params": {
    "subscription": 8669657463617608,
    "result": "BEAT"
  }
}

Description

Subscribe Heartbeat

Parameters

Parameter Data Type Required Description
jsonrpc string Yes JSON-RPC protocol version (must be "2.0")
method string Yes The method name to invoke
id number Yes Unique identifier for the request
params null Yes No additional parameters required

Method

subscribe_heartbeat

Response Fields

Field Data_Type Description
subscription integer Unique subscription ID for this WebSocket connection
result string Heartbeat status message (always "BEAT")

Unsubscribing from a WebSocket Stream

Description: Terminates active WebSocket subscriptions to stop receiving real-time updates and manage connection resources.

Use Cases:

To stop receiving updates, send an unsubscribe_* request with the subscription ID you received when you subscribed:

// Assume you stored the subscription id from the earlier response
const subId = 7957441702917313; // example

const unsubscribePayload = {
  jsonrpc: "2.0",
  method: "unsubscribe_order_book", // change accordingly
  id: 456,
  params: [subId],
};

socket.send(JSON.stringify(unsubscribePayload));

Unsubscribe Parameters

Parameter Data Type Required Description
jsonrpc string Yes JSON-RPC protocol version (must be "2.0")
method string Yes The unsubscribe method name
id number Yes Unique identifier for the request
params array Yes Array containing the subscription ID to cancel

Available unsubscribe methods:

Method Description
unsubscribe_live_price_data Stop receiving live price updates
unsubscribe_order_book Stop receiving order book updates
unsubscribe_candle_data Stop receiving candle data updates
unsubscribe_recent_trades Stop receiving recent trades updates
unsubscribe_heartbeat Stop receiving heartbeat messages

Twilight Indexer API

Overview

The Twilight Indexer API is a read-only HTTP service that exposes address-level aggregates and event lists derived from indexed Twilight protocol activity.

This API is intended for: - analytics and attribution systems (e.g. affiliate and rewards platforms) - dashboards and explorers - backend services that require a simplified, query-friendly view of protocol activity

Note This is an off-chain indexer API backed by indexed chain data. For authoritative protocol module REST endpoints and schemas, refer to the Twilight LCD Swagger UI: https://lcd.twilight.org.

Base URL

Production
https://indexer.twilight.org/api/

Local development
http://localhost:3030/api/

Authentication

No authentication is required.

Conventions

Table of Contents

  1. Health
  2. Decode Transaction
  3. Transaction Count
  4. Funding Transfers
  5. Exchange Withdrawal
  6. Exchange Deposit
  7. BTC Deposit
  8. BTC Withdrawal
  9. QQ Account Mapping
  10. Address Summary

Health

Health Check

Description
Verifies that the Indexer API service is running.

HTTP Method
GET

Path
/health

Example

curl -X GET "https://indexer.twilight.org/api/health"

Response (200)

The result from the above endpoint looks like this:

{
  "status": "healthy",
  "service": "twilight-indexer-api"
}

Decode Transaction

Decode Transaction

Description
Decodes a transaction from its bytecode representation and returns a structured JSON representation.

HTTP Method
POST

Path
/decode-transaction

Request Body

Field Type Required Description
tx_byte_code string Yes Hex-encoded transaction bytecode (may include 0x prefix)

Example

curl -X POST "https://indexer.twilight.org/api/decode-transaction" \
  -H "Content-Type: application/json" \
  -d '{"tx_byte_code":"0x123abc..."}'

Response (200)

The result from the above endpoint looks like this:

{
  "success": true,
  "tx_type": "transaction",
  "data": {}
}

Transaction Count

Get Transaction Count

Description
Returns the total number of transactions associated with a Twilight address.

HTTP Method
GET

Path
/transactions/{t_address}

Path Parameters

Parameter Type Required Description
t_address string Yes Twilight address

Example

curl -X GET "https://indexer.twilight.org/api/transactions/twilight1..."

Response (200)

The result from the above endpoint looks like this:

{
  "success": true,
  "t_address": "twilight1...",
  "transaction_count": 42
}

Funding Transfers

Funding Transfers

Description
Returns sats funds moved between accounts for a given t_address.

HTTP Method
GET

Path
/funding/{t_address}

Path Parameters

Parameter Type Required Description
t_address string Yes Twilight address

Response Fields

Field Type Description
funds_moved[] array List of funding-to-funding transfers
funds_moved[].amount integer Amount in sats
funds_moved[].denom string Denomination (expected sats)
funds_moved[].block integer Block height

Example


curl -X GET "https://indexer.twilight.org/api/funding/twilight1..."

Response (200)

Status: 200 OK

The result from the above endpoint looks like this:

{
  "success": true,
  "t_address": "twilight1abc123...",
  "funds_moved": [
    {
      "amount": 100000,
      "denom": "sats",
      "block": 12345
    },
    {
      "amount": 50000,
      "denom": "sats",
      "block": 12350
    }
  ]
}

Exchange Withdrawal

Trading → Funding (Dark Burn)

Description
Returns trading-to-funding movement for a t_address (dark sats burned).

HTTP Method
GET

Path
/exchange-withdrawal/{t_address}

Path Parameters

Parameter Type Required Description
t_address string Yes Twilight address

Response Fields

Field Type Description
dark_burned_sats[] array List of burn events
dark_burned_sats[].q_address string QuisQuis account
dark_burned_sats[].amount integer Amount in sats
dark_burned_sats[].block integer Block height

Example

curl -X GET "https://indexer.twilight.org/api/exchange-withdrawal/twilight1..."

Response (200)

The result from the above endpoint looks like this:

{
  "success": true,
  "t_address": "twilight1...",
  "dark_burned_sats": [
    {
      "q_address": "qq1...",
      "amount": 1000,
      "block": 12345
    }
  ]
}

Exchange Deposit

Funding → Trading (Dark Mint)

Description
Returns funding-to-trading movement for a t_address (dark sats minted).

HTTP Method
GET

Path
/exchange-deposit/{t_address}

Path Parameters

Parameter Type Required Description
t_address string Yes Twilight address

Response Fields

Field Type Description
dark_minted_sats[] array List of mint events
dark_minted_sats[].q_address string QuisQuis account
dark_minted_sats[].amount integer Amount in sats
dark_minted_sats[].block integer Block height
curl -X GET "https://indexer.twilight.org/api/exchange-deposit/twilight1..."

Response (200)

The result from the above endpoint looks like this:

{
  "success": true,
  "t_address": "twilight1...",
  "dark_minted_sats": [
    {
      "q_address": "qq1...",
      "amount": 1000,
      "block": 12345
    }
  ]
}

BTC Deposit

BTC → Twilight (Lit Mint)

Description
Returns BTC bridge deposits recorded for a t_address (lit sats minted).

HTTP Method
GET

Path
/btc-deposit/{t_address}

Path Parameters

Parameter Type Required Description
t_address string Yes Twilight address

Response Fields

Field Type Description
lit_minted_sats[] array List of mint events
lit_minted_sats[].amount integer Amount in sats
lit_minted_sats[].block integer Block height

Example

curl -X GET "https://indexer.twilight.org/api/btc-deposit/twilight1..."

Response (200)

The result from the above endpoint looks like this:

{
  "success": true,
  "t_address": "twilight1...",
  "lit_minted_sats": [
    {
      "amount": 1000,
      "block": 12345
    }
  ]
}

BTC Withdrawal

Twilight → BTC (Lit Burn)

Description
Returns BTC bridge withdrawals recorded for a t_address (lit sats burned).

HTTP Method
GET

Path
/btc-withdrawal/{t_address}

Path Parameters

Parameter Type Required Description
t_address string Yes Twilight address

Response Fields

Field Type Description
lit_burned_sats[] array List of burn events
lit_burned_sats[].amount integer Amount in sats
lit_burned_sats[].block integer Block height

Example

curl -X GET "https://indexer.twilight.org/api/btc-withdrawal/twilight1..."

Response (200)

The result from the above endpoint looks like this:

{
  "success": true,
  "t_address": "twilight1...",
  "lit_burned_sats": [
    {
      "amount": 1000,
      "block": 12345
    }
  ]
}

QQ Account Mapping

Get QQ Account(s)

Description
Returns QuisQuis account(s) mapped to a Twilight address.

HTTP Method
GET

Path
/qq-account/{t_address}

Path Parameters

Parameter Type Required Description
t_address string Yes Twilight address

Response Fields

Field Type Description
q_addresses[] array List of qq account mappings
q_addresses[].qq_account string QuisQuis account
q_addresses[].block integer Block height

Example

curl -X GET "https://indexer.twilight.org/api/qq-account/twilight1..."

Response (200)

The result from the above endpoint looks like this:

{
  "success": true,
  "t_address": "twilight1...",
  "q_addresses": [
    {
      "qq_account": "qq1...",
      "block": 12345
    }
  ]
}

Address Summary

Get All Address Data

Description
Convenience endpoint returning the aggregated payload across all core address metrics.

HTTP Method
GET

Path
/address/{t_address}/all

Path Parameters

Parameter Type Required Description
t_address string Yes Twilight address

Response Fields

Field Type Description
transaction_count integer Total transaction count
funds_moved[] array Funding transfers
dark_burned_sats[] array Exchange withdrawals (dark burn)
dark_minted_sats[] array Exchange deposits (dark mint)
lit_minted_sats[] array BTC deposits (lit mint)
lit_burned_sats[] array BTC withdrawals (lit burn)

Example

curl -X GET "https://indexer.twilight.org/api/address/twilight1.../all"

Response (200)

The result from the above endpoint looks like this:

{
  "success": true,
  "t_address": "twilight1...",
  "transaction_count": 42,
  "funds_moved": [],
  "dark_burned_sats": [],
  "dark_minted_sats": [],
  "lit_minted_sats": [],
  "lit_burned_sats": []
}

HTTP Status Codes

Code Meaning
200 Success
400 Invalid request
500 Server or database error

Glossary

Term Description
t_address Twilight blockchain address
qq_account / q_address QuisQuis privacy-layer account identifier
sats Satoshis (integer BTC base unit)
Lit minted / burned BTC bridge in/out of Twilight
Dark minted / burned Funding ↔ trading movement