Filament API
This is an in-depth guide to onboarding market makers, focusing on how orders are processed and signed.
We will explain how to use the provided code, break down key concepts such as signature generation, and guide you through the modules used (e.g., nanoid, ethers).
Our platform interacts with the order book API to facilitate trading using buy and sell orders based on price changes.
Dependencies
nanoid: Generates unique, secure IDs used for each order.
ethers.js (version 5.7.2): A library that provides utilities for interacting with Ethereum, particularly useful for signing messages (orders in our case).
Key Concepts and Workflow
1. Price Change Orders
Market makers often need to update their orders based on price changes. The processOrders function automates this by creating and sending orders to the platform with unique identifiers and signatures.
import { nanoid } from "nanoid";
import { handleOrderSignature } from "./utils";
export NEXT_API_URL=https://orderbook.filament.finance/sei;
nanoid: This package is used to create a unique identifier for each order. Each generated ID is lowercase to maintain consistency.handleOrderSignature: This utility function is used to sign the order ID using the provided private key.
2. Signature Generation: handleOrderSignature
handleOrderSignatureThe function handleOrderSignature is critical for ensuring the authenticity of each order by creating a cryptographic signature.
Explanation:
orderId: The unique order ID generated bynanoid.signature: The private key used to sign the order (passed assigningKeyinprocessOrders).The function uses
ethers.jsto sign the message, ensuring that only the owner of the private key can create valid orders.
Purpose of Signature:
Signatures verify the identity of the market maker submitting the order. When an order is signed with the private key, the platform can trust the authenticity of the request, making it difficult for malicious actors to forge orders.
3. Function: processOrders
processOrdersThe processOrders function handles the creation of orders and prepares them to be sent to the API.
Explanation of Parameters:
price: Price to place ordersisBuy: A boolean value indicating whether the order is a buy (true) or a sell (false).asset: The asset or token being traded (e.g., SOL, BTC).account: The wallet address of the market maker, which will be used for the order.signingKey: The private key used to sign the order for verification purposes.
Workflow:
For each price change, it generates a unique order ID using
nanoid().The order ID is signed using the
handleOrderSignaturefunction.An order payload is created with information like the asset being traded, order size, leverage, and limit price.
The payload can be sent to the API for order execution.
4. Sending the Order
Once the payload is created, it can be sent to the platformβs API at the endpoint provided in the configuration. The API will process the order and execute it according to the details provided (e.g., size, limit price, etc.).
NEXT_API_URL: This is the base URL for the order book API, which will receive the payload containing the order details.
Exchange URL
Limit Order Payload:
Market Order Payload
Cancel Order
Add Collateral
Remove Collateral
Update Take Profit On Position
Update Stop Loss on Position
Update Take Profit And Stop Loss on Position
GET Endpoints
Get All Traded Assets:
Relevant Info:
Current mark Price
Current Spot Price
Index Token Address for Asset
Response:
GET Calls for Orders, Positions And Market Stats
Please find the below Postman Documentation of GET endpoints, to get following info:
Open Orders
{{baseUrl}}/v1/orders/open-orders/paginated/account/:account?token=&side=&page=0&size=10
This end-point provides details on all open orders placed by the user.
It is paginated endpoint.
Inputs:
account: Account address need to be passed in lower case (Mandatory)
Optional arguments to filter out futher:
token: Asset Eg: BTC
side: BUY/SELL
Output:
Paginated response of user open orders:
Datapoints include:
orderId: Unique Order id of the order.
openTime: order open time
account: user account
side: BUY/SELL
token: asset on which position is created
triggerPrice: price at which order will be triggered.
typeOfOrder:
Limit
Market
TakeProfit
StopLoss
size: Size of order in USDC.
orderValue: Number of tokens.
collateral: Used collateral for this open order.
decreaseOrder: true if order a decrease order
Note: Order can be of two types,
Normal orders to increase or create positon.
Orders to reduce position are categorized as decrease orders.
isTakeProfit -> true is order is a Take Profit order, otherwise false
isStopLoss -> true is order is a Stop Loss order, otherwise false
decreaseOrder -> Provides current liquidation price of user position, it keep on updating with moving market price.
Eg:
Closed Orders
{{baseUrl}}/v1/orders/closed-orders/paginated/account/:account?token=&side=&page=0&size=10
This end-point provides details on all closed orders by the user.
It is paginated endpoint.
Inputs:
account: Account address need to be passed in lower case (Mandatory)
Optional arguments to filter out futher:
token: Asset Eg: BTC
side: BUY/SELL
Output:
Paginated response of user open orders:
Datapoints include:
orderId: Unique Order id of the order.
openTime: order open time
closedTime: Give last update on this order
account: user account
side: BUY/SELL
token: asset on which position is created
triggerPrice: price at which order will be triggered.
typeOfOrder:
Limit
Market
TakeProfit
StopLoss
size: Size of order in USDC.
orderValue: Number of tokens.
orderStatus:
OPEN
MATCHED
CANCELLED
FAILED
collateral: Used collateral for this order.
decreaseOrder: true if order a decrease order
Note: Order can be of two types,
Normal orders to increase or create positon.
Orders to reduce position are categorized as decrease orders.
isTakeProfit -> true is order is a Take Profit order, otherwise false
isStopLoss -> true is order is a Stop Loss order, otherwise false
decreaseOrder -> Provides current liquidation price of user position, it keep on updating with moving market price.
Eg:
JSON
Note: There can be multiple enteries for an orderId.
Eg: Lets say for orderId: "edfd8saq8b8ajwzlakdza"
Order opened at time: 30/09/2024 - 11:56:47, for size: 400 USDC
It Matched for size $200, then an entry will be present with status matched and size $200.
Then if this order is cancelled, then another entry will be present of size $200 with status CANCELLED
Positons (Open Positions - Trades)
URL: {{baseUrl}}/v1/positions/trades/paginated/:account?page=0&size=10
This end-point provides details on all open positions of the user.
Inputs:
account: Account address need to be passed in lower case.
Output:
Paginated response of user positions:
Datapoints include:
openTime: Position open time
account: user account
side: BUY/SELL
token: asset on which position is created
entryPrice: average price of your position.
markPrice: current mark price, which is basically the best Ask.
size: Size of position in USDC, it keep on updating with market price movement.
quantity: Number of tokens (remains constant unless position is increased or decreased)
Collateral: Amount locked in USDC
Fees: Borrowing fees + Trading fees + Funding fees
realizedPnL: This is actually unrealized PnL value. which is calculated basd on formula.
BUY -> (markPrice - averagePrice) x quantity
SELL -> (averagePrice - markPrice) x quantity
takeProfit -> Return take profit price if set for position, otherwise null.
stopLoss -> Return stop loss price if set for position, otherwise null.
Liquidation Price -> Provides current liquidation price of user position, it keep on updating with moving market price.
leverage β size / collateral
Eg:
Trade History
URL: {{baseUrl}}/v1/positions/tradeHistory/paginated/:account?page=0&size=10
This end-point provides all matched trades, it gives insight on every order match.
Inputs:
account: Account address need to be passed in lower case.
Output:
Paginated response of user positions:
Datapoints include:
tradeTime: Time when trade occurrred.
account: user account
side: BUY/SELL
token: asset on which position is created
price: price at which order was matched and trade was executed.
size: Size of position in USDC.
tradeValue: Number of tokens
Collateral: Amount locked in USDC
Fees: Borrowing fees + Trading fees + Funding fees charged
closedPnL: Realized PnL
orderType ->
OpenLong
OpenShort
CloseLong
CloseShort
LiquidationCloseLong
LiquidationCloseShort
associatedOrderId: Order Id associated with this trade.
Eg:
Get trade history with associated Order Id.
URL: {{baseUrl}}/v1/positions/tradeHistory/paginated/:account?page=0&size=10&associatedOrderId=
Inputs:
account: Account address need to be passed in lower case.
associatedOrderId (Optional parameter): Order Id, for which necessary trades are required to be found.
Output:
Example
Account Balance
URL: {{baseUrl}}/v1/accountData/balance/:account
This endpoint give insight on available deposited balance in USDC. Basically amount of collateral free to use. Input: account: User address Output: USDC value Eg: 343.917502459535209000
URL: {{baseUrl}}/v1/positions/balance/:account
It gives insight on USDC locked with the position, adding or subtracting unrealized PnL and subtracting fees.
Input:
account: user account
Output:
Gives you list of objects, each object corresponds to position of every asset.
token -> Asset info
amount -> collateral locked in position + open orders for this asset + unrealized PnL (can be positive or negative)
value β Number of BTC tokens (locked in position + tokens that will be obtained on fulfilling open orders)
Eg:
Account PnL and Volume
Latest status on orders based on order Id
POST call on URL: {{baseUrl}}/v1/orders/latest-status
BODY: List of order ids 1.
Response: 1.
Pre-requisite
Bearer Token need to be passed as the method of authentication to fetch data from the following endpoints.
How to fetch bearer token is explained above.
Web Socket Connections
API_BASE_URL = https://orderbook.filament.finance/sei/
Order Book State:
To get Order Book State, we can use the following end points:
Get Index Token, from βGet All Traded Assets endpointβ for each traded asset. For eg: for BTC, indexToken = β0x152b9d0fdc40c096757f570a51e494bd4b943e50β
complete URL =
${API_BASE_URL}api/order-book/orderbook-websocket;To connect with websockets, we need to create a initial connection, then connect to /topic/orderBookState:
It will return following JSON
Live Feed On Assets:
To get live feed on state, we can use the following end points:
complete URL =
${API_BASE_URL}api/order-book/orderbook-websocket;Get Index Token, from βGet All Traded Assets endpointβ for each traded asset. For eg: for BTC, indexToken = β0x152b9d0fdc40c096757f570a51e494bd4b943e50β
To connect with web sockets, we need to create a initial connection, then connect to /topic/livefeed:
It will return following JSON
Native WebSocket Connections
Native WebSocket connections provide a more granular approach to interacting with WebSocket servers without relying on higher-level libraries like SockJS or STOMP clients. Below is an example of connecting to the Filament Finance Order Book WebSocket server using Python.
WebSocket Connection Workflow
Establish a WebSocket Connection
Connect to the WebSocket endpoint using the
websocket.WebSocketApplibrary.Define callback functions to handle
on_open,on_message,on_close, andon_errorevents.
Send STOMP Frames
Connect Frame: Establishes the STOMP connection by sending necessary headers.
Subscribe Frame: Subscribes to the desired topic, such as
/topic/orderBookState.Send Frame: Sends initialization messages with the required payload (e.g.,
indexToken).
Receive and Process Messages
Handle incoming messages via the
on_messagecallback to process data in real-time.
Threaded Connection
Run the WebSocket client in a separate thread to maintain a persistent connection while allowing other processes to run concurrently.
OrderBook State:
BASE_URL = wss://orderbook.filament.finance/sei/api/order-book/book-websocket
Example Code
Order Updates:
BASE_URL = wss://orderbook.filament.finance/sei/api/order-websocket
account β Wallet address need to passed in lower case Eg: 0xb02a810c5bb22b093ed52e3d6adb45c8519d68e7
Mandatory Parameters:
account
Optional Parameters:
token
side
Payload required to be passed:
Example Code
Sample Response, on order updates:
How to Place Close Orders for Open Positions
Using the response from the trades endpoint, you can determine the necessary details (quantity, entryPrice, and side) for each position and decide the price at which they want to close the position, either for profit or loss. Below is a step-by-step guide:
Step 1: Fetch Open Positions
Endpoint:
https://orderbook.filament.finance/sei/api/v1/positions/trades/paginated/{ACCOUNT}?page={page}&size={size}Data Retrieved:
Each position includes fields like:
Side (
BUYorSELL)Quantity (e.g.,
0.000139)Entry Price (e.g.,
98269.916666)Collateral and other metrics.
Example, for account:
Use these fields:
quantity: Total amount of the token to close.entryPrice: Reference price to determine profit/loss.side: Indicates whether the position isBUYorSELL.
Step 2: Place Close Order
Endpoint:
https://orderbook.filament.finance/sei/filament/api/v1/exchangePayload Construction:
Construct the payload using the provided
quantity,closePrice(user-defined), andside.reduceOnlyflag should be true for closed orders.size=quantityxentryPriceisBuyfalse: If position was short
true: If position was long
Payload Example: For a
SELLposition:Parameters Explained:
isBuy:falsefor closing aSELLposition;truefor closing aBUYposition.size: Equal to thequantityfrom the position.reduceOnly: Ensures the order reduces the position.limitPrice: User-specified close price.
Send the Request:
Use
POSTto send the constructed payload to the endpoint.
Step 3: Confirmation
The response from the order placement endpoint will indicate whether the close order was successfully placed.
Summary
Fetch open positions using the trades endpoint.
Extract
quantity,entryPrice, andsidefrom the response.Define a close price β Which will decide whether position will be closed in profit or loss.
Construct a reduce-only order payload:
Use
isBuybased on the position side (BUYorSELL).Set
reduceOnlytotrue.Specify the
limitPrice.
Place the close order via the orderbook endpoint.
Last updated