Introduction
Welcome to Injective Protocol's documentation!
Here you can find a comprehensive overview of our protocol, as well as tutorials, guides and general resources for developers and API traders.
If you would like to ask any questions or be a part of our community, please join our Discord Group or Telegram Group. We have a dedicated channel in our Discord group for questions related to the API.
Clients
Python Client
Dependencies
Ubuntu
sudo apt install python3.X-dev autoconf automake build-essential libffi-dev libtool pkg-config
Fedora
sudo dnf install python3-devel autoconf automake gcc gcc-c++ libffi-devel libtool make pkgconfig
macOS
brew install autoconf automake libtool
Installation
Install injective-py from PyPI using pip
.
pip install injective-py
Reference
Golang Client
1. Create your own client repo and go.mod file
go mod init foo
2. Import SDK into go.mod
module foo
go 1.18
require ( github.com/InjectiveLabs/sdk-go v1.39.4 )
Consult the sdk-go repository to find the latest release and replace the version in your go.mod file. Version v1.39.4 is only an example and must be replaced with the newest release
3. Download the package
Download the package using go mod download
go mod download github.com/InjectiveLabs/sdk-go
Reference
Typescript Client
Installation
Install the @injectivelabs/sdk-ts
npm package using yarn
yarn add @injectivelabs/sdk-ts
Reference
Overview
Injective is a DeFi focused layer-1 blockchain built for the next generation of decentralized derivatives exchange. The Injective Chain is a Tendermint-based IBC-compatible blockchain which supports a decentralized orderbook-based DEX protocol and a trustless ERC-20 token bridge to the Ethereum blockchain.
It is the first decentralized exchange focused layer-1 blockchain for decentralized perpetual swaps, futures, and spot trading that unlocks the full potential of decentralized derivatives and borderless DeFi. Every component of the protocol has been built to be fully trustless, censorship-resistant, publicly verifiable, and front-running resistant.
By providing the unrestricted and unprecedented ability to express diverse views in the decentralized financial markets, we are striving to empower individuals with the ability to more efficiently allocate capital in our society.
Architecture Overview
Injective enables traders to create and trade on arbitrary spot and derivative markets. The entire process includes on-chain limit orderbook management, on-chain trade execution, on-chain order matching, on-chain transaction settlement, and on-chain trading incentive distribution through the logic codified by the Injective Chain's exchange module.
Architecturally there are two main services that traders should concern themselves with:
- The Injective Chain node (the Chain API)
- The Injective Exchange API
The trading lifecycle is as follows:
- First, traders cryptographically sign a transaction containing one or more order messages (e.g.
MsgBatchCreateDerivativeLimitOrders
,MsgCreateSpotMarketOrder
,MsgCancelDerivativeLimitOrder
, etc. ). - Then the transaction is broadcasted to an Injective Chain node.
- The transaction is then added to the mempool and becomes included in a block. More details on this process can be found here.
- The handler for each respective message is run. During handler execution, order cancel and liquidation messages are processed immediately, whereas order creation messages are added to a queue.
- At the end of the block, the batch auction process for order matching begins.
- First, the queued market orders are executed against the resting orderbook (which does NOT include the new orders from the current block) and are cleared at a uniform clearing price.
- Second, the queued limit orders are matched against each other and the resting orderbook to result in an uncrossed orderbook. Limit orders created in that block are cleared at a uniform clearing price while resting limit orders created in previous blocks are cleared at an equal or better price than their limit order price.
- The funds are settled accordingly, with positions being created for derivative trades and assets being swapped for spot trades.
- Events containing the trade and settlement information are emitted by the Chain.
- The Injective Exchange API backend indexes the events and pushes updates to all subscribed traders.
Key Differences To CEX
- All information is public which includes things like untriggered Stop/Take orders or pending orders in the mempool.
- The data stored on-chain is minimal for performance reasons and reflects only the current state, relayers provide additional historical data as well as a user interface for traders through the Injective Exchange API backend.
- Usually a DEX has front-running issues, but those are mitigated at Injective through fast block times and FBA.
- The order of execution is different. Any new exchange action is a new transaction and is not executed immediately. Instead, it is added to a queue (mempool) and executed once the block is committed. At the time of the block commit, all included transactions happen more or less instantly. Firstly, code that is inside the handler is executed in the transaction sequence which is decided by the miner. This is not a problem since the sequence does not affect matching prices due to FBA and thus fairness is guaranteed.
To summarize the sequence of state changes on the Injective Chain:
- Mempool: A queue of pending transactions.
- BeginBlocker: Code that is executed at the beginning of every block. We use it for certain maintenance tasks (details can be found in the exchange module documentation).
- Handler: Code that is executed when a transaction is included in a block.
- EndBlocker: Code that is executed at the end of every block. We use it to match orders, calculate funds changes and update the positions.
Comparison to CEX
When you submit an order to Injective Chain,
Centralized Exchange (CEX) | Decentralized Exchange (DEX) |
---|---|
Exchange Gateway | Injective Chain Handler |
Exchange Matching Engine | Injective Chain EndBlocker |
Exchange Trade Report | Injective Chain EndBlocker |
Co-location | Injective Node (Decentralized Validators) |
Frequent Batch Auction (FBA)
The goal is to further prevent any Front-Running in a decentralized setting. Most DEX's suffer from this as all information is public and traders can collude with miners or pay high gas fees enabling them to front-run any trades. We mitigate this by fast block times combined with a Frequent Batch Auction:
In any given block:
- Calculate one uniform clearing price for all market orders and execute them. For an example for the market order matching in FBA fashion, look here.
- Limit orders are combined with the resting orderbook and orders are matched as long as there is still negative spread. The limit orders are all matched at one uniform clearing price. For an example for the limit order matching in FBA fashion, look here.
Trading Fees and Gas
If you are a trader on existing centralized exchanges, you will be familiar with the concept of trading fees. Traders are charged a fee for each successful trade. However, for a DEX, there are additional gas costs that must be paid to the network. And luckily, the gas fee from trading on Injective is very minimal.
- If you are a trader using a DEX UI, you don't need to worry about the gas costs, because the relayer will pay them for you. But in return you will be paying the trading fee in full.
- If you are using the API, then you will need to pay the gas costs.
- The gas costs are currently very small. 20K transactions will cost about 1 INJ.
- You can set the recipient_fee to any of your own wallet addresses since you are in essence your own relayer saving you about 40% of all fees.
Mark Price Margin Requirement
Quantity = 2 BTC, InitialMarginRatio = 0.05
MarkPrice = $45,000, EntryPrice = $43,000
Margin ≥ 2 * 0.05 * $45,000 = $4,500
MarginLong ≥ max(2 * (0.05 * $45,000 - ($45,000 - $43,000)), $4,500)
MarginLong ≥ max($500, $4,500) = $4,500
MarginShort ≥ max(2 * (0.05 * $45,000 - ($43,000 - $45,000)), $4,500)
MarginShort ≥ max($8,500, $4,500) = $8,500
So in this case if the trader wanted to create a short position with
an entry price which essentially starts at a loss of $2,000 as
unrealized PNL, he would need to post at a minimum $8,500 as margin,
rather than the usual required $4,500.
You might be familiar with margin requirements on Centralized Exchanges. When creating a new position, it must fulfill the following requirement:
Margin >= InitialMarginRatio * Quantity * EntryPrice
For example in a market with maximally 20x leverage, your initial margin must be at least 0.05 of the order's notional (entryPrice * quantity
). On Injective additionally the margin must also fulfill the following mark price requirement:
Margin >= Quantity * (InitialMarginRatio * MarkPrice - PNL)
where PNL
is the expected profit and loss of the position if it was closed at the MarkPrice.
Liquidations
Long Position:
Quantity = 1 BTC, MaintenanceMarginRatio = 0.05
EntryPrice = $50,000, Margin = $5,000
Now the MarkPrice drops down to $47,300
which is below the liquidation price of $47,500.
The position is auto-closed via reduce-only order:
Sell order:
Quantity = 1 BTC, Price = $0, Margin = $0
Assuming it gets matched with a clearing price of 47,100:
Liquidation Payout = Position Margin + PNL = $5,000 - $2,900 = $2,100
Liquidator Profit = $2,100 * 0.5 = $1,050
Insurance Fund Profit = $2,100 * 0.5 = $1,050
When your position falls below the maintenance margin ratio, the position can and likely will be liquidated by anyone running the liquidator bot. You will loose your entire position and all funds remaining in the position. What happens on-chain is that automatically a reduce-only market order of the same size as the position is created. The market order will have a worst price defined as Infinity or 0, implying it will be matched at whatever prices are available in the order book.
One key difference is that the payout from executing the reduce-only market order will not go towards the position owner. Instead, half of the remaining funds are transferred to the liquidator bot and the other half is transferred to the insurance fund.
If the payout in the position was negative, i.e., the position's negative PNL was greater than its margin, then the insurance fund will cover the missing funds.
Also note that liquidations are executed immediately in a block before any other order matching occurs.
Fee Discounts
Fee discounts are enabled by looking at the past trailing 30 day window. So long as you meet both conditions for a tier (past fees paid AND staked amount), you will receive the respective discounts.
- Note that there is a caching mechanism in place which can take up to one day to before being updated with a new tier.
- Negative maker fee markets are not eligible for discounts.
- If the fee discount proposal was passed less than 30 days ago, the fee paid requirement is ignored so we don't unfairly penalize people who onboard immediately.
Funding Rate
The hourly funding rate on perpetual markets determines the percentage that traders on one side have to pay to the other side each hour. If the rate is positive, longs are paying shorts. If the rate is negative shorts are paying longs. The further trade prices within that hour deviated from the mark price, the higher the funding rate will be up to a maximum of 0.0625% (1.5% per day).
Closing a Position
Suppose you have an open position:
- Direction = Long
- Margin = $5,000
- EntryPrice = $50,000
- Quantity = 0.5 BTC
You create a new vanilla order for
- Direction = Sell
- Margin = $10,000
- Price = $35,000
- Quantity = 0.75 BTC
which is getting fully matched. First, the position is fully closed:
- OrderMarginUsedForClosing = OrderMargin * CloseQuantity / OrderQuantity
- OrderMarginUsedForClosing = $10,000 * 0.5 / 0.75 = $6,667
The proportional closing order margin is then used for the payout:
- Payout = PNL + PositionMargin + OrderMarginUsedForClosing
- Payout = ($35,000-$50,000) * 0.5 + $5,000 + $6,667 = $4,167
And a new position is opened in the opposite direction:
- Direction = Short
- Margin = $3,333
- Price = $35,000
- Quantity = 0.25 BTC
There are two ways to close a position:
Closing via Reduce-Only Order
When you close a position vis a reduce-only order, no additional margin is used from the order. All reduce-only orders have a margin of zero. In addition, reduce-only orders are only used to close positions, not to open new ones.
Closing via Vanilla Order
You can also close a position via vanilla orders. When a sell vanilla order is getting matched while you have an open Long position, the position will be closed at the price of the sell order. Depending on the size of the order and position, the position may be either
- partially closed
- fully closed
- or fully closed with subsequent opening of a new position in the opposite direction.
Note that how the margin inside the order is used depends on which of the three scenarios you are in. If you close a position via vanilla order, the margin is only used to cover PNL payouts, not to go into the position. If the order subsequently opens a new position in the opposite direction (scenario 3), the remaining proportional margin will go towards the new position.
Trading Rewards
Assume you have a trading rewards campaign with 100 INJ as rewards:
Reward Tokens: 100 INJ
Trader Reward Points = 100
Total Reward Points = 1,000
Trader Rewards = Trader Reward Points / Total Reward Points * Reward Tokens
Trader Rewards = 100 / 1,000 * 100 INJ = 10 INJ
During a given campaign, the exchange will record each trader's cumulative trading reward points obtained from trading fees (with boosts applied, if applicable) from all eligible markets. At the end of each campaign each trader will receive a pro-rata percentage of the trading rewards pool based off their trading rewards points from that campaign epoch. Those rewards will be automatically deposited into the trader's respective wallets, it's not necessary to manually withdraw them.
Reduce-Only Order Precedence
Imagine a trader has a the following position:
- LONG:
1 BTC
with EntryPrice of $59,000
And the following SELL orders:
Buy Price | Quantity | Order Type |
---|---|---|
$66,500 | 0.2 BTC | Vanilla |
$65,500 | 0.2 BTC | Reduce-only |
$64,500 | 0.3 BTC | Vanilla |
$63,500 | 0.1 BTC | Reduce-only |
This has some implications when placing new orders.
Upon placing a reduce-only order
- If any reduce-only orders would be invalid after executing all of the trader's other limit sell orders that have better prices in the same direction.
In our example, consider a new reduce-only order of 0.4 BTC
at $64,600
.
Sell Price | Quantity | Order Type |
---|---|---|
$66,500 | 0.2 BTC | Vanilla |
$65,500 | 0.2 BTC | Reduce-only |
$64,600 | 0.4 BTC | Reduce-only |
$64,500 | 0.3 BTC | Vanilla |
$63,500 | 0.1 BTC | Reduce-only |
This is perfectly valid and no further action is required. But what if the order was for 0.5 BTC
instead?
Sell Price | Quantity | Order Type |
---|---|---|
$66,500 | 0.2 BTC | Vanilla |
$65,500 | 0.2 BTC | Reduce-only |
$64,600 | 0.5 BTC | Reduce-only |
$64,500 | 0.3 BTC | Vanilla |
$63,500 | 0.1 BTC | Reduce-only |
If the orders are getting matched, once the last reduce-only of $65,500 with 0.2 BTC order is reached, the position will have been reduced to 1 BTC - 0.1 BTC - 0.3 BTC - 0.5 BTC = 0.1 BTC
. A reduce-only order of 0.2 BTC after that will thus be invalid.
To prevent that, we simply reject the creation of the new 0.5 BTC reduce-only order. In other words any reduce-only order can never be larger than the expected position's quantity at the time of matching.
Upon placing a vanilla limit order
- If any reduce-only limit orders would be invalidated when all the orders up to and including the new vanilla limit order were filled.
In our example, consider a new vanilla order of 0.4 BTC
at $64,600
.
Sell Price | Quantity | Order Type |
---|---|---|
$66,500 | 0.2 BTC | Vanilla |
$65,500 | 0.2 BTC | Reduce-only |
$64,600 | 0.4 BTC | Vanilla |
$64,500 | 0.3 BTC | Vanilla |
$63,500 | 0.1 BTC | Reduce-only |
Again this perfectly valid and no further action is required. But what if the order was for 0.5 BTC
instead?
Sell Price | Quantity | Order Type |
---|---|---|
$66,500 | 0.2 BTC | Vanilla |
$65,500 | 0.2 BTC | Reduce-only |
$64,600 | 0.5 BTC | Vanilla |
$64,500 | 0.3 BTC | Vanilla |
$63,500 | 0.1 BTC | Reduce-only |
If the orders are getting matched, once the last reduce-only of $65,500 with 0.2 BTC order is reached, the position will have been reduced to 1 BTC - 0.1 BTC - 0.3 BTC - 0.5 BTC = 0.1 BTC
. A reduce-only order of 0.2 BTC after that will thus be invalid.
To prevent that, we simply cancel the existing 0.2 BTC reduce-only order. In other words new vanilla limit orders can invalidate and auto-cancel existing reduce-only limit orders.
Examples
Adding a Spot Market Buy Order
Maker Fee = 0.1%
Taker Fee = 0.2%
Market Buy Order:
Quantity = 1 ETH
Worst Price = 3,000 USDT
→ The account's available balance is decremented by 3,000 USDT + Taker Fee = 3,006 USDT
.
Upon matching with a resting sell order with price of 2,000 USDT
the new account balances are calculated as:
Trading Fee = 1 * 2,000 * 0.002 = 4 USDT
Credit Amount = 1 ETH
Debit Amount = 1 * 2,000 + 4 = 2,004 USDT
Clearing Refund = 3,006 - 2,004 = 1,002 USDT
Adding a Spot Market Sell Order
Maker Fee = 0.1%
Taker Fee = 0.2%
Market Sell Order:
Quantity = 1 ETH
Worst Price = 1,500 USDT
→ The account's available balance is decremented by 1 ETH
.
Upon matching the with a resting sell order with price of 2,000 USDT
new account balances are calculated as:
Trading Fee = 1 * 2,000 * 0.002 = 4 USDT
Debit Amount = 1 ETH
Credit Amount = 1 * 2,000 - 4 = 1,996 USDT
Clearing Refund = 0
Adding a Spot Limit Buy Order
Maker Fee = 0.1%
Taker Fee = 0.2%
Market Buy Order:
Quantity = 1 ETH
Price = 2,000 USDT
→ The account's available balance is decremented by 2,000 USDT + Taker Fee = 2,004 USDT
.
After creation:
If Unmatched, the order becomes a resting limit order (maker) and we refund the fee difference between maker and taker:
Fee Refund = 1 * 2,000 * (0.002 - 0.001) = 2 USDT
If Matched Immediately: (assuming an FBA clearing price of 1,900 USDT)
Trading Fee = 1 * 1,900 * 0.002 = 3.8 USDT
Credit Amount = 1 ETH
Debit Amount = 1 * 1,900 + 3.8 = 1,903.8 USDT
Clearing Refund = (1 + 0.002) * (2,000 - 1,900) = 100.2 USDT
Unmatched Fee Refund = 0 USDT
If Filled Later By Market Order:
Trading Fee = 1 * 2,000 * 0.001 = 2 USDT
Credit Amount (in base asset) = 1 ETH
Debit Amount (in quote asset) = 1 * 2,000 + 2 = 2,002 USDT
Adding a Spot Limit Sell Order
Maker Fee = 0.1%
Taker Fee = 0.2%
Market Sell Order:
Quantity = 1 ETH
Price = 2,000 USDT
→ The account's available balance is decremented by 1 ETH
.
After creation:
If Unmatched, the order becomes a resting limit order (maker) and we refund the fee difference between maker and taker:
Fee Refund = 0 ETH
If Matched Immediately: (assuming an FBA clearing price of 2,100 USDT)
Trading Fee = 1 * 2,100 * 0.002 = 4.2 USDT
Credit Amount = 1 * 2,100 * (1 - 0.002) = 2,095.8 USDT
Debit Amount = 1 ETH
Clearing Refund = 0 ETH
Fee Refund = 0 USDT
If Filled Later By Market Order:
Credit Amount (in quote asset) = 1 * 2,000 - 2 = 1,998 USDT
Debit Amount (in base asset) = 1 ETH
Trading Fee = 1 * 2,000 * 0.001 = 2 USDT
Derivative Market Order Payouts
The payouts for derivative market orders work the same way as for derivative limit orders with the one difference that they are cancelled if not immediately matched, see spot market and derivative limit orders as reference.
Adding a Derivative Limit Buy Order
Quantity = 1
,Price = 2,000
,Margin = 200
TakerFeeRate = 0.002
MakerFeeRate = 0.001
→ The account's available balance is decremented by Margin + Taker Fee = 200 + 2000*0.002 = 204 USDT
.
After creation:
If Unmatched, the order becomes a resting limit order (maker) and we refund the fee difference between maker and taker for vanilla orders (reduce-only orders don't pay upfront fees):
Fee Refund = Quantity * Price * (TakerFeeRate - MakerFeeRate) = 1 * 2,000 * (0.002 - 0.001) = 2 USDT
AvailableBalance = AvailableBalance + Fee Refund = 0 + 2 = 2
If Matched:
Assuming:
- an FBA clearing price of 1,990 USDT
an existing
SHORT
position:Position Quantity = 0.5 ETH
Position Entry Price = 1,950 USDT
Position Margin = 400 USDT
Would result in:
1. Closing existing position with proportional order margin for closing:
CloseExecutionMargin = ExecutionMargin * CloseQuantity / OrderQuantity = 200 * 0.5 / 1 = 100 USDT
ClosingPayout = PNL + PositionMargin * CloseQuantity / PositionQuantity
PNL = CloseQuantity * (FillPrice - EntryPrice) = 0.5 * (1,990 - 1,950) = 20 USDT
ClosingPayout = 20 + 400 * 0.5 / 0.5 = 420 USDT
2. Opening new position in opposite direction:
a new
LONG
position:Position Quantity = 0.5 ETH
Position Entry Price = 2,000 USDT
Position Margin = 100 USDT
3. Refunding fee difference from order price vs. clearing price:
PriceDelta = Price - ClearingPrice = 2,000 - 1,990 = 10
ClearingFeeRefund = FillQuantity * PriceDelta * TakerFeeRate = 1 * 10 * 0.002 = 0.002 USDT
(in the case of matching a sell order, this would have been a charge, not a refund)
Market Order Matching
Existing Orderbook
Sells | Buys | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
New Orders
- 1x market buy order for 0.2 BTC with worst price 64,360
- 1x market buy order for 0.4 BTC with worst price 66,000
- 1x market sell order for 0.1 BTC with worst price 60,000
- 1x market sell order for 0.2 BTC with worst price 61,000
- 1x market sell order for 0.3 BTC with worst price 69,000
Resulting Orderbook
Sells | Buys | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
Market Buys: Matching the highest priced market buy order first for 0.4 BTC. Now for the second market buy order only 0.1 BTC is left at matchable price, meaning the other 0.1 BTC in the order will be cancelled. Both orders will be matched with the single resting limit order at a price of 64,360 for a total quantity of 0.5 BTC.
Market Sells: Matching the first two market sell orders for at a matching price of (64,210*0.1 + 64,205*0.2) / 0.3 = 64,206.67
for a total quantity of 0.3 BTC. The resting limit orders are both matched at their specified price points of 64,210 and 64,205. Since the last market sell order of 69,000 cannot be fulfilled, it is cancelled.
Limit Order Matching
Existing Orderbook
Sells | Buys | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
New Orders
Sells | Buys | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
Matching Orders
All new orders are incorporated into the existing orderbook. In our case this results in a negative spread:
Sells | Buys | ||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
As long as negative spread exists, orders are matched against each other. The first buy order is fully matched:
Sells | Buys | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
Now the second buy order can still be fully matched:
Sells | Buys | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
This is the end of the matching, since no more negative spread exists (64,220 > 62,210
).
All orders will be matched with a uniform clearing price within the range of the last sell order price and the last buy order price.
- Last sell order price: 64,220
- Last buy order price: 64,360
- 64,220 >= Clearing price >= 64,360
Step 1: Check if clearing price range is out of bounds regarding the resting orderbook mid price.
- Resting orderbook mid price: (64,250+64,210)/2 = 64,230
- Is within range of clearing price ✅ (if not, a clearing price of either last buy or last sell price would be used)
Step 2: Check if clearing price range is out of bounds regarding the mark price.
- Let's assume mark price is 64,300
- Is within range of clearing price ✅ (if not, a clearing price of either last buy or last sell price would be used)
Step 3: Set clearing price = mark price.
Resources
Here you can find a comprehensive overview of the exchange ecosystem on Injective, guides and general resources for developers and API traders.
Explorer
A Web interface that allows you to search for information on the Injective Chain
Faucet
A web-based service that provides free tokens to users on testnet and allows them to experiment on the Injective Chain.
Status
Monitor the uptime of all public services.
Indexer API
The Indexer API is read-only whereas the Chain API is write and also includes a limited set of API requests to read data. The Chain API reads query the blockchain state from the node directly as opposed to the Indexer API which reconstructs state from events emitted by chain.
On a high-level the end-user trading applications and Injective Products use the Indexer API to read data and the Chain API to write data to the blockchain. Even though it’s possible to develop trading applications using the Chain API only, the Indexer API includes more methods, streaming support, gRPC and also allows you to fetch historical data as the Chain API queries the blockchain state which doesn’t include historical records.
- InjectiveAccountsRPC
InjectiveAccountsRPC defines the gRPC API of the Exchange Accounts provider.
SubaccountsList
Get a list of subaccounts for a specific address.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
account_address = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
subacc_list = await client.get_subaccount_list(account_address)
print(subacc_list)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
accountAddress := "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
res, err := exchangeClient.GetSubaccountsList(ctx, accountAddress)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const accountAddress = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const subaccountLists = await exchangeClient.account.fetchSubaccountsList(
accountAddress
);
console.log(protoObjectToJson(subaccountLists));
})();
Parameter | Type | Description | Required |
---|---|---|---|
account_address | String | The Injective Chain address | Yes |
Response Parameters
Response Example:
subaccounts: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
subaccounts: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000001"
{
"subaccounts": [
"0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000001"
]
}
{
"subaccountsList": [
"0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000001"
]
}
Parameter | Type | Description |
---|---|---|
subaccounts | Array |
SubaccountHistory
Get the subaccount's transfer history.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
denom = "inj"
transfer_types = ["withdraw", "deposit"]
skip = 10
limit = 10
subacc_history = await client.get_subaccount_history(
subaccount_id=subaccount,
denom=denom,
transfer_types=transfer_types,
skip=skip,
limit=limit
)
print(subacc_history)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
accountPB "github.com/InjectiveLabs/sdk-go/exchange/accounts_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
denom := "inj"
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
transferTypes := []string{"deposit"}
skip := uint64(0)
limit := int32(10)
req := accountPB.SubaccountHistoryRequest{
Denom: denom,
SubaccountId: subaccountId,
TransferTypes: transferTypes,
Skip: skip,
Limit: limit,
}
res, err := exchangeClient.GetSubaccountHistory(ctx, req)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const subaccountId =
"0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const denom = "inj";
const transferTypes = ["deposit"];
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const subaccountHistory = await exchangeClient.account.fetchSubaccountHistory(
{
subaccountId: subaccountId,
denom: denom,
transferTypes: transferTypes,
pagination: pagination,
});
console.log(protoObjectToJson(subaccountHistory));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
denom | String | Filter by denom | No |
transfer_types | Array | Filter by transfer types | No |
skip | Integer | Skip the last transfers, you can use this to fetch all transfers since the API caps at 100 | No |
limit | Integer | Limit the transfers returned | No |
Response Parameters
Response Example:
transfers {
transfer_type: "deposit"
src_account_address: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
dst_subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
amount {
denom: "inj"
amount: "50000000000000000000"
}
executed_at: 1651492257605
}
transfers {
transfer_type: "deposit"
src_account_address: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
dst_subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
amount {
denom: "inj"
amount: "1000000000000000000"
}
executed_at: 1652453978939
}
{
"transfers": [
{
"transfer_type": "deposit",
"src_account_address": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"dst_subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"amount": {
"denom": "inj",
"amount": "50000000000000000000"
},
"executed_at": 1651492257605
},
{
"transfer_type": "deposit",
"src_account_address": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"dst_subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"amount": {
"denom": "inj",
"amount": "1000000000000000000"
},
"executed_at": 1652453978939
}
]
}
{
"transfersList": [
{
"transferType": "deposit",
"srcSubaccountId": "",
"srcAccountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"dstSubaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"dstAccountAddress": "",
"amount": {
"denom": "inj",
"amount": "50000000000000000000"
},
"executedAt": 1651492257605
},
{
"transferType": "deposit",
"srcSubaccountId": "",
"srcAccountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"dstSubaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"dstAccountAddress": "",
"amount": {
"denom": "inj",
"amount": "1000000000000000000"
},
"executedAt": 1652453978939
},
{
"transferType": "deposit",
"srcSubaccountId": "",
"srcAccountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"dstSubaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"dstAccountAddress": "",
"amount": {
"denom": "inj",
"amount": "1000000000000000000"
},
"executedAt": 1653010969661
}
]
}
Parameter | Type | Description |
---|---|---|
transfers | SubaccountBalanceTransfer | SubaccountBalanceTransfer object |
SubaccountBalanceTransfer
Parameter | Type | Description |
---|---|---|
amount | CosmosCoin | CosmosCoin |
dst_account_address | String | Account address of the receiving side |
executed_at | Integer | Timestamp of the transfer in UNIX millis |
src_subaccount_id | String | Subaccount ID of the sending side |
transfer_type | String | Type of the subaccount balance transfer (Should be one of: [internal external withdraw deposit]) |
CosmosCoin
Parameter | Type | Description |
---|---|---|
amount | String | Coin amount |
denom | String | Coin denominator |
SubaccountBalance
Get the balance of a subaccount for a specific denom.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
denom = "inj"
balance = await client.get_subaccount_balance(
subaccount_id=subaccount_id,
denom=denom
)
print(balance)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
denom := "inj"
res, err := exchangeClient.GetSubaccountBalance(ctx, subaccountId, denom)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const subaccountId =
"0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const denom = "inj";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const subaccountBalance = await exchangeClient.account.fetchSubaccountBalance(
subaccountId,
denom
);
console.log(protoObjectToJson(subaccountBalance));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
denom | String | Filter by denom | Yes |
Response Parameters
Response Example:
balance {
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
account_address: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
denom: "inj"
deposit {
total_balance: "52790000010000000003"
available_balance: "52790000010000000003"
}
}
{
"balance": {
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"account_address": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "inj",
"deposit": {
"total_balance": "53790000010000000003",
"available_balance": "52790000010000000003"
}
}
}
{
"balance": {
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"accountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "inj",
"deposit": {
"totalBalance": "50790000010000000003",
"availableBalance": "50790000010000000003"
}
}
}
Parameter | Type | Description |
---|---|---|
balance | SubaccountBalance | SubaccountBalance object |
SubaccountBalance
Parameter | Type | Description |
---|---|---|
denom | String | Coin denom on the chain |
deposit | SubaccountDeposit | SubaccountDeposit object |
subaccount_id | String | Filter by subaccount ID |
account_address | String | The Injective Chain address |
SubaccountDeposit
Parameter | Type | Description |
---|---|---|
available_balance | String | The available balance for a denom |
total_balance | String | The total balance for a denom |
SubaccountBalancesList
List the subaccount's balances for all denoms.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
subacc_balances_list = await client.get_subaccount_balances_list(subaccount)
print(subacc_balances_list)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
res, err := exchangeClient.GetSubaccountBalancesList(ctx, subaccountId)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const subaccountId = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const subaccountBalancesList = await exchangeClient.account.fetchSubaccountBalancesList(
subaccountId
);
console.log(protoObjectToJson(subaccountBalancesList));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
Response Parameters
Response Example:
balances {
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
account_address: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
denom: "inj"
deposit {
total_balance: "52790000010000000003"
available_balance: "52790000010000000003"
}
}
balances {
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
account_address: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
denom: "ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"
deposit {
total_balance: "1000000"
available_balance: "1000000"
}
}
{
"balances": [
{
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"account_address": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"deposit": {
"total_balance": "200501904612800.13082016560359584",
"available_balance": "200358014975479.130820165603595295"
}
},
{
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"account_address": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "inj",
"deposit": {
"total_balance": "53790000010000000003",
"available_balance": "52790000010000000003"
}
},
{
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"account_address": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9",
"deposit": {
"total_balance": "1000000",
"available_balance": "1000000"
}
}
]
}
{
"balancesList": [
{
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"accountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9",
"deposit": {
"totalBalance": "1000000",
"availableBalance": "990000"
}
},
{
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"accountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"deposit": {
"totalBalance": "200493880101034.695319283887814576",
"availableBalance": "200493854575534.695319283887814031"
}
},
{
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"accountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "inj",
"deposit": {
"totalBalance": "50790000010000000003",
"availableBalance": "50790000010000000003"
}
}
]
}
Parameter | Type | Description |
---|---|---|
balances | SubaccountBalance | SubaccountBalance object |
SubaccountBalance
Parameter | Type | Description |
---|---|---|
account_address | String | The Injective Chain address |
denom | String | Coin denom on the chain |
deposit | SubaccountDeposit | SubaccountDeposit object |
subaccount_id | String | Filter by subaccount ID |
SubaccountDeposit
Parameter | Type | Description |
---|---|---|
available_balance | String | The available balance for a denom |
total_balance | String | The total balance for a denom |
SubaccountOrderSummary
Get the subaccount's orders summary.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
subacc_order_summary = await client.get_subaccount_order_summary(subaccount_id=subaccount)
print(subacc_order_summary)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
accountPB "github.com/InjectiveLabs/sdk-go/exchange/accounts_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
orderDirection := "buy"
req := accountPB.SubaccountOrderSummaryRequest{
MarketId: marketId,
SubaccountId: subaccountId,
OrderDirection: orderDirection,
}
res, err := exchangeClient.GetSubaccountOrderSummary(ctx, req)
if err != nil {
fmt.Println(err)
}
fmt.Println("spot orders:", res.SpotOrdersTotal)
fmt.Println("derivative orders:", res.DerivativeOrdersTotal)
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const subaccountId = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const marketId = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0";
const orderDirection = "buy";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const subaccountOrderSummary = await exchangeClient.account.fetchSubaccountOrderSummary(
{
subaccountId,
marketId,
orderDirection
}
);
console.log(protoObjectToJson(subaccountOrderSummary));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
market_id | String | Filter by market ID | No |
order_direction | String | Filter by the direction of the orders (Should be one of: [buy sell]) | No |
Response Parameters
Response Example:
spot_orders_total: 64
derivative_orders_total: 1
spot orders: 2
derivative orders: 0
{
"spotOrdersTotal": 2,
"derivativeOrdersTotal": 0
}
Parameter | Type | Description |
---|---|---|
derivative_orders_total | Integer | Total count of subaccount's derivative orders in a given market |
spot_orders_total | Integer | Total count of subaccount's spot orders in a given market |
StreamSubaccountBalance
Stream the subaccount's balance for all denoms.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
subaccount = await client.stream_subaccount_balance(subaccount_id)
async for balance in subaccount:
print("Subaccount balance Update:\n")
print(balance)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
stream, err := exchangeClient.StreamSubaccountBalance(ctx, subaccountId)
if err != nil {
panic(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
fmt.Println(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const subaccountId =
"0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.account.streamSubaccountBalance({
subaccountId,
callback: (subaccountBalance) => {
console.log(protoObjectToJson(subaccountBalance));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
Response Parameters
Streaming Response Example:
balance {
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
account_address: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
deposit {
available_balance: "200439115032180.597507632843178205"
}
}
timestamp: 1652786118000
{
"balance": {
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"account_address": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"deposit": {
"total_balance": "200503979400874.28368413692326264",
"available_balance": "200360046875708.283684136923262095"
}
},
"timestamp": 1653037703000
}{
"balance": {
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"account_address": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"deposit": {
"total_balance": "200503560511302.28368413692326264",
"available_balance": "200359627986136.283684136923262095"
}
},
"timestamp": 1653037744000
}
{
"balance": {
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"accountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"deposit": {
"totalBalance": "200493439765890.695319283887814576",
"availableBalance": "200493414240390.695319283887814031"
}
},
"timestamp": 1654234765000
}
{
"balance": {
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"accountAddress": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"deposit": {
"totalBalance": "200493847328858.695319283887814576",
"availableBalance": "200493821803358.695319283887814031"
}
},
"timestamp": 1654234804000
}
Parameter | Type | Description |
---|---|---|
balance | SubaccountBalance | SubaccountBalance object |
timestamp | Integer | Operation timestamp in UNIX millis |
SubaccountBalance
Parameter | Type | Description |
---|---|---|
denom | String | Coin denom on the chain |
deposit | SubaccountDeposit | SubaccountDeposit object |
subaccount_id | String | Filter by subaccount ID |
account_address | String | The Injective Chain address |
SubaccountDeposit
Parameter | Type | Description |
---|---|---|
available_balance | String | The available balance for a denom |
total_balance | String | The total balance for a denom |
OrderStates
Get orders with an order hash, this request will return market orders and limit orders in all states [booked, partial_filled, filled, canceled]. For filled and canceled orders, there is a TTL of 1 day. Should your order be filled or canceled you will still be able to fetch it for 3 minutes.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
spot_order_hashes = ["0xa848395a768ee06af360e2e35bac6f598fdc52e8d0c34a588d32cd9108f3571f", "0x163861fba3d911631e18354a03e7357bc6358cd2042535e8ad11dc6c29f8c558"]
derivative_order_hashes = ["0x962af5e492a2ce4575616dbcf687a063ef9c4b33a047a9fb86794804923337c8"]
orders = await client.get_order_states(spot_order_hashes=spot_order_hashes, derivative_order_hashes=derivative_order_hashes)
print(orders)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
accountPB "github.com/InjectiveLabs/sdk-go/exchange/accounts_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
spotOrderHashes := []string{"0xb7b556d6eab10c4c185a660be44757a8a6715fb16db39708f2f76d9ce5ae8617"}
derivativeOrderHashes := []string{"0x4228f9a56a5bb50de4ceadc64df694c77e7752d58b71a7c557a27ec10e1a094e"}
req := accountPB.OrderStatesRequest{
SpotOrderHashes: spotOrderHashes,
DerivativeOrderHashes: derivativeOrderHashes,
}
res, err := exchangeClient.GetOrderStates(ctx, req)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const spotOrderHashes = ["0xb7b556d6eab10c4c185a660be44757a8a6715fb16db39708f2f76d9ce5ae8617"];
const derivativeOrderHashes = ["0x4228f9a56a5bb50de4ceadc64df694c77e7752d58b71a7c557a27ec10e1a094e"];
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const orderStates = await exchangeClient.account.fetchOrderStates(
{
spotOrderHashes,
derivativeOrderHashes
}
);
console.log(protoObjectToJson(orderStates));
})();
Parameter | Type | Description | Required |
---|---|---|---|
spot_order_hashes | Array | Array with the order hashes you want to fetch in spot markets | No |
derivative_order_hashes | Array | Array with the order hashes you want to fetch in derivative markets | No |
Response Parameters
Response Example:
spot_order_states {
order_hash: "0xa848395a768ee06af360e2e35bac6f598fdc52e8d0c34a588d32cd9108f3571f"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa"
order_type: "limit"
order_side: "buy"
state: "booked"
quantity_filled: "0"
quantity_remaining: "2000000"
created_at: 1652701438661
updated_at: 1652701438661
}
spot_order_states {
order_hash: "0x163861fba3d911631e18354a03e7357bc6358cd2042535e8ad11dc6c29f8c558"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa"
order_type: "limit"
order_side: "buy"
state: "booked"
quantity_filled: "0"
quantity_remaining: "2000000"
created_at: 1652693332688
updated_at: 1652693332688
}
derivative_order_states {
order_hash: "0x962af5e492a2ce4575616dbcf687a063ef9c4b33a047a9fb86794804923337c8"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
order_type: "limit"
order_side: "buy"
state: "booked"
quantity_filled: "0"
quantity_remaining: "1"
created_at: 1652786114544
updated_at: 1652786114544
}
{
"spot_order_states": [
{
"order_hash": "0xb7b556d6eab10c4c185a660be44757a8a6715fb16db39708f2f76d9ce5ae8617",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa",
"order_type": "limit",
"order_side": "buy",
"state": "booked",
"quantity_filled": "0",
"quantity_remaining": "1000000",
"created_at": 1654080262300,
"updated_at": 1654080262300
}
],
"derivative_order_states": [
{
"order_hash": "0x4228f9a56a5bb50de4ceadc64df694c77e7752d58b71a7c557a27ec10e1a094e",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0x1c79dac019f73e4060494ab1b4fcba734350656d6fc4d474f6a238c13c6f9ced",
"order_type": "limit",
"order_side": "buy",
"state": "booked",
"quantity_filled": "0",
"quantity_remaining": "1",
"created_at": 1654235059957,
"updated_at": 1654235059957
}
]
}
{
"spotOrderStatesList": [
{
"orderHash": "0xb7b556d6eab10c4c185a660be44757a8a6715fb16db39708f2f76d9ce5ae8617",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa",
"orderType": "limit",
"orderSide": "buy",
"state": "booked",
"quantityFilled": "0",
"quantityRemaining": "1000000",
"createdAt": 1654080262300,
"updatedAt": 1654080262300
}
],
"derivativeOrderStatesList": [
{
"orderHash": "0x4228f9a56a5bb50de4ceadc64df694c77e7752d58b71a7c557a27ec10e1a094e",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0x1c79dac019f73e4060494ab1b4fcba734350656d6fc4d474f6a238c13c6f9ced",
"orderType": "limit",
"orderSide": "buy",
"state": "booked",
"quantityFilled": "0",
"quantityRemaining": "1",
"createdAt": 1654235059957,
"updatedAt": 1654235059957
}
]
}
Parameter | Type | Description |
---|---|---|
spot_order_states | SpotOrderStates | SpotOrderStates object |
derivative_order_states | DerivativeOrderStates | DerivativeOrderStates object |
SpotOrderStates
Parameter | Type | Description |
---|---|---|
order_hash | String | The order hash |
subaccount_id | String | The subaccount ID that posted the order |
market_id | String | The market ID of the order |
order_type | String | The order type (Should be one of: [limit, market]) |
order_side | String | The order side (Should be one of: [buy, sell]) |
state | String | The order state (Should be one of: [booked, partial_filled, filled, canceled]) |
quantity_filled | String | The quantity that has been filled for your order |
quantity_remaining | String | The quantity that hasn't been filled for your order |
created_at | String | The timestamp of your order when it was first created |
updated_at | String | The timestamp of your order when it was last updated |
DerivativeOrderStates
Parameter | Type | Description |
---|---|---|
order_hash | String | The order hash |
subaccount_id | String | The subaccount ID that posted the order |
market_id | String | The market ID of the order |
order_type | String | The order type (Should be one of: [limit, market]) |
order_side | String | The order side (Should be one of: [buy, sell]) |
state | String | The order state (Should be one of: [booked, partial_filled, filled, canceled]) |
quantity_filled | String | The quantity that has been filled for your order |
quantity_remaining | String | The quantity that hasn't been filled for your order |
created_at | String | The timestamp of your order when it was first created |
updated_at | String | The timestamp of your order when it was last updated |
Portfolio
Get an overview of your portfolio.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
network = Network.testnet()
client = AsyncClient(network, insecure=False)
account_address = "inj10y4mpwgqr4c63m7t8spxhf8rgcy2dz5vt3mvk9"
portfolio = await client.get_portfolio(account_address=account_address)
print(portfolio)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
accountAddress := "inj10y4mpwgqr4c63m7t8spxhf8rgcy2dz5vt3mvk9"
res, err := exchangeClient.GetPortfolio(ctx, accountAddress)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const accountAddress = "inj10y4mpwgqr4c63m7t8spxhf8rgcy2dz5vt3mvk9";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const portfolio = await exchangeClient.account.fetchPortfolio(
accountAddress
);
console.log(protoObjectToJson(portfolio));
})();
Parameter | Type | Description | Required |
---|---|---|---|
account_address | String | The Injective Chain address | Yes |
Response Parameters
Response Example:
portfolio {
portfolio_value: "16951.32520096332191347385"
available_balance: "10127.3078647233442029"
locked_balance: "8193.1269388867038576"
unrealized_pnl: "-1369.10960264672614702615"
subaccounts {
subaccount_id: "0x792bb0b9001d71a8efcb3c026ba4e34608a68a8c000000000000000000000000"
available_balance: "10127.3078647233442029"
locked_balance: "8193.1269388867038576"
unrealized_pnl: "-1369.10960264672614702615"
}
}
{
"portfolio": {
"portfolio_value": "16961.63886335580191347385",
"available_balance": "10127.8309908372442029",
"locked_balance": "8192.6038127728038576",
"unrealized_pnl": "-1358.79594025424614702615",
"subaccounts": [
{
"subaccount_id": "0x792bb0b9001d71a8efcb3c026ba4e34608a68a8c000000000000000000000000",
"available_balance": "10127.8309908372442029",
"locked_balance": "8192.6038127728038576",
"unrealized_pnl": "-1358.79594025424614702615"
}
]
}
}
{
"portfolioValue": "18140.93939739028541677385",
"availableBalance": "10100.5755146800551762",
"lockedBalance": "8190.6761262577118576",
"unrealizedPnl": "-150.31224354748161702615",
"subaccountsList": [
{
"subaccountId": "0x792bb0b9001d71a8efcb3c026ba4e34608a68a8c000000000000000000000000",
"availableBalance": "10100.5755146800551762",
"lockedBalance": "8190.6761262577118576",
"unrealizedPnl": "-150.31224354748161702615"
}
]
}
Parameter | Type | Description |
---|---|---|
portfolio_value | String | The total value of your portfolio including bank balance, subaccounts' balance, unrealized profit & loss as well as margin in open positions |
available_balance | String | The total available balance in the subaccounts |
locked_balance | String | The amount of margin in open orders and positions |
unrealized_pnl | String | The approximate unrealized profit and loss across all positions (based on the mark price) |
subaccount_id | String | Filter balances by subaccount ID |
Rewards
Get the rewards for Trade & Earn, the request will fetch all addresses for the latest epoch (-1) by default.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
account_address = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
epoch = -1
rewards = await client.get_rewards(account_address=account_address, epoch=epoch)
print(rewards)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
accountPB "github.com/InjectiveLabs/sdk-go/exchange/accounts_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
accountAddress := "inj1rwv4zn3jptsqs7l8lpa3uvzhs57y8duemete9e"
epoch := int64(2)
req := accountPB.RewardsRequest{
Epoch: epoch,
AccountAddress: accountAddress,
}
res, err := exchangeClient.GetRewards(ctx, req)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const address = "inj1rwv4zn3jptsqs7l8lpa3uvzhs57y8duemete9e";
const epoch = 2;
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const rewards = await exchangeClient.account.fetchRewards(
{
address: address,
epoch: epoch
}
);
console.log(protoObjectToJson(rewards));
})();
Parameter | Type | Description | Required |
---|---|---|---|
account_address | String | The Injective Chain address | No |
epoch | Integer | The epoch ID | No |
Response Parameters
Response Example:
rewards {
account_address: "inj1uzg3kpezm8ju70qd0twr8eh20zph2jt8dh0p6a"
rewards {
denom: "inj"
amount: "15586502225212"
}
distributed_at: 1652259600148
}
{
"rewards": [
{
"account_address": "inj1rwv4zn3jptsqs7l8lpa3uvzhs57y8duemete9e",
"rewards": [
{
"denom": "inj",
"amount": "755104058929571177652"
}
],
"distributed_at": 1642582800716
}
]
}
{
"rewardsList": [
{
"accountAddress": "inj1rwv4zn3jptsqs7l8lpa3uvzhs57y8duemete9e",
"rewardsList": [
{
"denom": "inj",
"amount": "755104058929571177652"
}
],
"distributedAt": 1642582800716
}
]
}
Parameter | Type | Description |
---|---|---|
account_address | String | The Injective Chain address |
denom | String | The token denom |
amount | String | The amount of rewards distributed |
distributed_at | Integer | Timestamp of the transfer in UNIX millis |
- InjectiveSpotExchangeRPC
InjectiveSpotExchangeRPC defines the gRPC API of the Spot Exchange provider.
Market
Get details of a spot market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe"
market = await client.get_spot_market(market_id=market_id)
print(market)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketId := "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
res, err := exchangeClient.GetSpotMarket(ctx, marketId)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.spot.fetchMarket(marketId);
console.log(protoObjectToJson(market));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
Response Parameters
Response Example:
market {
market_id: "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa"
market_status: "active"
ticker: "ATOM/USDT"
base_denom: "ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"
base_token_meta {
name: "Cosmos"
address: "0x8D983cb9388EaC77af0474fA441C4815500Cb7BB"
symbol: "ATOM"
logo: "https://s2.coinmarketcap.com/static/img/coins/64x64/3794.png"
decimals: 6
updated_at: 1650978921848
}
quote_denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
maker_fee_rate: "0.001"
taker_fee_rate: "0.001"
service_provider_fee: "0.4"
min_price_tick_size: "0.01"
min_quantity_tick_size: "10000"
}
{
"market": {
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"market_status": "active",
"ticker": "INJ/USDT",
"base_denom": "inj",
"base_token_meta": {
"name": "Injective Protocol",
"address": "0xe28b3B32B6c345A34Ff64674606124Dd5Aceca30",
"symbol": "INJ",
"logo": "https://static.alchemyapi.io/images/assets/7226.png",
"decimals": 18,
"updated_at": 1650978921934
},
"quote_denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"maker_fee_rate": "0.001",
"taker_fee_rate": "0.002",
"service_provider_fee": "0.4",
"min_price_tick_size": "0.000000000000001",
"min_quantity_tick_size": "1000000000000000"
}
}
{
"market": {
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"marketStatus": "active",
"ticker": "INJ/USDT",
"baseDenom": "inj",
"baseTokenMeta": {
"name": "Injective Protocol",
"address": "0xe28b3B32B6c345A34Ff64674606124Dd5Aceca30",
"symbol": "INJ",
"logo": "https://static.alchemyapi.io/images/assets/7226.png",
"decimals": 18,
"updatedAt": 1650978921934
},
"quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"makerFeeRate": "0.001",
"takerFeeRate": "0.002",
"serviceProviderFee": "0.4",
"minPriceTickSize": "0.000000000000001",
"minQuantityTickSize": "1000000000000000"
}
}
Parameter | Type | Description |
---|---|---|
market | SpotMarketInfo | SpotMarketInfo object |
SpotMarketInfo
Parameter | Type | Description |
---|---|---|
base_denom | String | Coin denom of the base asset |
market_id | String | SpotMarket ID is keccak265(baseDenom |
market_status | String | The status of the market (Should be one of: [active paused suspended demolished expired]) |
min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity |
quote_token_meta | TokenMeta | TokenMeta object |
service_provider_fee | String | Percentage of the transaction fee shared with the service provider |
base_token_meta | TokenMeta | TokenMeta object |
maker_fee_rate | String | Defines the fee percentage makers pay when trading (in the quote asset) |
min_price_tick_size | String | Defines the minimum required tick size for the order's price |
quote_denom | String | Coin denom of the quote asset |
taker_fee_rate | String | Defines the fee percentage takers pay when trading (in the quote asset) |
ticker | String | A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset |
TokenMeta
Parameter | Type | Description |
---|---|---|
address | String | Token's Ethereum contract address |
decimals | Integer | Token decimals |
logo | String | URL to the logo image |
name | String | Token full name |
symbol | String | Token symbol short name |
updatedAt | Integer | Token metadata fetched timestamp in UNIX millis |
Markets
Get a list of spot markets.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_status = "active"
base_denom = "inj"
quote_denom = "peggy0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08"
market = await client.get_spot_markets(
market_status=market_status,
base_denom=base_denom,
quote_denom=quote_denom
)
print(market)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
spotExchangePB "github.com/InjectiveLabs/sdk-go/exchange/spot_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketStatus := "active"
quoteDenom := "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
req := spotExchangePB.MarketsRequest{
MarketStatus: marketStatus,
QuoteDenom: quoteDenom,
}
res, err := exchangeClient.GetSpotMarkets(ctx, req)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketStatus = "active";
const quoteDenom = "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const markets = await exchangeClient.spot.fetchMarkets({
marketStatus: marketStatus,
quoteDenom: quoteDenom,
})
console.log(protoObjectToJson(markets));
})();
Parameter | Type | Description | Required |
---|---|---|---|
base_denom | String | Filter by the base currency | No |
market_status | String | Filter by market status (Should be one of: [active paused suspended demolished expired]) | No |
quote_denom | String | Filter by the quote currency | No |
Response Parameters
Response Example:
markets {
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
market_status: "active"
ticker: "INJ/USDT"
base_denom: "inj"
base_token_meta {
name: "Injective Protocol"
address: "0xe28b3B32B6c345A34Ff64674606124Dd5Aceca30"
symbol: "INJ"
logo: "https://static.alchemyapi.io/images/assets/7226.png"
decimals: 18
updated_at: 1650978921934
}
quote_denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
maker_fee_rate: "0.001"
taker_fee_rate: "0.002"
service_provider_fee: "0.4"
min_price_tick_size: "0.000000000000001"
min_quantity_tick_size: "1000000000000000"
}
{
"markets": [
{
"market_id": "0x01edfab47f124748dc89998eb33144af734484ba07099014594321729a0ca16b",
"market_status": "active",
"ticker": "AAVE/USDT",
"base_denom": "peggy0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9",
"base_token_meta": {
"name": "Aave",
"address": "0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9",
"symbol": "AAVE",
"logo": "https://static.alchemyapi.io/images/assets/7278.png",
"decimals": 18,
"updated_at": 1650978921846
},
"quote_denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"maker_fee_rate": "0.001",
"taker_fee_rate": "0.002",
"service_provider_fee": "0.4",
"min_price_tick_size": "0.000000000000001",
"min_quantity_tick_size": "1000000000000000"
},
{
"market_id": "0xe8bf0467208c24209c1cf0fd64833fa43eb6e8035869f9d043dbff815ab76d01",
"market_status": "active",
"ticker": "UNI/USDT",
"base_denom": "peggy0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
"base_token_meta": {
"name": "Uniswap",
"address": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
"symbol": "UNI",
"logo": "https://static.alchemyapi.io/images/assets/7083.png",
"decimals": 18,
"updated_at": 1650978922133
},
"quote_denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"maker_fee_rate": "0.001",
"taker_fee_rate": "0.002",
"service_provider_fee": "0.4",
"min_price_tick_size": "0.000000000000001",
"min_quantity_tick_size": "1000000000000000"
}
]
}
{
"marketsList": [
{
"marketId": "0x01edfab47f124748dc89998eb33144af734484ba07099014594321729a0ca16b",
"marketStatus": "active",
"ticker": "AAVE/USDT",
"baseDenom": "peggy0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9",
"baseTokenMeta": {
"name": "Aave",
"address": "0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9",
"symbol": "AAVE",
"logo": "https://static.alchemyapi.io/images/assets/7278.png",
"decimals": 18,
"updatedAt": 1650978921846
},
"quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"makerFeeRate": "0.001",
"takerFeeRate": "0.002",
"serviceProviderFee": "0.4",
"minPriceTickSize": "0.000000000000001",
"minQuantityTickSize": "1000000000000000"
},
{
"marketId": "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa",
"marketStatus": "active",
"ticker": "ATOM/USDT",
"baseDenom": "ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9",
"baseTokenMeta": {
"name": "Cosmos",
"address": "0x8D983cb9388EaC77af0474fA441C4815500Cb7BB",
"symbol": "ATOM",
"logo": "https://s2.coinmarketcap.com/static/img/coins/64x64/3794.png",
"decimals": 6,
"updatedAt": 1650978921848
},
"quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"makerFeeRate": "0.001",
"takerFeeRate": "0.001",
"serviceProviderFee": "0.4",
"minPriceTickSize": "0.01",
"minQuantityTickSize": "10000"
},
{
"marketId": "0xe8bf0467208c24209c1cf0fd64833fa43eb6e8035869f9d043dbff815ab76d01",
"marketStatus": "active",
"ticker": "UNI/USDT",
"baseDenom": "peggy0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
"baseTokenMeta": {
"name": "Uniswap",
"address": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
"symbol": "UNI",
"logo": "https://static.alchemyapi.io/images/assets/7083.png",
"decimals": 18,
"updatedAt": 1650978922133
},
"quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"makerFeeRate": "0.001",
"takerFeeRate": "0.002",
"serviceProviderFee": "0.4",
"minPriceTickSize": "0.000000000000001",
"minQuantityTickSize": "1000000000000000"
}
]
}
Parameter | Type | Description |
---|---|---|
markets | SpotMarketInfo | SpotMarketInfo object |
SpotMarketInfo
Parameter | Type | Description |
---|---|---|
base_denom | String | Coin denom of the base asset |
market_id | String | SpotMarket ID is keccak265(baseDenom |
market_status | String | The status of the market (Should be one of: [active paused suspended demolished expired]) |
min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity |
quote_token_meta | TokenMeta | TokenMeta object |
service_provider_fee | String | Percentage of the transaction fee shared with the service provider |
base_token_meta | TokenMeta | TokenMeta object |
maker_fee_rate | String | Defines the fee percentage makers pay when trading (in the quote asset) |
min_price_tick_size | String | Defines the minimum required tick size for the order's price |
quote_denom | String | Coin denom of the quote asset |
taker_fee_rate | String | Defines the fee percentage takers pay when trading (in the quote asset) |
ticker | String | A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset |
TokenMeta
Parameter | Type | Description |
---|---|---|
address | String | Token's Ethereum contract address |
decimals | Integer | Token decimals |
logo | String | URL to the logo image |
name | String | Token full name |
symbol | String | Token symbol short name |
updatedAt | Integer | Token metadata fetched timestamp in UNIX millis |
StreamMarkets
Stream live updates of spot markets.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
markets = await client.stream_spot_markets()
async for market in markets:
print(market)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketIds := []string{"0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"}
stream, err := exchangeClient.StreamSpotMarket(ctx, marketIds)
if err != nil {
fmt.Println(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
fmt.Println(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";;
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketIds = ["0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"];
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.spot.streamSpotMarket({
marketIds,
callback: (streamSpotMarket) => {
console.log(protoObjectToJson(streamSpotMarket));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Response Parameters
Streaming Response Example:
market: {
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
market_status: "active",
ticker: "INJ/USDT",
base_denom: "inj",
base_token_meta: {
name: "Injective Protocol",
address: "0xe28b3B32B6c345A34Ff64674606124Dd5Aceca30",
symbol: "INJ",
logo: "https://static.alchemyapi.io/images/assets/7226.png",
decimals: 18,
updated_at: 1632535055751
},
quote_denom: "peggy0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08",
quote_token_meta: {
name: "Tether",
address: "0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08",
symbol: "USDT",
logo: "https://static.alchemyapi.io/images/assets/825.png",
decimals: 6,
updated_at: 1632535055759
},
maker_fee_rate: "0.001",
taker_fee_rate: "0.002",
service_provider_fee: "0.4",
min_price_tick_size: "0.000000000000001",
min_quantity_tick_size: "1000000000000000"
},
operation_type: "update",
timestamp: 1632535055790
{
"market": {
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"market_status": "active",
"ticker": "INJ/USDT",
"base_denom": "inj",
"base_token_meta": {
"name": "Injective Protocol",
"address": "0xe28b3B32B6c345A34Ff64674606124Dd5Aceca30",
"symbol": "INJ",
"logo": "https://static.alchemyapi.io/images/assets/7226.png",
"decimals": 18,
"updated_at": 1632535055751
},
"quote_denom": "peggy0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08",
"quote_token_meta": {
"name": "Tether",
"address": "0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updated_at": 1632535055759
},
"maker_fee_rate": "0.001",
"taker_fee_rate": "0.002",
"service_provider_fee": "0.4",
"min_price_tick_size": "0.000000000000001",
"min_quantity_tick_size": "1000000000000000"
},
"operation_type": "update",
"timestamp": 1632535055790
}
{
"market": {
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"marketStatus": "active",
"ticker": "INJ/USDT",
"baseDenom": "inj",
"baseTokenMeta": {
"name": "Injective Protocol",
"address": "0xe28b3B32B6c345A34Ff64674606124Dd5Aceca30",
"symbol": "INJ",
"logo": "https://static.alchemyapi.io/images/assets/7226.png",
"decimals": 18,
"updatedAt": 1632535055751
},
"quoteDenom": "peggy0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08",
"quoteTokenMeta": {
"name": "Tether",
"address": "0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updatedAt": 1632535055759
},
"makerFeeRate": "0.001",
"takerFeeRate": "0.002",
"serviceProviderRate": "0.4",
"minPriceTickSize": "0.000000000000001",
"minQuantityTickSize": "1000000000000000"
},
"operationType": "update",
"timestamp": 1632535055790
}
Parameter | Type | Description |
---|---|---|
market | SpotMarketInfo | SpotMarketInfo object |
operation_type | String | Update type (Should be one of: [insert replace update invalidate]) |
timestamp | Integer | Operation timestamp in UNIX millis |
SpotMarketInfo
Parameter | Type | Description |
---|---|---|
base_denom | String | Coin denom of the base asset |
market_id | String | SpotMarket ID is keccak265(baseDenom |
market_status | String | The status of the market (Should be one of: [active paused suspended demolished expired]) |
min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity |
quote_token_meta | TokenMeta | TokenMeta object |
service_provider_fee | String | Percentage of the transaction fee shared with the service provider |
base_token_meta | TokenMeta | TokenMeta object |
maker_fee_rate | String | Defines the fee percentage makers pay when trading (in the quote asset) |
min_price_tick_size | String | Defines the minimum required tick size for the order's price |
quote_denom | String | Coin denom of the quote asset |
taker_fee_rate | String | Defines the fee percentage takers pay when trading (in the quote asset) |
ticker | String | A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset |
TokenMeta
Parameter | Type | Description |
---|---|---|
address | String | Token's Ethereum contract address |
decimals | Integer | Token decimals |
logo | String | URL to the logo image |
name | String | Token full name |
symbol | String | Token symbol short name |
updatedAt | Integer | Token metadata fetched timestamp in UNIX millis |
OrdersHistory
Get orders of a spot market in all states.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe"
subaccount_id = "0xed8c4C43E03E24b7F12975472da771Ce2f8b857c000000000000000000000000"
skip = 10
limit = 10
order_types = ["buy_po"]
orders = await client.get_historical_spot_orders(
market_id=market_id,
subaccount_id=subaccount_id,
skip=skip,
limit=limit
)
print(orders)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
subaccount_id | String | Filter by subaccount ID | No |
skip | Integer | Skip the last orders, you can use this to fetch all orders since the API caps at 100 | No |
limit | Integer | Limit the orders returned | No |
direction | String | Filter by direction | No |
start_time | Integer | Search for orders createdAt >= startTime, time in milliseconds | No |
end_time | Integer | Search for orders createdAt <= startTime, time in milliseconds | No |
state | String | The order state (Should be one of: [booked, partial_filled, filled, canceled]) | No |
execution_types | List | The execution of the order (Should be one of: [limit market]) | No |
order_types | List | The order type (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell buy_po sell_po]) | No |
Response Parameters
Response Example:
orders {
order_hash: "0x0f62edfb64644762c20490d9573034c2f319e87e857401c41eea1fe373045dd7"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccount_id: "0x1b99514e320ae0087be7f87b1e3057853c43b799000000000000000000000000"
execution_type: "limit"
order_type: "sell_po"
price: "1887550000"
trigger_price: "0"
quantity: "14.66"
filled_quantity: "0"
state: "canceled"
created_at: 1660245368028
updated_at: 1660245374789
direction: "sell"
}
orders {
order_hash: "0x82bb34aa9779c784f541269d3048b038a8c0100e17ef09b1367f44d8e2f6b052"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccount_id: "0x1b99514e320ae0087be7f87b1e3057853c43b799000000000000000000000000"
execution_type: "limit"
order_type: "buy_po"
price: "1854460000"
trigger_price: "0"
quantity: "16.01"
filled_quantity: "0"
state: "canceled"
created_at: 1660245184145
updated_at: 1660245368028
direction: "buy"
}
paging {
total: 1000
}
Parameter | Type | Description |
---|---|---|
orders | SpotOrderHistory | SpotOrderHistory object |
SpotOrderHistory
Parameter | Type | Description |
---|---|---|
order_hash | String | Hash of the order |
quantity | String | Quantity of the order |
is_active | Boolean | Indicates if the order is active |
state | String | Order state (Should be one of: [booked partial_filled filled canceled]) |
trigger_price | String | Trigger price is the trigger price used by stop/take orders |
market_id | String | Derivative Market ID |
created_at | Integer | Order committed timestamp in UNIX millis |
updated_at | Integer | Order updated timestamp in UNIX millis. |
price | String | Price of the order |
subaccount_id | String | The subaccountId that this order belongs to |
order_type | String | Order type (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell buy_po sell_po]) |
execution_type | String | The type of the order (Should be one of: [limit market]) |
filled_quantity | String | The amount of the quantity filled |
direction | String | The direction of the order (Should be one of: [buy sell]) |
StreamOrdersHistory
Stream order updates of a spot market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe"
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
orders = await client.stream_historical_spot_orders(
market_id=market_id,
)
async for order in orders:
print(order)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
subaccount_id | String | Filter by subaccount ID | No |
direction | String | Filter by direction (Should be one of: [buy sell]) | No |
state | String | Filter by state (Should be one of: [booked partial_filled filled canceled]) | No |
order_types | List | Filter by order type (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell buy_po sell_po]) | No |
execution_types | List | Filter by execution type (Should be one of: [limit market]) | No |
Response Parameters
Streaming Response Example:
order {
order_hash: "0xe34ada890ab627fb904d8dd50411a4ca64d1f6cb56c7305a2833772b36ae5660"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
is_active: true
subaccount_id: "0xed8c4c43e03e24b7f12975472da771ce2f8b857c000000000000000000000000"
execution_type: "limit"
order_type: "buy_po"
price: "0.000000000001849"
trigger_price: "0"
quantity: "10817000000000000000"
filled_quantity: "0"
state: "booked"
created_at: 1665486460484
updated_at: 1665486460484
direction: "buy"
}
operation_type: "insert"
timestamp: 1665486462000
Parameter | Type | Description |
---|---|---|
order | SpotOrderHistory | SpotOrderHistory object |
operation_type | String | Order update type (Should be one of: [insert replace update invalidate]) |
timestamp | Integer | Operation timestamp in UNIX millis |
SpotOrderHistory
Parameter | Type | Description |
---|---|---|
order_hash | String | Hash of the order |
quantity | String | Quantity of the order |
is_active | Boolean | Indicates if the order is active |
state | String | Order state (Should be one of: [booked partial_filled filled canceled]) |
trigger_price | String | Trigger price is the trigger price used by stop/take orders |
market_id | String | Derivative Market ID |
created_at | Integer | Order committed timestamp in UNIX millis |
updated_at | Integer | Order updated timestamp in UNIX millis. |
price | String | Price of the order |
subaccount_id | String | The subaccountId that this order belongs to |
order_type | String | Order type (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell buy_po sell_po]) |
execution_type | String | The type of the order (Should be one of: [limit market]) |
filled_quantity | String | The amount of the quantity filled |
direction | String | The direction of the order (Should be one of: [buy sell]) |
Trades
Get trades of a spot market.
Trade execution types
- Market for market orders
- limitFill for a resting limit order getting filled by a market order
- LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
- LimitMatchNewOrder for the other way around (new limit order getting matched)
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
execution_side = "taker"
direction = "buy"
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
orders = await client.get_spot_trades(
market_id=market_id,
execution_side=execution_side,
direction=direction,
subaccount_id=subaccount_id
)
print(orders)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccountId := "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
req := derivativeExchangePB.TradesRequest{
MarketId: marketId,
SubaccountId: subaccountId,
}
res, err := exchangeClient.GetDerivativeTrades(ctx, req)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson, TradeExecutionSide, TradeDirection } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0";
const subaccountId = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000";
const direction = TradeDirection.Buy;
const executionSide = TradeExecutionSide.Maker;
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.spot.fetchTrades(
{
marketId: marketId,
subaccountId: subaccountId,
direction: direction,
executionSide: executionSide,
});
console.log(protoObjectToJson(market));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
subaccount_id | String | Filter by subaccount ID | No |
direction | String | Filter by the direction of the trade (Should be one of: [buy sell]) | No |
execution_side | String | Filter by the execution side of the trade (Should be one of: [maker taker]) | No |
skip | Integer | Skip the last trades, you can use this to fetch all trades since the API caps at 100 | No |
limit | Integer | Limit the trades returned | No |
start_time | Integer | startTime <= x.executedAt <= endTime | No |
end_time | Integer | endTime >= x.executedAt <= startTime | No |
Response Parameters
Response Example:
trades {
order_hash: "0xa6b94df3b6ba72e601e9f876a851b985f34963299ccee66e51e177890102468f"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
trade_execution_type: "limitMatchNewOrder"
trade_direction: "buy"
price {
price: "0.0000000000051955"
quantity: "10000000000000000"
timestamp: 1652261436256
}
fee: "103.91"
executed_at: 1652261436256
fee_recipient: "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
}
trades {
order_hash: "0x6ad25de6dac78159fe66a02bded6bc9609ad67a3ad7b50c9809ce22c5855d571"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
trade_execution_type: "limitMatchNewOrder"
trade_direction: "buy"
price {
price: "0.0000000000054255"
quantity: "10000000000000000"
timestamp: 1652097626589
}
fee: "108.51"
executed_at: 1652097626589
fee_recipient: "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
}
{
"trades": [
{
"order_hash": "0xdc7cb11c1ad1edd129848da46b3c02f3a6860bc1478b8ba0620f7c18bae0eefe",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"trade_execution_type": "limitFill",
"position_delta": {
"trade_direction": "sell",
"execution_price": "42536400000",
"execution_quantity": "0.02",
"execution_margin": "850728000"
},
"payout": "850728000",
"fee": "425364",
"executed_at": 1652793510591,
"fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
{
"order_hash": "0x5e871a3dfb977acdd6727b6a4fa8156750b89078ad425406ffb2a9d06898ebf5",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"trade_execution_type": "limitMatchRestingOrder",
"position_delta": {
"trade_direction": "buy",
"execution_price": "40128736026.409431766475",
"execution_quantity": "0.02",
"execution_margin": "833072000"
},
"payout": "0",
"fee": "401287.36026409431766475",
"executed_at": 1652775275064,
"fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
}
]
}
{
"tradesList": [
{
"orderHash": "0xf7b0741b6e6ca6121f7747f662348674efc12e544746caf2d6cd045d6782dcb9",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"tradeExecutionType": "limitMatchRestingOrder",
"tradeDirection": "buy",
"price": {
"price": "0.000000000001880078",
"quantity": "32000000000000000000",
"timestamp": 1653642433329
},
"fee": "60162.496",
"executedAt": 1653642433329,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
{
"orderHash": "0x6f0be3232ffd084c0377302177c9fcf5caafea412c6c8d2daa352c91bd3c1c3c",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"tradeExecutionType": "limitMatchRestingOrder",
"tradeDirection": "buy",
"price": {
"price": "0.0000000000018405",
"quantity": "26000000000000000000",
"timestamp": 1653631819163
},
"fee": "47853",
"executedAt": 1653631819163,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
}
]
}
Parameter | Type | Description |
---|---|---|
trades | SpotTrade | SpotTrade object |
SpotTrade
Parameter | Type | Description |
---|---|---|
trade_direction | String | Filter by the trade direction(Should be one of: [buy sell]) |
trade_execution_type | String | Filter by the trade execution type (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder]) |
fee | String | The fee associated with the trade (quote asset denom) |
market_id | String | Filter by the market ID |
order_hash | String | The order hash |
price | PriceLevel | PriceLevel object |
subaccount_id | String | Filter by the subaccount ID |
executed_at | Integer | Timestamp of trade execution in UNIX millis |
fee_recipient | String | The address that received 40% of the fees |
PriceLevel
Parameter | Type | Description |
---|---|---|
price | String | Number of the price level |
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
StreamTrades
Stream trades of a spot market.
Trade execution types
- Market for market orders
- limitFill for a resting limit order getting filled by a market order
- LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
- LimitMatchNewOrder for the other way around (new limit order getting matched)
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_ids = [
"0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe",
"0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe"
]
execution_side = "maker"
direction = "sell"
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
trades = await client.stream_spot_trades(
market_id=market_ids[0],
execution_side=execution_side,
direction=direction,
subaccount_id=subaccount_id
)
async for trade in trades:
print(trade)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
spotExchangePB "github.com/InjectiveLabs/sdk-go/exchange/spot_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketId := "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
req := spotExchangePB.StreamTradesRequest{
MarketId: marketId,
SubaccountId: subaccountId,
}
stream, err := exchangeClient.StreamSpotTrades(ctx, req)
if err != nil {
fmt.Println(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
fmt.Println(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson, TradeExecutionSide, TradeDirection } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";;
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0";
const subaccountId = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const direction = TradeDirection.Sell;
const executionSide = TradeExecutionSide.Taker;
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.spot.streamSpotTrades(
{
marketId: marketId,
direction: direction,
subaccountId: subaccountId,
pagination: pagination,
executionSide: executionSide,
callback: (streamSpotTrades) => {
console.log(protoObjectToJson(streamSpotTrades));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_ids | Array | Filter by an array of market IDs | Conditional |
market_id | String | Filter by market ID | Conditional |
subaccount_ids | Array | Filter by an array of subaccount IDs | Conditional |
subaccount_id | String | Filter by subaccount ID | Conditional |
execution_side | String | Filter by the execution side of the trade (Should be one of: [maker taker]) | No |
direction | String | Filter by the direction of the trade (Should be one of: [buy sell]) | No |
skip | Integer | Skip the last trades, you can use this to fetch all trades since the API caps at 100 | No |
limit | Integer | Limit the trades returned | No |
Response Parameters
Streaming Response Example:
trade {
order_hash: "0x2d374994918a86f45f9eca46efbc64d866b9ea1d0c49b5aa0c4a114be3570d05"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
trade_execution_type: "market"
trade_direction: "sell"
price {
price: "0.000000000001654"
quantity: "1000000000000000000"
timestamp: 1652809465316
}
fee: "3308"
executed_at: 1652809465316
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
}
operation_type: "insert"
timestamp: 1652809469000
{
"trade": {
"order_hash": "0x88e34872af0147f57c8c5a093c3a6a8a97358615bccf975b4a06dfb5162daeaf",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"trade_execution_type": "market",
"trade_direction": "sell",
"price": {
"price": "0.000000000001654",
"quantity": "1000000000000000000",
"timestamp": 1653042087046
},
"fee": "3308",
"executed_at": 1653042087046,
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
"operation_type": "insert",
"timestamp": 1653042089000
}{
"trade": {
"order_hash": "0xb5d651a01faa90ec53b0fa34f00f3ecdfe169f9fc35be8114ee113eea9257c30",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"trade_execution_type": "market",
"trade_direction": "sell",
"price": {
"price": "0.000000000001654",
"quantity": "2000000000000000000",
"timestamp": 1653042093023
},
"fee": "6616",
"executed_at": 1653042093023,
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
"operation_type": "insert",
"timestamp": 1653042098000
}
{
"trade": {
"orderHash": "0xedf6203fce7e3391052ddd8244385b267ddbe81aebd90724cde09c0c1b4af73b",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"tradeExecutionType": "market",
"tradeDirection": "sell",
"price": {
"price": "0.000000000003",
"quantity": "1000000000000000000",
"timestamp": 1654080019844
},
"fee": "6000",
"executedAt": 1654080019844,
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
"operationType": "insert",
"timestamp": 1654080026000
}
{
"trade": {
"orderHash": "0xac596cc795ba91dc8f10b6d251e211679f908be04f8becca566210fab20bfd2f",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"tradeExecutionType": "market",
"tradeDirection": "sell",
"price": {
"price": "0.000000000003",
"quantity": "49000000000000000000",
"timestamp": 1654080025588
},
"fee": "294000",
"executedAt": 1654080025588,
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
"operationType": "insert",
"timestamp": 1654080028000
}
Parameter | Type | Description |
---|---|---|
operation_type | String | Trade operation type (Should be one of: [insert invalidate]) |
timestamp | Integer | Operation timestamp in UNIX millis |
trade | SpotTrade | SpotTrade object |
SpotTrade
Parameter | Type | Description |
---|---|---|
trade_direction | String | Filter by the trade direction(Should be one of: [buy sell]) |
trade_execution_type | String | Filter by the trade execution type (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder]) |
fee | String | The fee associated with the trade (quote asset denom) |
market_id | String | Filter by the market ID |
order_hash | String | The order hash |
price | PriceLevel | PriceLevel object |
subaccount_id | String | Filter by the subaccount ID |
executed_at | Integer | Timestamp of trade execution in UNIX millis |
fee_recipient | String | The address that received 40% of the fees |
PriceLevel
Parameter | Type | Description |
---|---|---|
price | String | Number of the price level |
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
Orderbook
Get the orderbook of a spot market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe"
orderbook = await client.get_spot_orderbook(market_id=market_id)
print(orderbook)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketId := "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
res, err := exchangeClient.GetSpotOrderbook(ctx, marketId)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson, ExchangeClient } from "@injectivelabs/sdk-ts";
(async () => {
const network = getNetworkInfo(Network.Testnet);
const marketId = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0";
const exchangeClient = new ExchangeClient.ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.spotApi.fetchSpotOrderbook(marketId);
console.log(protoObjectToJson(market, {}));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
Response Parameters
Response Example:
orderbook {
buys {
price: "0.000000000001654"
quantity: "27000000000000000000"
timestamp: 1652809260554
}
buys {
price: "0.000000000001608"
quantity: "38000000000000000000"
timestamp: 1652809253308
}
sells {
price: "0.000000000002359"
quantity: "42000000000000000000"
timestamp: 1652774849587
}
sells {
price: "0.000000000002367"
quantity: "40000000000000000000"
timestamp: 1652774849587
}
{
"orderbook": {
"buys": [
{
"price": "0.000000000001654",
"quantity": "27000000000000000000",
"timestamp": 1652395260912
},
{
"price": "0.000000000001608",
"quantity": "38000000000000000000",
"timestamp": 1652351094680
},
],
"sells": [
{
"price": "0.000000000002305",
"quantity": "28000000000000000000",
"timestamp": 1652774849587
},
{
"price": "0.00000000000231",
"quantity": "10000000000000000000",
"timestamp": 1652774849587
},
{
"price": "0.000000000002313",
"quantity": "20000000000000000000",
"timestamp": 1652774849587
},
{
"price": "0.0000000003",
"quantity": "220000000000000000000",
"timestamp": 1652264026293
}
]
}
}
{
"orderbook": {
"buysList": [
{
"price": "0.000000000002375",
"quantity": "4000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000002349",
"quantity": "14000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000002336",
"quantity": "34000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000001",
"quantity": "4000000000000000000",
"timestamp": 1653930539754
}
],
"sellsList": [
{
"price": "0.0000000000025",
"quantity": "1000000000000000000",
"timestamp": 1654080089976
}
]
}
}
Parameter | Type | Description |
---|---|---|
orderbook | SpotLimitOrderbook | SpotLimitOrderbook object |
SpotLimitOrderbook
Parameter | Type | Description |
---|---|---|
buys | PriceLevel | PriceLevel object |
sells | PriceLevel | PriceLevel object |
PriceLevel
Parameter | Type | Description |
---|---|---|
price | String | Number of the price level |
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
Orderbooks
Get the orderbook for an array of spot markets.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_ids = [
"0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe",
"0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0"
]
markets = await client.get_spot_orderbooks(market_ids=market_ids)
print(markets)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketIds := []string{"0x26413a70c9b78a495023e5ab8003c9cf963ef963f6755f8b57255feb5744bf31", "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"}
res, err := exchangeClient.GetSpotOrderbooks(ctx, marketIds)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketIds = ["0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0", "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa"];
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.spot.fetchOrderbooks(marketIds);
console.log(protoObjectToJson(market));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_ids | Array | Filter by an array of market IDs | Yes |
Response Parameters
Response Example:
orderbooks {
market_id: "0x26413a70c9b78a495023e5ab8003c9cf963ef963f6755f8b57255feb5744bf31"
orderbook {
buys {
price: "0.000000000006057"
quantity: "38000000000000000000"
timestamp: 1652395483345
}
buys {
price: "0.000000000005643"
quantity: "8000000000000000000"
timestamp: 1652340918434
}
sells {
price: "0.000000000008102"
quantity: "50000000000000000000"
timestamp: 1652773614923
}
sells {
price: "0.000000000008108"
quantity: "48000000000000000000"
timestamp: 1652774630240
orderbooks {
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
orderbook {
buys {
price: "0.000000000001654"
quantity: "27000000000000000000"
timestamp: 1652395260912
}
buys {
price: "0.000000000001608"
quantity: "38000000000000000000"
timestamp: 1652351094680
sells {
price: "0.00000000002792"
quantity: "30000000000000000"
timestamp: 1652263504751
}
sells {
price: "0.0000000003"
quantity: "220000000000000000000"
timestamp: 1652264026293
}
}
}
{
"orderbooks": [
{
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"orderbook": {
"buys": [
{
"price": "0.000000000001654",
"quantity": "27000000000000000000",
"timestamp": 1652395260912
},
{
"price": "0.000000000000001",
"quantity": "62000000000000000",
"timestamp": 1649838645114
}
],
"sells": [
{
"price": "0.00000000002792",
"quantity": "30000000000000000",
"timestamp": 1652263504751
},
{
"price": "0.0000000003",
"quantity": "220000000000000000000",
"timestamp": 1652264026293
}
]
}
},
{
"market_id": "0x26413a70c9b78a495023e5ab8003c9cf963ef963f6755f8b57255feb5744bf31",
"orderbook": {
"buys": [
{
"price": "0.000000000006057",
"quantity": "38000000000000000000",
"timestamp": 1652395483345
},
{
"price": "0.000000000005643",
"quantity": "8000000000000000000",
"timestamp": 1652340012497
},
{
"price": "0.000000000005374",
"quantity": "46000000000000000000",
"timestamp": 1652340012497
}
],
"sells": [
{
"price": "0.000000000014033",
"quantity": "48000000000000000000",
"timestamp": 1650976706210
},
{
"price": "0.000000000014036",
"quantity": "48000000000000000000",
"timestamp": 1650974855789
},
{
"price": "0.000000000014094",
"quantity": "44000000000000000000",
"timestamp": 1650976917202
}
]
}
}
]
}
{
"orderbooksList": [
{
"marketId": "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa",
"orderbook": {
"buysList": [
{
"price": "22",
"quantity": "1000000",
"timestamp": 1654080262300
}
],
"sellsList": [
{
"price": "23",
"quantity": "10000",
"timestamp": 1654080273783
}
]
}
},
{
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"orderbook": {
"buysList": [
{
"price": "0.000000000002375",
"quantity": "4000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000002349",
"quantity": "14000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000002336",
"quantity": "34000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000001",
"quantity": "4000000000000000000",
"timestamp": 1653930539754
}
],
"sellsList": [
{
"price": "0.0000000000025",
"quantity": "1000000000000000000",
"timestamp": 1654080089976
}
]
}
}
]
}
Parameter | Type | Description |
---|---|---|
orderbook | SpotLimitOrderbook | SpotLimitOrderbook object |
market_id | String | Filter by market ID |
SpotLimitOrderbook
Parameter | Type | Description |
---|---|---|
buys | PriceLevel | PriceLevel object |
sells | PriceLevel | PriceLevel object |
PriceLevel
Parameter | Type | Description |
---|---|---|
price | String | Number of the price level |
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
StreamOrderbooks
Stream orderbook updates for an array of spot markets.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_ids = ["0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe", "0x7a57e705bb4e09c88aecfc295569481dbf2fe1d5efe364651fbe72385938e9b0"]
orderbook = await client.stream_spot_orderbooks(market_ids=market_ids)
async for orders in orderbook:
print(orders)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketIds := []string{"0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"}
stream, err := exchangeClient.StreamSpotOrderbook(ctx, marketIds)
if err != nil {
fmt.Println(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
fmt.Println(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";;
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketIds = ["0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"];
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.spot.streamSpotOrderbook(
{
marketIds,
callback: (streamSpotOrderbook) => {
console.log(protoObjectToJson(streamSpotOrderbook));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_ids | Array | Filter by market IDs | Yes |
Response Parameters
Streaming Response Example:
orderbook {
buys {
price: "0.000000000001654"
quantity: "27000000000000000000"
timestamp: 1652395260912
}
buys {
price: "0.000000000001608"
quantity: "38000000000000000000"
timestamp: 1652351094680
}
buys {
price: "0.000000000001573"
quantity: "48000000000000000000"
timestamp: 1652338751248
}
sells {
price: "0.000000000005246"
quantity: "42000000000000000000"
timestamp: 1651613401202
}
sells {
price: "0.00000000002792"
quantity: "30000000000000000"
timestamp: 1652263504751
}
sells {
price: "0.0000000003"
quantity: "220000000000000000000"
timestamp: 1652264026293
}
}
operation_type: "update"
timestamp: 1652809737000
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
{
"orderbook": {
"buys": [
{
"price": "0.000000000002349",
"quantity": "14000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000002336",
"quantity": "34000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000002328",
"quantity": "12000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.000000000001",
"quantity": "4000000000000000000",
"timestamp": 1653930539754
}
],
"sells": [
{
"price": "0.000000000003",
"quantity": "1000000000000000000",
"timestamp": 1654080771385
}
]
},
"operation_type": "update",
"timestamp": 1654080908000,
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
}
{
"orderbook": {
"buysList": [
{
"price": "0.000000000002375",
"quantity": "4000000000000000000",
"timestamp": 1653968629289
},
{
"price": "0.0000000000015",
"quantity": "46000000000000000000",
"timestamp": 1652340323984
},
{
"price": "0.000000000001",
"quantity": "4000000000000000000",
"timestamp": 1653930539754
}
],
"sellsList": []
},
"operationType": "update",
"timestamp": 1654080598000,
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
}
Parameter | Type | Description |
---|---|---|
operation_type | String | Order update type (Should be one of: [insert replace update invalidate]) |
orderbook | SpotLimitOrderbook | SpotLimitOrderbook object |
timestamp | Integer | Operation timestamp in UNIX millis |
market_id | String | Filter by market ID |
SpotLimitOrderbook
Parameter | Type | Description |
---|---|---|
buys | PriceLevel | PriceLevel object |
sells | PriceLevel | PriceLevel object |
PriceLevel
Parameter | Type | Description |
---|---|---|
price | String | Number of the price level |
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
SubaccountOrdersList
Get orders of a subaccount.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe"
skip = 10
limit = 10
orders = await client.get_spot_subaccount_orders(
subaccount_id=subaccount_id,
market_id=market_id,
skip=skip,
limit=limit
)
print(orders)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
spotExchangePB "github.com/InjectiveLabs/sdk-go/exchange/spot_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketId := "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
skip := uint64(0)
limit := int32(2)
req := spotExchangePB.SubaccountOrdersListRequest{
MarketId: marketId,
SubaccountId: subaccountId,
Skip: skip,
Limit: limit,
}
res, err := exchangeClient.GetSubaccountSpotOrdersList(ctx, req)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0";
const subaccountId = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.spot.fetchSubaccountOrdersList(
{
subaccountId: subaccountId,
marketId: marketId,
pagination: pagination,
}
);
console.log(protoObjectToJson(market));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
market_id | String | Filter by market ID | No |
skip | Integer | Skip the last orders, you can use this to fetch all orders since the API caps at 100 | No |
limit | Integer | Limit the orders returned | No |
Response Parameters
Response Example:
orders {
order_hash: "0x5e970df47eb5a65a5f907e3a2912067dde416eca8609c838e08c0dbebfbefaa5"
order_side: "sell"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
price: "0.000000000005"
quantity: "1000000000000000000"
unfilled_quantity: "1000000000000000000"
trigger_price: "0"
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
state: "booked"
created_at: 1652809317404
updated_at: 1652809317404
}
orders {
order_hash: "0x318418b546563a75c11dc656ee0fb41608e2893b0de859cf2b9e2d65996b6f9c"
order_side: "buy"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
price: "0.000000000001"
quantity: "1000000000000000000"
unfilled_quantity: "1000000000000000000"
trigger_price: "0"
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
state: "booked"
created_at: 1652809253308
updated_at: 1652809253308
}
{
"orders": [
{
"order_hash": "0x5e970df47eb5a65a5f907e3a2912067dde416eca8609c838e08c0dbebfbefaa5",
"order_side": "sell",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"price": "0.000000000005",
"quantity": "1000000000000000000",
"unfilled_quantity": "1000000000000000000",
"trigger_price": "0",
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"created_at": 1652809317404,
"updated_at": 1652809317404
},
{
"order_hash": "0x318418b546563a75c11dc656ee0fb41608e2893b0de859cf2b9e2d65996b6f9c",
"order_side": "buy",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"price": "0.000000000001",
"quantity": "1000000000000000000",
"unfilled_quantity": "1000000000000000000",
"trigger_price": "0",
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"created_at": 1652809253308,
"updated_at": 1652809253308
}
]
}
{
"ordersList": [
{
"orderHash": "0x2f63441ddea8003bb29c28949d4a3f3b1e40fb423154164a7b579fbefa2e4f8d",
"orderSide": "sell",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"price": "0.000000000003",
"quantity": "1000000000000000000",
"unfilledQuantity": "1000000000000000000",
"triggerPrice": "0",
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"createdAt": 1654080771385,
"updatedAt": 1654080771385
},
{
"orderHash": "0xb5b7f863c0f94f31668670d9ac74df6c31dc37b5d3b73e7ac43a200da58fbaeb",
"orderSide": "buy",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"price": "0.000000000001",
"quantity": "1500000000000000000",
"unfilledQuantity": "1500000000000000000",
"triggerPrice": "0",
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"createdAt": 1654079407709,
"updatedAt": 1654079407709
},
{
"orderHash": "0x9bfdda8da0008059844bff8e2cfa0399d5a71abaadc2a3b659c4c2c0db654fb6",
"orderSide": "buy",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"price": "0.000000000001",
"quantity": "2000000000000000000",
"unfilledQuantity": "2000000000000000000",
"triggerPrice": "0",
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"createdAt": 1654079382459,
"updatedAt": 1654079382459
},
{
"orderHash": "0xc2d56db71c54e5d0814746ebb966d63bb6c0b5f3462e97b2d607028881144b3b",
"orderSide": "buy",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"price": "0.000000000002",
"quantity": "2000000000000000000",
"unfilledQuantity": "2000000000000000000",
"triggerPrice": "0",
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"createdAt": 1654079341993,
"updatedAt": 1654079341993
},
{
"orderHash": "0xd3f1e94393fc026a6a5b709b52b5ad0057e771b2b2768f4d7aebd03c5dfa383f",
"orderSide": "buy",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"price": "0.000000000002",
"quantity": "1000000000000000000",
"unfilledQuantity": "1000000000000000000",
"triggerPrice": "0",
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"createdAt": 1654079259156,
"updatedAt": 1654079259156
}
]
}
Parameter | Type | Description |
---|---|---|
orders | SpotLimitOrder | SpotLimitOrder object |
SpotLimitOrder
Parameter | Type | Description |
---|---|---|
state | String | Order state (Should be one of: [booked partial_filled filled canceled]) |
subaccount_id | String | The subaccount ID this order belongs to |
unfilled_quantity | String | The amount of the quantity remaining unfilled |
market_id | String | Spot market ID is keccak265(baseDenom + quoteDenom) |
order_hash | String | Hash of the order |
order_side | String | The type of the order (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell]) |
fee_recipient | String | The fee recipient address |
price | String | The price of the order |
quantity | String | The quantity of the order |
trigger_price | String | The price used by stop/take orders |
created_at | Integer | Order committed timestamp in UNIX millis |
SubaccountTradesList
Get trades of a subaccount.
Trade execution types
- Market for market orders
- limitFill for a resting limit order getting filled by a market order
- LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
- LimitMatchNewOrder for the other way around (new limit order getting matched)
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id = "0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe"
execution_type = "market"
direction = "buy"
skip = 10
limit = 10
trades = await client.get_spot_subaccount_trades(
subaccount_id=subaccount_id,
market_id=market_id,
execution_type=execution_type,
direction=direction,
skip=skip,
limit=limit
)
print(trades)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
spotExchangePB "github.com/InjectiveLabs/sdk-go/exchange/spot_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
marketId := "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccountId := "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
skip := uint64(0)
limit := int32(2)
req := spotExchangePB.SubaccountTradesListRequest{
MarketId: marketId,
SubaccountId: subaccountId,
Skip: skip,
Limit: limit,
}
res, err := exchangeClient.GetSubaccountSpotTradesList(ctx, req)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson, TradeExecutionType, TradeDirection } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0";
const subaccountId = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const direction = TradeDirection.Buy;
const executionType = TradeExecutionType.Market;
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.spot.fetchSubaccountTradesList(
{
subaccountId: subaccountId,
marketId: marketId,
direction: direction,
executionType: executionType,
pagination: pagination,
}
);
console.log(protoObjectToJson(market));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
market_id | String | Filter by market ID | No |
direction | String | Filter by the direction of the trades (Should be one of: [buy sell]) | No |
execution_type | String | Filter by the execution type of the trades (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder]) | No |
skip | Integer | Skip the last trades, you can use this to fetch all trades since the API caps at 100 | No |
limit | Integer | Limit the trades returned | No |
Response Parameters
Response Example:
trades {
order_hash: "0x96453bfbda21b4bd53b3b2b85d510f2fec8a56893e9a142d9f7d32484647bccf"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
trade_execution_type: "market"
trade_direction: "buy"
price {
price: "0.000000000002305"
quantity: "1000000000000000000"
timestamp: 1652809734211
}
fee: "4610"
executed_at: 1652809734211
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
}
trades {
order_hash: "0x76b84ef27778636595e9582a0641f100a4d593e92a9dcc4fdf64c3000894988f"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
trade_execution_type: "market"
trade_direction: "buy"
price {
price: "0.000000000002305"
quantity: "1000000000000000000"
timestamp: 1652809124051
}
fee: "4610"
executed_at: 1652809124051
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
}
{
"trades": [
{
"order_hash": "0xbf5cf18a5e73c61d465a60ca550c5fbe0ed37b9ca0a49f7bd1de012e983fe55e",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"trade_execution_type": "limitFill",
"trade_direction": "sell",
"price": {
"price": "0.000000000002305",
"quantity": "1000000000000000000",
"timestamp": 1652809734211
},
"fee": "2305",
"executed_at": 1652809734211,
"fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
{
"order_hash": "0xfd474dc696dc291bca8ca1b371653994fd846a303c08d26ccc17a7b60939d256",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"trade_execution_type": "limitFill",
"trade_direction": "sell",
"price": {
"price": "0.000000000002318",
"quantity": "4000000000000000000",
"timestamp": 1652773190338
},
"fee": "9272",
"executed_at": 1652773190338,
"fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
}
]
}
{
"tradesList": [
{
"orderHash": "0xa6e42876bc57db846a06e1efbf481c99696fc8e50797d6535dde70545240839c",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"tradeExecutionType": "market",
"tradeDirection": "buy",
"price": {
"price": "0.0000000000025",
"quantity": "1000000000000000000",
"timestamp": 1654080596036
},
"fee": "5000",
"executedAt": 1654080596036,
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
{
"orderHash": "0x78b04557c96b82cfb49bb31955c4f990e4cf1bd2a976d683defdf676d427632f",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"tradeExecutionType": "market",
"tradeDirection": "buy",
"price": {
"price": "0.0000000003",
"quantity": "55000000000000000000",
"timestamp": 1653935308434
},
"fee": "33000000",
"executedAt": 1653935308434,
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
{
"orderHash": "0x6ad25de6dac78159fe66a02bded6bc9609ad67a3ad7b50c9809ce22c5855d571",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"tradeExecutionType": "limitMatchNewOrder",
"tradeDirection": "buy",
"price": {
"price": "0.0000000000054255",
"quantity": "10000000000000000",
"timestamp": 1652097626589
},
"fee": "108.51",
"executedAt": 1652097626589,
"feeRecipient": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
}
]
}
Parameter | Type | Description |
---|---|---|
trades | SpotTrade | SpotTrade object |
SpotTrade
Parameter | Type | Description |
---|---|---|
trade_direction | String | Filter by the trade direction(Should be one of: [buy sell]) |
trade_execution_type | String | Filter by the trade execution type (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder]) |
fee | String | The fee associated with the trade (quote asset denom) |
market_id | String | Filter by the market ID |
order_hash | String | The order hash |
price | PriceLevel | PriceLevel object |
subaccount_id | String | Filter by the subaccount ID |
executed_at | Integer | Timestamp of trade execution in UNIX millis |
fee_recipient | String | The address that received 40% of the fees |
PriceLevel
Parameter | Type | Description |
---|---|---|
price | String | Number of the price level |
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
- InjectiveDerivativeExchangeRPC
InjectiveDerivativeExchangeRPC defines the gRPC API of the Derivative Exchange provider.
Market
Get details of a derivative market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
market = await client.get_derivative_market(market_id=market_id)
print(market)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
res, err := exchangeClient.GetDerivativeMarket(ctx, marketId)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.derivatives.fetchMarket(marketId);
console.log(protoObjectToJson(market));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
Response Parameters
Response Example:
market {
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
market_status: "active"
ticker: "BTC/USDT PERP"
oracle_base: "BTC"
oracle_quote: "USDT"
oracle_type: "bandibc"
oracle_scale_factor: 6
initial_margin_ratio: "0.095"
maintenance_margin_ratio: "0.05"
quote_denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
quote_token_meta {
name: "Tether"
address: "0xdAC17F958D2ee523a2206206994597C13D831ec7"
symbol: "USDT"
logo: "https://static.alchemyapi.io/images/assets/825.png"
decimals: 6
updated_at: 1650978923435
}
maker_fee_rate: "0.0005"
taker_fee_rate: "0.0012"
service_provider_fee: "0.4"
is_perpetual: true
min_price_tick_size: "100000"
min_quantity_tick_size: "0.0001"
perpetual_market_info {
hourly_funding_rate_cap: "0.000625"
hourly_interest_rate: "0.00000416666"
next_funding_timestamp: 1652792400
funding_interval: 3600
}
perpetual_market_funding {
cumulative_funding: "7234678245.415396885076050889"
cumulative_price: "6.214149999812187743"
last_timestamp: 1652775381
}
}
{
"market": {
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"market_status": "active",
"ticker": "BTC/USDT PERP",
"oracle_base": "BTC",
"oracle_quote": "USDT",
"oracle_type": "bandibc",
"oracle_scale_factor": 6,
"initial_margin_ratio": "0.095",
"maintenance_margin_ratio": "0.05",
"quote_denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"quote_token_meta": {
"name": "Tether",
"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updated_at": 1650978923435
},
"maker_fee_rate": "0.0005",
"taker_fee_rate": "0.0012",
"service_provider_fee": "0.4",
"is_perpetual": true,
"min_price_tick_size": "100000",
"min_quantity_tick_size": "0.0001",
"perpetual_market_info": {
"hourly_funding_rate_cap": "0.000625",
"hourly_interest_rate": "0.00000416666",
"next_funding_timestamp": 1652864400,
"funding_interval": 3600
},
"perpetual_market_funding": {
"cumulative_funding": "7246105747.050586213851272386",
"cumulative_price": "31.114148427047982579",
"last_timestamp": 1652793510
}
}
}
{
"market": {
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"marketStatus": "active",
"ticker": "BTC/USDT PERP",
"oracleBase": "BTC",
"oracleQuote": "USDT",
"oracleType": "bandibc",
"oracleScaleFactor": 6,
"initialMarginRatio": "0.095",
"maintenanceMarginRatio": "0.05",
"quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"quoteTokenMeta": {
"name": "Tether",
"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updatedAt": 1650978923435
},
"makerFeeRate": "0.0005",
"takerFeeRate": "0.0012",
"serviceProviderFee": "0.4",
"isPerpetual": true,
"minPriceTickSize": "100000",
"minQuantityTickSize": "0.0001",
"perpetualMarketInfo": {
"hourlyFundingRateCap": "0.000625",
"hourlyInterestRate": "0.00000416666",
"nextFundingTimestamp": 1654246800,
"fundingInterval": 3600
},
"perpetualMarketFunding": {
"cumulativeFunding": "8239865636.851083559033030036",
"cumulativePrice": "-3.875827592425613503",
"lastTimestamp": 1654243770
}
}
}
Parameter | Type | Description |
---|---|---|
market | DerivativeMarketInfo | DerivativeMarketInfo object |
DerivativeMarketInfo
Parameter | Type | Description |
---|---|---|
oracle_quote | String | Oracle quote currency |
oracle_type | String | Oracle Type |
quote_denom | String | Coin denom used for the quote asset |
is_perpetual | Boolean | True if the market is a perpetual swap market |
maker_fee_rate | String | Defines the fee percentage makers pay when trading (in quote asset) |
min_price_tick_size | String | Defines the minimum required tick size for the order's price |
min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity |
oracle_scale_factor | Integer | OracleScaleFactor |
taker_fee_rate | String | Defines the fee percentage takers pay when trading (in quote asset) |
expiry_futures_market_info | Array | ExpiryFuturesMarketInfo object |
initial_margin_ratio | String | Defines the initial margin ratio of a derivative market |
market_status | String | The status of the market (Should be one of: [active paused suspended demolished expired]) |
service_provider_fee | String | Percentage of the transaction fee shared with the service provider |
oracle_base | String | Oracle base currency |
perpetual_market_funding | PerpetualMarketFunding | PerpetualMarketFunding object |
perpetual_market_info | PerpetualMarketInfo | PerpetualMarketInfo object |
ticker | String | The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset |
maintenance_margin_ratio | String | Defines the maintenance margin ratio of a derivative market |
market_id | String | The market ID |
quoteTokenMeta | TokenMeta | TokenMeta object |
PerpetualMarketFunding
Parameter | Type | Description |
---|---|---|
cumulative_funding | String | Defines the cumulative funding of a perpetual market |
cumulative_price | String | Defines the cumulative price for the current hour up to the last timestamp |
last_timestamp | Integer | Defines the last funding timestamp in UNIX seconds |
PerpetualMarketInfo
Parameter | Type | Description |
---|---|---|
hourly_funding_rate_cap | String | Defines the default maximum absolute value of the hourly funding rate |
hourly_interest_rate | String | Defines the hourly interest rate of the perpetual market |
next_funding_timestamp | Integer | Defines the next funding timestamp in UNIX seconds |
funding_interval | Integer | Defines the funding interval in seconds |
TokenMeta
Parameter | Type | Description |
---|---|---|
updated_at | Integer | Token metadata fetched timestamp in UNIX millis |
address | String | Token Ethereum contract address |
decimals | Integer | Token decimals |
logo | String | URL to the logo image |
name | String | Token full name |
symbol | String | Token symbol short name |
Markets
Get a list of derivative markets.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_status = "active" # active, paused, suspended, demolished or expired
quote_denom = "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
market = await client.get_derivative_markets(
market_status=market_status,
quote_denom=quote_denom
)
print(market)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketStatus := "active"
quoteDenom := "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
req := derivativeExchangePB.MarketsRequest{
MarketStatus: marketStatus,
QuoteDenom: quoteDenom,
}
res, err := exchangeClient.GetDerivativeMarkets(ctx, req)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketStatus = "active";
const quoteDenom = "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7";
const exchangeClient = new ExchangeGrpcClient(network.exchangeApi);
const markets = await exchangeClient.derivatives.fetchMarkets({
marketStatus: marketStatus,
quoteDenom: quoteDenom,
});
console.log(protoObjectToJson(markets));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_status | String | Filter by market status (Should be one of: [active paused suspended demolished expired]) | No |
quote_denom | String | Filter by the Coin denomination of the quote currency | No |
Response Parameters
Response Example:
markets {
market_id: "0x54d4505adef6a5cef26bc403a33d595620ded4e15b9e2bc3dd489b714813366a"
market_status: "active"
ticker: "ETH/USDT PERP"
oracle_base: "ETH"
oracle_quote: "USDT"
oracle_type: "bandibc"
oracle_scale_factor: 6
initial_margin_ratio: "0.195"
maintenance_margin_ratio: "0.05"
quote_denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
quote_token_meta {
name: "Tether"
address: "0xdAC17F958D2ee523a2206206994597C13D831ec7"
symbol: "USDT"
logo: "https://static.alchemyapi.io/images/assets/825.png"
decimals: 6
updated_at: 1650978923442
}
maker_fee_rate: "0.0005"
taker_fee_rate: "0.0012"
service_provider_fee: "0.4"
is_perpetual: true
min_price_tick_size: "10000"
min_quantity_tick_size: "0.01"
perpetual_market_info {
hourly_funding_rate_cap: "0.000625"
hourly_interest_rate: "0.00000416666"
next_funding_timestamp: 1652371200
funding_interval: 3600
}
perpetual_market_funding {
cumulative_funding: "386580047.750314353885122297"
cumulative_price: "435.300710510988475128"
last_timestamp: 1652790383
}
}
markets {
market_id: "0xfb5f14852bd01af901291dd2aa65e997b3a831f957124a7fe7aa40d218ff71ae"
market_status: "active"
ticker: "XAG/USDT PERP"
oracle_base: "XAG"
oracle_quote: "USDT"
oracle_type: "bandibc"
oracle_scale_factor: 6
initial_margin_ratio: "0.8"
maintenance_margin_ratio: "0.4"
quote_denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
quote_token_meta {
name: "Tether"
address: "0xdAC17F958D2ee523a2206206994597C13D831ec7"
symbol: "USDT"
logo: "https://static.alchemyapi.io/images/assets/825.png"
decimals: 6
updated_at: 1650978923534
}
maker_fee_rate: "0.003"
taker_fee_rate: "0.005"
service_provider_fee: "0.4"
is_perpetual: true
min_price_tick_size: "10000"
min_quantity_tick_size: "0.01"
perpetual_market_info {
hourly_funding_rate_cap: "0.000625"
hourly_interest_rate: "0.00000416666"
next_funding_timestamp: 1652792400
funding_interval: 3600
}
perpetual_market_funding {
cumulative_funding: "1099659.417190990913058692"
cumulative_price: "-4.427475055338306767"
last_timestamp: 1652775322
}
}
{
"markets": [
{
"market_id": "0x1c79dac019f73e4060494ab1b4fcba734350656d6fc4d474f6a238c13c6f9ced",
"market_status": "active",
"ticker": "BNB/USDT PERP",
"oracle_base": "BNB",
"oracle_quote": "USDT",
"oracle_type": "bandibc",
"oracle_scale_factor": 6,
"initial_margin_ratio": "0.095",
"maintenance_margin_ratio": "0.05",
"quote_denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"quote_token_meta": {
"name": "Tether",
"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updated_at": 1650978923353
},
"maker_fee_rate": "0.0005",
"taker_fee_rate": "0.0012",
"service_provider_fee": "0.4",
"is_perpetual": true,
"min_price_tick_size": "10000",
"min_quantity_tick_size": "0.01",
"perpetual_market_info": {
"hourly_funding_rate_cap": "0.000625",
"hourly_interest_rate": "0.00000416666",
"next_funding_timestamp": 1652864400,
"funding_interval": 3600
},
"perpetual_market_funding": {
"cumulative_funding": "48248742.484852568471323698",
"cumulative_price": "5.691379282523162906",
"last_timestamp": 1652775374
}
},
{
"market_id": "0xfb5f14852bd01af901291dd2aa65e997b3a831f957124a7fe7aa40d218ff71ae",
"market_status": "active",
"ticker": "XAG/USDT PERP",
"oracle_base": "XAG",
"oracle_quote": "USDT",
"oracle_type": "bandibc",
"oracle_scale_factor": 6,
"initial_margin_ratio": "0.8",
"maintenance_margin_ratio": "0.4",
"quote_denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"quote_token_meta": {
"name": "Tether",
"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updated_at": 1650978923534
},
"maker_fee_rate": "0.003",
"taker_fee_rate": "0.005",
"service_provider_fee": "0.4",
"is_perpetual": true,
"min_price_tick_size": "10000",
"min_quantity_tick_size": "0.01",
"perpetual_market_info": {
"hourly_funding_rate_cap": "0.000625",
"hourly_interest_rate": "0.00000416666",
"next_funding_timestamp": 1652864400,
"funding_interval": 3600
},
"perpetual_market_funding": {
"cumulative_funding": "1099659.417190990913058692",
"cumulative_price": "-4.427475055338306767",
"last_timestamp": 1652775322
}
}
]
}
{
"marketsList": [
{
"marketId": "0x1c79dac019f73e4060494ab1b4fcba734350656d6fc4d474f6a238c13c6f9ced",
"marketStatus": "active",
"ticker": "BNB/USDT PERP",
"oracleBase": "BNB",
"oracleQuote": "USDT",
"oracleType": "bandibc",
"oracleScaleFactor": 6,
"initialMarginRatio": "0.095",
"maintenanceMarginRatio": "0.05",
"quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"quoteTokenMeta": {
"name": "Tether",
"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updatedAt": 1650978923353
},
"makerFeeRate": "0.0005",
"takerFeeRate": "0.0012",
"serviceProviderFee": "0.4",
"isPerpetual": true,
"minPriceTickSize": "10000",
"minQuantityTickSize": "0.01",
"perpetualMarketInfo": {
"hourlyFundingRateCap": "0.000625",
"hourlyInterestRate": "0.00000416666",
"nextFundingTimestamp": 1654246800,
"fundingInterval": 3600
},
"perpetualMarketFunding": {
"cumulativeFunding": "56890491.178246679699729639",
"cumulativePrice": "7.082760891515203314",
"lastTimestamp": 1654245985
}
},
{
"marketId": "0x00030df39180df04a873cb4aadc50d4135640af5c858ab637dbd4d31b147478c",
"marketStatus": "active",
"ticker": "Frontrunner Futures: Expires 5.21.2023",
"oracleBase": "FRNT",
"oracleQuote": "USDT",
"oracleType": "pricefeed",
"oracleScaleFactor": 6,
"initialMarginRatio": "0.999999999999999999",
"maintenanceMarginRatio": "0.1",
"quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"quoteTokenMeta": {
"name": "Tether",
"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updatedAt": 1653064108501
},
"makerFeeRate": "0.005",
"takerFeeRate": "0.012",
"serviceProviderFee": "0.4",
"isPerpetual": false,
"minPriceTickSize": "0.000000000000001",
"minQuantityTickSize": "0.0001",
"expiryFuturesMarketInfo": {
"expirationTimestamp": 1684600043,
"settlementPrice": "0"
}
}
]
}
Parameter | Type | Description |
---|---|---|
markets | DerivativeMarketInfo | DerivativeMarketInfo object |
DerivativeMarketInfo
Parameter | Type | Description |
---|---|---|
oracle_quote | String | Oracle quote currency |
oracle_type | String | Oracle Type |
quote_denom | String | Coin denom used for the quote asset |
is_perpetual | Boolean | True if the market is a perpetual swap market |
maker_fee_rate | String | Defines the fee percentage makers pay when trading (in quote asset) |
min_price_tick_size | String | Defines the minimum required tick size for the order's price |
min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity |
oracle_scale_factor | Integer | OracleScaleFactor |
taker_fee_rate | String | Defines the fee percentage takers pay when trading (in quote asset) |
expiry_futures_market_info | Array | ExpiryFuturesMarketInfo object |
initial_margin_ratio | String | Defines the initial margin ratio of a derivative market |
market_status | String | The status of the market (Should be one of: [active paused suspended demolished expired]) |
service_provider_fee | String | Percentage of the transaction fee shared with the service provider |
oracle_base | String | Oracle base currency |
perpetual_market_funding | PerpetualMarketFunding | PerpetualMarketFunding object |
perpetual_market_info | PerpetualMarketInfo | PerpetualMarketInfo object |
ticker | String | The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset |
maintenance_margin_ratio | String | Defines the maintenance margin ratio of a derivative market |
market_id | String | The market ID |
quoteTokenMeta | TokenMeta | TokenMeta object |
PerpetualMarketFunding
Parameter | Type | Description |
---|---|---|
cumulative_funding | String | Defines the cumulative funding of a perpetual market |
cumulative_price | String | Defines the cumulative price for the current hour up to the last timestamp |
last_timestamp | Integer | Defines the last funding timestamp in UNIX seconds |
PerpetualMarketInfo
Parameter | Type | Description |
---|---|---|
hourly_funding_rate_cap | String | Defines the default maximum absolute value of the hourly funding rate |
hourly_interest_rate | String | Defines the hourly interest rate of the perpetual market |
next_funding_timestamp | Integer | Defines the next funding timestamp in UNIX seconds |
funding_interval | Integer | Defines the funding interval in seconds |
TokenMeta
Parameter | Type | Description |
---|---|---|
updated_at | Integer | Token metadata fetched timestamp in UNIX millis |
address | String | Token Ethereum contract address |
decimals | Integer | Token decimals |
logo | String | URL to the logo image |
name | String | Token full name |
symbol | String | Token symbol short name |
StreamMarkets
Stream live updates of derivative markets.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
markets = await client.stream_derivative_markets()
async for market in markets:
print(market)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"}
stream, err := exchangeClient.StreamDerivativeMarket(ctx, marketIds)
if err != nil {
panic(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
panic(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";;
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketIds = ["0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"];
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.derivatives.streamDerivativeMarket(
{
marketIds,
callback: (streamMarket) => {
console.log(protoObjectToJson(streamMarket));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Response Parameters
Streaming Response Example:
market {
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
market_status: "active"
ticker: "BTC/USDT PERP"
oracle_base: "BTC"
oracle_quote: "USDT"
oracle_type: "bandibc"
oracle_scale_factor: 6
initial_margin_ratio: "0.095"
maintenance_margin_ratio: "0.05"
quote_denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
quote_token_meta {
name: "Tether"
address: "0xdAC17F958D2ee523a2206206994597C13D831ec7"
symbol: "USDT"
logo: "https://static.alchemyapi.io/images/assets/825.png"
decimals: 6
updated_at: 1650978923435
}
maker_fee_rate: "0.0005"
taker_fee_rate: "0.0012"
service_provider_fee: "0.4"
is_perpetual: true
min_price_tick_size: "100000"
min_quantity_tick_size: "0.0001"
perpetual_market_info {
hourly_funding_rate_cap: "0.000625"
hourly_interest_rate: "0.00000416666"
next_funding_timestamp: 1652796000
funding_interval: 3600
}
perpetual_market_funding {
cumulative_funding: "7234678245.415396885076050889"
cumulative_price: "6.214149999812187743"
last_timestamp: 1652775381
}
}
operation_type: "update"
timestamp: 1652792406000
{
"market": {
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"market_status": "active",
"ticker": "BTC/USDT PERP",
"oracle_base": "BTC",
"oracle_quote": "USDT",
"oracle_type": "bandibc",
"oracle_scale_factor": 6,
"initial_margin_ratio": "0.095",
"maintenance_margin_ratio": "0.05",
"quote_denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"quote_token_meta": {
"name": "Tether",
"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updated_at": 1650978923435
},
"maker_fee_rate": "0.0005",
"taker_fee_rate": "0.0012",
"service_provider_fee": "0.4",
"is_perpetual": true,
"min_price_tick_size": "100000",
"min_quantity_tick_size": "0.0001",
"perpetual_market_info": {
"hourly_funding_rate_cap": "0.000625",
"hourly_interest_rate": "0.00000416666",
"next_funding_timestamp": 1653040800,
"funding_interval": 3600
},
"perpetual_market_funding": {
"cumulative_funding": "7356035675.459202347630388315",
"cumulative_price": "3.723976370878870887",
"last_timestamp": 1653038971
}
},
"operation_type": "update",
"timestamp": 1653038974000
}
{
"market": {
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"marketStatus": "active",
"ticker": "BTC/USDT PERP",
"oracleBase": "BTC",
"oracleQuote": "USDT",
"oracleType": "bandibc",
"oracleScaleFactor": 6,
"initialMarginRatio": "0.095",
"maintenanceMarginRatio": "0.05",
"quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"quoteTokenMeta": {
"name": "Tether",
"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"symbol": "USDT",
"logo": "https://static.alchemyapi.io/images/assets/825.png",
"decimals": 6,
"updatedAt": 1650978923435
},
"makerFeeRate": "0.0005",
"takerFeeRate": "0.0012",
"serviceProviderFee": "0.4",
"isPerpetual": true,
"minPriceTickSize": "100000",
"minQuantityTickSize": "0.0001",
"perpetualMarketInfo": {
"hourlyFundingRateCap": "0.000625",
"hourlyInterestRate": "0.00000416666",
"nextFundingTimestamp": 1654246800,
"fundingInterval": 3600
},
"perpetualMarketFunding": {
"cumulativeFunding": "8239865636.851083559033030036",
"cumulativePrice": "7.15770685160786651",
"lastTimestamp": 1654246073
}
},
"operationType": "update",
"timestamp": 1654246076000
}
Parameter | Type | Description |
---|---|---|
market | DerivativeMarketInfo | DerivativeMarketInfo object |
DerivativeMarketInfo
Parameter | Type | Description |
---|---|---|
oracle_quote | String | Oracle quote currency |
oracle_type | String | Oracle Type |
quote_denom | String | Coin denom used for the quote asset |
is_perpetual | Boolean | True if the market is a perpetual swap market |
maker_fee_rate | String | Defines the fee percentage makers pay when trading (in quote asset) |
min_price_tick_size | String | Defines the minimum required tick size for the order's price |
min_quantity_tick_size | String | Defines the minimum required tick size for the order's quantity |
oracle_scale_factor | Integer | OracleScaleFactor |
taker_fee_rate | String | Defines the fee percentage takers pay when trading (in quote asset) |
expiry_futures_market_info | Array | ExpiryFuturesMarketInfo object |
initial_margin_ratio | String | Defines the initial margin ratio of a derivative market |
market_status | String | The status of the market (Should be one of: [active paused suspended demolished expired]) |
service_provider_fee | String | Percentage of the transaction fee shared with the service provider |
oracle_base | String | Oracle base currency |
perpetual_market_funding | PerpetualMarketFunding | PerpetualMarketFunding object |
perpetual_market_info | PerpetualMarketInfo | PerpetualMarketInfo object |
ticker | String | The name of the pair in format AAA/BBB, where AAA is the base asset and BBB is the quote asset |
maintenance_margin_ratio | String | Defines the maintenance margin ratio of a derivative market |
market_id | String | The market ID |
quoteTokenMeta | TokenMeta | TokenMeta object |
PerpetualMarketFunding
Parameter | Type | Description |
---|---|---|
cumulative_funding | String | Defines the cumulative funding of a perpetual market |
cumulative_price | String | Defines the cumulative price for the current hour up to the last timestamp |
last_timestamp | Integer | Defines the last funding timestamp in UNIX seconds |
PerpetualMarketInfo
Parameter | Type | Description |
---|---|---|
hourly_funding_rate_cap | String | Defines the default maximum absolute value of the hourly funding rate |
hourly_interest_rate | String | Defines the hourly interest rate of the perpetual market |
next_funding_timestamp | Integer | Defines the next funding timestamp in UNIX seconds |
funding_interval | Integer | Defines the funding interval in seconds |
TokenMeta
Parameter | Type | Description |
---|---|---|
updated_at | Integer | Token metadata fetched timestamp in UNIX millis |
address | String | Token Ethereum contract address |
decimals | Integer | Token decimals |
logo | String | URL to the logo image |
name | String | Token full name |
symbol | String | Token symbol short name |
OrdersHistory
Get orders of a derivative market in all states.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
subaccount_id = "0x1b99514e320ae0087be7f87b1e3057853c43b799000000000000000000000000"
skip = 10
limit = 10
orders = await client.get_historical_derivative_orders(
market_id=market_id,
subaccount_id=subaccount_id,
skip=skip,
limit=limit
)
print(orders)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
subaccount_id | String | Filter by subaccount ID | No |
skip | Integer | Skip the last orders, you can use this to fetch all orders since the API caps at 100 | No |
limit | Integer | Limit the orders returned | No |
direction | String | Filter by direction | No |
is_conditional | String | Search for conditional/non-conditional orders(Should be one of: [true, false]) | No |
start_time | Integer | Search for orders createdAt >= startTime, time in milliseconds | No |
end_time | Integer | Search for orders createdAt <= startTime, time in milliseconds | No |
state | String | The order state (Should be one of: [booked, partial_filled, filled, canceled]) | No |
execution_types | List | The execution of the order (Should be one of: [limit market]) | No |
order_types | List | The order type (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell buy_po sell_po]) | No |
Response Parameters
Response Example:
orders {
order_hash: "0x165224339897b61dfb37b424732e4be4f78dafa7cee8204622e9683aa5fc7522"
market_id: "0x54d4505adef6a5cef26bc403a33d595620ded4e15b9e2bc3dd489b714813366a"
subaccount_id: "0x5ffab11640f42352685c1a35e12500ec983920ae000000000000000000000000"
execution_type: "limit"
order_type: "buy_po"
price: "1281030000"
trigger_price: "0"
quantity: "7"
filled_quantity: "0"
state: "canceled"
created_at: 1665484862242
updated_at: 1665484868636
direction: "buy"
margin: "2241800000"
}
orders {
order_hash: "0x91455da6374636567cf0793a4555c258246627453bdf48b1126e03beae5dcc7d"
market_id: "0x54d4505adef6a5cef26bc403a33d595620ded4e15b9e2bc3dd489b714813366a"
subaccount_id: "0x5ffab11640f42352685c1a35e12500ec983920ae000000000000000000000000"
execution_type: "limit"
order_type: "sell_po"
price: "1283930000"
trigger_price: "0"
quantity: "7"
filled_quantity: "0"
state: "canceled"
created_at: 1665484862242
updated_at: 1665484868636
direction: "sell"
margin: "2246890000"
}
paging {
total: 1000
}
Parameter | Type | Description |
---|---|---|
orders | DerivativeOrderHistory | DerivativeOrderHistory object |
DerivativeOrderHistory
Parameter | Type | Description |
---|---|---|
order_hash | String | Hash of the order |
quantity | String | Quantity of the order |
is_active | Boolean | Indicates if the order is active |
is_reduce_only | Boolean | Indicates if the order is reduce-only |
is_conditional | Boolean | Indicates if the order is conditional |
state | String | Order state (Should be one of: [booked partial_filled filled canceled]) |
trigger_price | String | Trigger price is the trigger price used by stop/take orders |
trigger_at | Integer | Trigger timestamp in UNIX millis |
market_id | String | Derivative Market ID |
created_at | Integer | Order committed timestamp in UNIX millis |
updated_at | Integer | Order updated timestamp in UNIX millis |
price | String | Price of the order |
subaccount_id | String | The subaccountId that this order belongs to |
order_type | String | Order type (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell buy_po sell_po]) |
execution_type | String | The type of the order (Should be one of: [limit market]) |
filled_quantity | String | The amount of the quantity filled |
direction | String | The direction of the order (Should be one of: [buy sell]) |
placed_order_hash | String | Order hash placed upon conditional order trigger |
margin | String | The margin of the order |
StreamOrdersHistory
Stream order updates of a derivative market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
order_side = "sell"
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
orders = await client.stream_historical_derivative_orders(
market_id=market_id
)
async for order in orders:
print(order)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
subaccount_id | String | Filter by subaccount ID | No |
direction | String | Filter by direction (Should be one of: [buy sell]) | No |
state | String | Filter by state (Should be one of: [booked partial_filled filled canceled]) | No |
order_types | List | Filter by order type (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell buy_po sell_po]) | No |
execution_types | List | Filter by execution type (Should be one of: [limit market]) | No |
Response Parameters
Streaming Response Example:
order {
order_hash: "0xfb526d72b85e9ffb4426c37bf332403fb6fb48709fb5d7ca3be7b8232cd10292"
market_id: "0x1c79dac019f73e4060494ab1b4fcba734350656d6fc4d474f6a238c13c6f9ced"
is_active: true
subaccount_id: "0x5ffab11640f42352685c1a35e12500ec983920ae000000000000000000000000"
execution_type: "limit"
order_type: "sell_po"
price: "274310000"
trigger_price: "0"
quantity: "144"
filled_quantity: "0"
state: "booked"
created_at: 1665487076373
updated_at: 1665487076373
direction: "sell"
margin: "3950170000"
}
operation_type: "insert"
timestamp: 1665487078000
Parameter | Type | Description |
---|---|---|
order | DerivativeOrderHistory | DerivativeOrderHistory object |
operation_type | String | Order update type (Should be one of: [insert replace update invalidate]) |
timestamp | Integer | Operation timestamp in UNIX millis |
DerivativeOrderHistory
Parameter | Type | Description |
---|---|---|
order_hash | String | Hash of the order |
quantity | String | Quantity of the order |
is_active | Boolean | Indicates if the order is active |
is_reduce_only | Boolean | Indicates if the order is reduce-only |
is_conditional | Boolean | Indicates if the order is conditional |
state | String | Order state (Should be one of: [booked partial_filled filled canceled]) |
trigger_price | String | Trigger price is the trigger price used by stop/take orders |
trigger_at | Integer | Trigger timestamp in UNIX millis |
market_id | String | Derivative Market ID |
created_at | Integer | Order committed timestamp in UNIX millis |
updated_at | Integer | Order updated timestamp in UNIX millis |
price | String | Price of the order |
subaccount_id | String | The subaccountId that this order belongs to |
order_type | String | Order type (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell buy_po sell_po]) |
execution_type | String | The type of the order (Should be one of: [limit market]) |
filled_quantity | String | The amount of the quantity filled |
direction | String | The direction of the order (Should be one of: [buy sell]) |
placed_order_hash | String | Order hash placed upon conditional order trigger |
margin | String | The margin of the order |
Trades
Get trades of a derivative market.
Trade execution types
- Market for market orders
- limitFill for a resting limit order getting filled by a market order
- LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
- LimitMatchNewOrder for the other way around (new limit order getting matched)
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
trades = await client.get_derivative_trades(
market_id=market_id,
subaccount_id=subaccount_id
)
print(trades)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
spotExchangePB "github.com/InjectiveLabs/sdk-go/exchange/spot_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
req := spotExchangePB.TradesRequest{
MarketId: marketId,
SubaccountId: subaccountId,
}
res, err := exchangeClient.GetSpotTrades(ctx, req)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson, TradeExecutionSide, TradeDirection } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0";
const subaccountId = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000";
const direction = TradeDirection.Buy;
const executionSide = TradeExecutionSide.Maker;
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.spot.fetchTrades(
{
marketId: marketId,
subaccountId: subaccountId,
direction: direction,
executionSide: executionSide,
});
console.log(protoObjectToJson(market));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Conditional |
market_ids | String | Filter by market IDs | Conditional |
subaccount_id | String | Filter by subaccount ID | No |
subaccount_ids | String | Filter by subaccount IDs | No |
execution_side | String | Filter by the execution side of the trade (Should be one of: [maker taker]) | No |
direction | String | Filter by the direction of the trade (Should be one of: [buy sell]) | No |
skip | Integer | Skip the last trades, you can use this to fetch all trades since the API caps at 100 | No |
limit | Integer | Limit the trades returned | No |
start_time | Integer | startTime <= x.executedAt <= endTime | No |
end_time | Integer | endTime >= x.executedAt <= startTime | No |
Response Parameters
Response Example:
trades {
order_hash: "0x33cb4e0af0550b14a92615bd059f46a04d5847cd6c7efb1a604046a3b60c2d25"
subaccount_id: "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
trade_execution_type: "limitMatchRestingOrder"
position_delta {
trade_direction: "sell"
execution_price: "40570100000"
execution_quantity: "0.06"
execution_margin: "2333082000"
}
payout: "2502714419.611037287127629754"
fee: "1217103"
executed_at: 1652775161287
fee_recipient: "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
}
trades {
order_hash: "0x8f7626957f098fcdb6a610e72d85fc84e59d459ff4007018847b2ff200e97f77"
subaccount_id: "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
trade_execution_type: "limitMatchRestingOrder"
position_delta {
trade_direction: "sell"
execution_price: "40570100000"
execution_quantity: "0.05"
execution_margin: "1992390000"
}
payout: "2085595349.675864405939691462"
fee: "1014252.5"
executed_at: 1652775161287
fee_recipient: "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
}
{
"trades": [
{
"order_hash": "0x96453bfbda21b4bd53b3b2b85d510f2fec8a56893e9a142d9f7d32484647bccf",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"trade_execution_type": "market",
"trade_direction": "buy",
"price": {
"price": "0.000000000002305",
"quantity": "1000000000000000000",
"timestamp": 1652809734211
},
"fee": "4610",
"executed_at": 1652809734211,
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
{
"order_hash": "0x2d374994918a86f45f9eca46efbc64d866b9ea1d0c49b5aa0c4a114be3570d05",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"trade_execution_type": "market",
"trade_direction": "sell",
"price": {
"price": "0.000000000001654",
"quantity": "1000000000000000000",
"timestamp": 1652809465316
},
"fee": "3308",
"executed_at": 1652809465316,
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
{
"order_hash": "0x832e8544a047a108a45f712d9cbff8ec1349296e65a3cdc312b374849335ae45",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
"trade_execution_type": "limitFill",
"trade_direction": "sell",
"price": {
"price": "0.00000000002792",
"quantity": "10000000000000000",
"timestamp": 1650974383413
},
"fee": "279.2",
"executed_at": 1650974383413,
"fee_recipient": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
}
]
}
{
"tradesList": [
{
"orderHash": "0x3da3c53a00c28787d614c533b70d0c8c954dfa54a31ce930e58c23ee88e3ea09",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "limitMatchRestingOrder",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "39406400000",
"executionQuantity": "0.02",
"executionMargin": "841900000"
},
"payout": "856231180.396992742528328042",
"fee": "394064",
"executedAt": 1654246304825,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
{
"orderHash": "0x0dfc926924befc45d36a6178501143085a05e2dfb45330a05f57ed16a1b27a82",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "limitMatchRestingOrder",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "39406400000",
"executionQuantity": "0.07",
"executionMargin": "2912938000"
},
"payout": "2996809131.389474598849148143",
"fee": "1379224",
"executedAt": 1654246304825,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
{
"orderHash": "0xcae7168f316a60deaa832eaea99f0ac25a276efbc35913adc74fa64698925422",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "limitMatchRestingOrder",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "40128736026.409431766475",
"executionQuantity": "0.05",
"executionMargin": "2014460000"
},
"payout": "1990739547.202719429741148872",
"fee": "1003218.400660235794161875",
"executedAt": 1654246213333,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
{
"orderHash": "0x11736cd550f7d53db11e89d0ae240a1d5a10aa78b00013a760b32964be15dd6d",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "limitMatchRestingOrder",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "40128736026.409431766475",
"executionQuantity": "0.02",
"executionMargin": "804982000"
},
"payout": "796295818.881087771896459548",
"fee": "401287.36026409431766475",
"executedAt": 1654246213333,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
}
]
}
Parameter | Type | Description |
---|---|---|
trades | DerivativeTrade | DerivativeTrade object |
DerivativeTrade
Parameter | Type | Description |
---|---|---|
executed_at | Integer | Timestamp of trade execution in UNIX millis |
position_delta | PositionDelta | PositionDelta object |
subaccount_id | String | The subaccount ID that executed the trade |
trade_execution_type | String | The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder]) |
fee | String | The fee associated with the trade |
is_liquidation | Boolean | True if the trade is a liquidation |
market_id | String | The market ID |
order_hash | String | The order hash |
payout | String | The payout associated with the trade |
fee_recipient | String | The address that received 40% of the fees |
PositionDelta
Parameter | Type | Description |
---|---|---|
execution_price | String | Execution price of the trade |
execution_quantity | String | Execution quantity of the trade |
trade_direction | String | The direction the trade (Should be one of: [buy sell]) |
execution_margin | String | Execution margin of the trade |
StreamTrades
Stream trades of a derivative market.
Trade execution types
- Market for market orders
- limitFill for a resting limit order getting filled by a market order
- LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
- LimitMatchNewOrder for the other way around (new limit order getting matched)
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_ids = [
"0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3",
"0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff"
]
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
trades = await client.stream_derivative_trades(
market_id=market_ids[0],
subaccount_id=subaccount_id
)
async for trade in trades:
print(trade)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccountId := "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
req := derivativeExchangePB.StreamTradesRequest{
MarketId: marketId,
SubaccountId: subaccountId,
}
stream, err := exchangeClient.StreamDerivativeTrades(ctx, req)
if err != nil {
panic(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
panic(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import {getNetworkInfo, Network} from "@injectivelabs/networks";
import {protoObjectToJson, TradeDirection, TradeExecutionSide} from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";;
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketIds = ["0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"];
const subaccountIds = ["0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"];
const executionSide = TradeExecutionSide.Maker;
const direction = TradeDirection.Buy;
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.derivatives.streamDerivativeTrades(
{
marketIds: marketIds,
subaccountIds: subaccountIds,
executionSide: executionSide,
direction: direction,
pagination: pagination,
callback: (streamDerivativeTrades) => {
console.log(protoObjectToJson(streamDerivativeTrades));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_ids | Array | Filter by an array of market IDs | Conditional |
market_id | String | Filter by market ID | Conditional |
subaccount_ids | Array | Filter by an array of subaccount IDs | Conditional |
subaccount_id | String | Filter by subaccount ID | Conditional |
execution_side | String | Filter by the execution side of the trade (Should be one of: [maker taker]) | No |
direction | String | Filter by the direction of the trade (Should be one of: [buy sell]) | No |
skip | Integer | Skip the last trades, you can use this to fetch all trades since the API caps at 100 | No |
limit | Integer | Limit the trades returned | No |
Response Parameters
Streaming Response Example:
trade {
order_hash: "0xa4906e8dc4247c5b080714aae4cd29d20c78e09979c5f061c69f4b1cadb2e530"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
trade_execution_type: "market"
position_delta {
trade_direction: "buy"
execution_price: "42053654000"
execution_quantity: "1"
execution_margin: "6962400000"
}
payout: "35164524279.16524912591576706"
fee: "50464384.8"
executed_at: 1652793010506
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
}
operation_type: "insert"
timestamp: 1652793013000
{
"trade": {
"order_hash": "0x0403d2e51d73aa1cb46004b16d76279afece9ad14e3784eb93aa6370de466f81",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"trade_execution_type": "limitMatchRestingOrder",
"position_delta": {
"trade_direction": "sell",
"execution_price": "40249100000",
"execution_quantity": "0.06",
"execution_margin": "2388462000"
},
"payout": "0",
"fee": "1207473",
"executed_at": 1653040243183,
"fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
"operation_type": "insert",
"timestamp": 1653040246000
}{
"trade": {
"order_hash": "0x728d69975e4057d1801f1a7031d0ccf7242abacbf73320da55abab677efc2a7e",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"trade_execution_type": "limitMatchRestingOrder",
"position_delta": {
"trade_direction": "sell",
"execution_price": "40249100000",
"execution_quantity": "0.02",
"execution_margin": "779300000"
},
"payout": "0",
"fee": "402491",
"executed_at": 1653040243183,
"fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
"operation_type": "insert",
"timestamp": 1653040246000
}
{
"trade": {
"orderHash": "0xc133f2be809052e24c05132014fc685a0c691e2ac1eacfccc0f52749b20bbfda",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "limitMatchRestingOrder",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "39687300000",
"executionQuantity": "0.01",
"executionMargin": "397675000"
},
"payout": "413013107.353824969334409788",
"fee": "198436.5",
"executedAt": 1654246489592,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
"operationType": "insert",
"timestamp": 1654246493000
}
{
"trade": {
"orderHash": "0xb59e0591c9a6b8edc95c3b1ee21cb37541164e96acbb3253b68fb0a9675a854d",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "limitMatchRestingOrder",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "39687300000",
"executionQuantity": "0.05",
"executionMargin": "1996400000"
},
"payout": "2065065536.76912484667204894",
"fee": "992182.5",
"executedAt": 1654246489592,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
"operationType": "insert",
"timestamp": 1654246493000
}
{
"trade": {
"orderHash": "0x15e0e47533e55b7fe9d8a16053d0d5419b70a8cafac0820cf367f24ecae73eb9",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "limitMatchRestingOrder",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "39687300000",
"executionQuantity": "0.03",
"executionMargin": "1190619000"
},
"payout": "1239039322.061474908003229364",
"fee": "595309.5",
"executedAt": 1654246489592,
"feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
},
"operationType": "insert",
"timestamp": 1654246493000
}
Parameter | Type | Description |
---|---|---|
trade | DerivativeTrade | DerivativeTrade object |
operation_type | String | Executed trades update type (Should be one of: [insert invalidate]) |
timestamp | Integer | Operation timestamp in UNIX millis |
DerivativeTrade
Parameter | Type | Description |
---|---|---|
executed_at | Integer | Timestamp of trade execution in UNIX millis |
position_delta | PositionDelta | PositionDelta object |
subaccount_id | String | The subaccount ID that executed the trade |
trade_execution_type | String | The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder]) |
fee | String | The fee associated with the trade |
is_liquidation | Boolean | True if the trade is a liquidation |
market_id | String | The market ID |
order_hash | String | The order hash |
payout | String | The payout associated with the trade |
fee_recipient | String | The address that received 40% of the fees |
PositionDelta
Parameter | Type | Description |
---|---|---|
execution_price | String | Execution price of the trade |
execution_quantity | String | Execution quantity of the trade |
trade_direction | String | The direction the trade (Should be one of: [buy sell]) |
execution_margin | String | Execution margin of the trade |
Positions
Get the positions of a market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
skip = 10
limit = 10
positions = await client.get_derivative_positions(
market_id=market_id,
subaccount_id=subaccount_id,
skip=skip,
limit=limit
)
print(positions)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
skip := uint64(0)
limit := int32(2)
req := derivativeExchangePB.PositionsRequest{
MarketId: marketId,
Skip: skip,
Limit: limit,
}
res, err := exchangeClient.GetDerivativePositions(ctx, req)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce";
const subaccountId = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000";
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const positions = await exchangeClient.derivatives.fetchPositions(
{
marketId: marketId,
subaccountId: subaccountId,
pagination: pagination,
});
console.log(protoObjectToJson(positions));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | No |
subaccount_id | String | Filter by subaccount ID | No |
skip | Integer | Skip the last positions, you can use this to fetch all positions since the API caps at 100 | No |
limit | Integer | Limit the positions returned | No |
Response Parameters
Response Example:
positions {
ticker: "BTC/USDT PERP"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccount_id: "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
direction: "short"
quantity: "0.2999"
entry_price: "42536400000"
margin: "12756666360"
liquidation_price: "81021714285.714285"
mark_price: "40128736026.4094317665"
aggregate_reduce_only_quantity: "0"
}
{
"positions": [
{
"ticker": "BTC/USDT PERP",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0x306db78bc90ddf11bd917358f48942ccb48f4dc6000000000000000000000000",
"direction": "short",
"quantity": "0.01",
"entry_price": "35187550000",
"margin": "143194359.84865",
"liquidation_price": "47149510461.77619",
"mark_price": "40128736026.4094317665",
"aggregate_reduce_only_quantity": "0"
},
{
"ticker": "BTC/USDT PERP",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"direction": "long",
"quantity": "0.5501",
"entry_price": "38000115954.863590915583488073",
"margin": "20888477638.841827",
"liquidation_price": "29441820.010972",
"mark_price": "40128736026.4094317665",
"aggregate_reduce_only_quantity": "0"
}
]
}
{
"positionsList": [
{
"ticker": "BTC/USDT PERP",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"direction": "short",
"quantity": "1.6321",
"entryPrice": "40673269578.764267860566718788",
"margin": "65479686044.860453741141489314",
"liquidationPrice": "76945874187.425265",
"markPrice": "40128736026.4094317665",
"aggregateReduceOnlyQuantity": "0"
}
]
}
Parameter | Type | Description |
---|---|---|
positions | DerivativePosition | DerivativePosition object |
DerivativePosition
Parameter | Type | Description |
---|---|---|
direction | String | Direction of the position (Should be one of: [long short]) |
market_id | String | The market ID |
subaccount_id | String | The subaccount ID the position belongs to |
ticker | String | Ticker of the derivative market |
aggregate_reduce_only_quantity | String | Aggregate quantity of the reduce-only orders associated with the position |
entry_price | String | Entry price of the position |
liquidation_price | String | Liquidation price of the position |
margin | String | Margin of the position |
mark_price | String | Oracle price of the base asset |
quantity | String | Quantity of the position |
StreamPositions
Stream position updates for a specific market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
positions = await client.stream_derivative_positions(
market_id=market_id,
subaccount_id=subaccount_id
)
async for position in positions:
print(position)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
req := derivativeExchangePB.StreamPositionsRequest{
MarketId: marketId,
}
stream, err := exchangeClient.StreamDerivativePositions(ctx, req)
if err != nil {
panic(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
panic(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";;
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce";
const subaccountId = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000";
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.derivatives.streamDerivativePositions(
{
marketId,
subaccountId,
callback: (streamDerivativePositions) => {
console.log(protoObjectToJson(streamDerivativePositions));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
subaccount_ids | Array | Filter by an array of subaccount IDs | Conditional |
subaccount_id | String | Filter by subaccount ID | Conditional |
Response Parameters
Streaming Response Example:
position {
ticker: "BTC/USDT PERP"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
direction: "short"
quantity: "1.0199"
entry_price: "38378719194.028200611794156506"
margin: "11988891871.766026653636863544"
liquidation_price: "47746368764.216275"
mark_price: "40128736026.4094317665"
aggregate_reduce_only_quantity: "0"
}
timestamp: 1652793296000
{
"position": {
"ticker": "BTC/USDT PERP",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"direction": "short",
"quantity": "0.4499",
"entry_price": "40187334829.308997167725462798",
"margin": "17648170480.844939276952101173",
"liquidation_price": "75632579558.528471",
"mark_price": "40128736026.4094317665",
"aggregate_reduce_only_quantity": "0"
},
"timestamp": 1653039418000
}{
"position": {
"ticker": "BTC/USDT PERP",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"direction": "short",
"quantity": "0.4499",
"entry_price": "40415133266.89312760388339505",
"margin": "17780087110.130349528796488556",
"liquidation_price": "76128781140.582706",
"mark_price": "40128736026.4094317665",
"aggregate_reduce_only_quantity": "0"
},
"timestamp": 1653039464000
}{
"position": {
"ticker": "BTC/USDT PERP",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"direction": "short",
"quantity": "0.4499",
"entry_price": "40306914705.252255649316986606",
"margin": "17654816331.908168110936068341",
"liquidation_price": "75760533574.235878",
"mark_price": "40128736026.4094317665",
"aggregate_reduce_only_quantity": "0"
},
"timestamp": 1653039501000
}
{
"position": {
"ticker": "BTC/USDT PERP",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"direction": "short",
"quantity": "1.6321",
"entryPrice": "40555935751.758890674529114982",
"margin": "65283896141.678537523412631302",
"liquidationPrice": "76719878206.648298",
"markPrice": "40128736026.4094317665",
"aggregateReduceOnlyQuantity": "0"
},
"timestamp": 1654246646000
}
{
"position": {
"ticker": "BTC/USDT PERP",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
"direction": "short",
"quantity": "1.6321",
"entryPrice": "40489113688.030524225816723708",
"margin": "65069810777.851918748331744252",
"liquidationPrice": "76531312698.56045",
"markPrice": "40128736026.4094317665",
"aggregateReduceOnlyQuantity": "0"
},
"timestamp": 1654246687000
}
Parameter | Type | Description |
---|---|---|
positions | DerivativePosition | DerivativePosition object |
timestamp | Integer | Operation timestamp in UNIX millis |
DerivativePosition
Parameter | Type | Description |
---|---|---|
direction | String | Direction of the position (Should be one of: [long short]) |
market_id | String | The market ID |
subaccount_id | String | The subaccount ID the position belongs to |
ticker | String | Ticker of the derivative market |
aggregate_reduce_only_quantity | String | Aggregate quantity of the reduce-only orders associated with the position |
entry_price | String | Entry price of the position |
liquidation_price | String | Liquidation price of the position |
margin | String | Margin of the position |
mark_price | String | Oracle price of the base asset |
quantity | String | Quantity of the position |
Orderbook
Get the orderbook of a derivative market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
market = await client.get_derivative_orderbook(market_id=market_id)
print(market)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
res, err := exchangeClient.GetDerivativeOrderbook(ctx, marketId)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const orderbook = await exchangeClient.derivatives.fetchOrderbook(marketId);
console.log(protoObjectToJson(orderbook));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
Response Parameters
Response Example:
orderbook {
buys {
price: "37640700000"
quantity: "0.1399"
timestamp: 1650974417291
}
buys {
price: "30000000000"
quantity: "1"
timestamp: 1649838645114
}
sells {
price: "42536400000"
quantity: "0.02"
timestamp: 1652668629866
}
sells {
price: "42737100000"
quantity: "0.13"
timestamp: 1652366712839
}
sells {
price: "50000000000"
quantity: "0.01"
timestamp: 1652457633995
}
}
{
"orderbook": {
"buys": [
{
"price": "37640700000",
"quantity": "0.1399",
"timestamp": 1650974417291
},
{
"price": "37520300000",
"quantity": "0.16",
"timestamp": 1651491945818
},
{
"price": "37399900000",
"quantity": "0.15",
"timestamp": 1651491945818
},
{
"price": "30000000000",
"quantity": "1",
"timestamp": 1649838645114
}
],
"sells": [
{
"price": "50000000000",
"quantity": "0.01",
"timestamp": 1652457633995
}
]
}
}
{
"orderbook": {
"buysList": [
{
"price": "39165600000",
"quantity": "0.07",
"timestamp": 1654245802262
},
{
"price": "39085300000",
"quantity": "0.07",
"timestamp": 1654245802262
},
{
"price": "25000000000",
"quantity": "0.1",
"timestamp": 1653932262361
}
],
"sellsList": [
{
"price": "39446500000",
"quantity": "0.07",
"timestamp": 1654246681580
},
{
"price": "40449700000",
"quantity": "0.08",
"timestamp": 1654246681580
},
{
"price": "43058100000",
"quantity": "0.0577",
"timestamp": 1654245756032
},
{
"price": "50000000000",
"quantity": "0.012",
"timestamp": 1653932262361
}
]
}
}
Parameter | Type | Description |
---|---|---|
orderbook | DerivativeLimitOrderbook | DerivativeLimitOrderbook object |
DerivativeLimitOrderbook
Parameter | Type | Description |
---|---|---|
buys | PriceLevel | PriceLevel object |
sells | PriceLevel | PriceLevel object |
PriceLevel
Parameter | Type | Description |
---|---|---|
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
price | String | Price number of the price level |
Orderbooks
Get the orderbook for an array of derivative markets.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_ids = [
"0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3",
"0xd5e4b12b19ecf176e4e14b42944731c27677819d2ed93be4104ad7025529c7ff"
]
markets = await client.get_derivative_orderbooks(market_ids=market_ids)
print(markets)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce", "0x1f73e21972972c69c03fb105a5864592ac2b47996ffea3c500d1ea2d20138717"}
res, err := exchangeClient.GetDerivativeOrderbooks(ctx, marketIds)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketIds = ["0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"];
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const market = await exchangeClient.derivatives.fetchOrderbooks(marketIds);
console.log(protoObjectToJson(market));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_ids | Array | Filter by an array of market IDs | Yes |
Response Parameters
Response Example:
orderbooks: {
market_id: "0x1f73e21972972c69c03fb105a5864592ac2b47996ffea3c500d1ea2d20138717",
orderbook: {
buys: {
price: "13107000",
quantity: "0.3",
timestamp: 1646998496535
},
buys: {
price: "12989000",
quantity: "0.8",
timestamp: 1646998520256
}
}
},
orderbooks: {
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
orderbook: {
buys: {
price: "39873942000",
quantity: "0.1",
timestamp: 1646998535041
},
buys: {
price: "39752458000",
quantity: "0.3",
timestamp: 1646998517630
}
}
}
{
"orderbooks": [
{
"market_id": "0x1f73e21972972c69c03fb105a5864592ac2b47996ffea3c500d1ea2d20138717",
"orderbook": {}
},
{
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"orderbook": {
"buys": [
{
"price": "37640700000",
"quantity": "0.1399",
"timestamp": 1652792829016
},
{
"price": "37520300000",
"quantity": "0.16",
"timestamp": 1652786114544
},
{
"price": "35000000000",
"quantity": "3",
"timestamp": 1649838645114
},
{
"price": "31000000000",
"quantity": "0.01",
"timestamp": 1649838645114
},
{
"price": "30000000000",
"quantity": "1",
"timestamp": 1649838645114
}
],
"sells": [
{
"price": "50000000000",
"quantity": "0.01",
"timestamp": 1652457633995
}
]
}
}
]
}
{
"orderbooksList": [
{
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"orderbook": {
"buysList": [
{
"price": "39767500000",
"quantity": "0.05",
"timestamp": 1654246733424
},
{
"price": "39687300000",
"quantity": "0.08",
"timestamp": 1654246733424
},
{
"price": "25000000000",
"quantity": "0.1",
"timestamp": 1653932262361
}
],
"sellsList": [
{
"price": "40249100000",
"quantity": "0.05",
"timestamp": 1654246769016
},
{
"price": "43539600000",
"quantity": "0.17",
"timestamp": 1654245756032
},
{
"price": "50000000000",
"quantity": "0.012",
"timestamp": 1653932262361
}
]
}
}
]
}
Parameter | Type | Description |
---|---|---|
orderbook | DerivativeLimitOrderbook | DerivativeLimitOrderbook object |
market_id | String | Filter by market ID |
DerivativeLimitOrderbook
Parameter | Type | Description |
---|---|---|
buys | PriceLevel | PriceLevel object |
sells | PriceLevel | PriceLevel object |
PriceLevel
Parameter | Type | Description |
---|---|---|
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
price | String | Price number of the price level |
StreamOrderbooks
Stream orderbook updates for an array of derivative markets.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
markets = await client.stream_derivative_orderbook(market_id=market_id)
async for market in markets:
print(market)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketIds := []string{"0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"}
stream, err := exchangeClient.StreamDerivativeOrderbook(ctx, marketIds)
if err != nil {
panic(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
panic(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";;
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketIds = ["0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"];
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.derivatives.streamDerivativeOrderbook(
{
marketIds,
callback: (streamOrderbook) => {
console.log(protoObjectToJson(streamOrderbook));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_ids | Array | Filter by market IDs | Yes |
Response Parameters
Streaming Response Example:
orderbook {
buys {
price: "37640700000"
quantity: "0.1399"
timestamp: 1652792829016
}
buys {
price: "37520300000"
quantity: "0.16"
timestamp: 1652786114544
}
buys {
price: "35179900000"
quantity: "0.01"
timestamp: 1650974417291
}
sells {
price: "50000000000"
quantity: "0.01"
timestamp: 1652457633995
}
}
operation_type: "update"
timestamp: 1652793515000
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
{
"orderbook": {
"buys": [
{
"price": "40289200000",
"quantity": "0.02",
"timestamp": 1653039106493
},
{
"price": "30000000000",
"quantity": "1",
"timestamp": 1649838645114
}
],
"sells": [
{
"price": "40971400000",
"quantity": "0.01",
"timestamp": 1653039061717
},
{
"price": "41212200000",
"quantity": "0.08",
"timestamp": 1653038883873
},
{
"price": "50000000000",
"quantity": "0.01",
"timestamp": 1652457633995
}
]
},
"operation_type": "update",
"timestamp": 1653039112000,
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
}{
"orderbook": {
"buys": [
{
"price": "39286000000",
"quantity": "0.02",
"timestamp": 1653038931674
},
{
"price": "30000000000",
"quantity": "1",
"timestamp": 1649838645114
}
],
"sells": [
{
"price": "39767500000",
"quantity": "0.01",
"timestamp": 1653039143024
},
{
"price": "40168800000",
"quantity": "0.02",
"timestamp": 1653039143024
},
{
"price": "50000000000",
"quantity": "0.01",
"timestamp": 1652457633995
}
]
},
"operation_type": "update",
"timestamp": 1653039145000,
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
}{
"orderbook": {
"buys": [
{
"price": "40249100000",
"quantity": "0.03",
"timestamp": 1653039193813
},
{
"price": "50000000000",
"quantity": "0.01",
"timestamp": 1652457633995
}
]
},
"operation_type": "update",
"timestamp": 1653039198000,
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
}
{
"orderbook": {
"buysList": [
{
"price": "39767500000",
"quantity": "0.05",
"timestamp": 1654246733424
},
{
"price": "39687300000",
"quantity": "0.08",
"timestamp": 1654246733424
},
{
"price": "25000000000",
"quantity": "0.1",
"timestamp": 1653932262361
}
],
"sellsList": [
{
"price": "40530000000",
"quantity": "0.01",
"timestamp": 1654246681580
},
{
"price": "43539600000",
"quantity": "0.17",
"timestamp": 1654245756032
},
{
"price": "50000000000",
"quantity": "0.012",
"timestamp": 1653932262361
}
]
},
"operationType": "update",
"timestamp": 1654246904000,
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
}
Parameter | Type | Description |
---|---|---|
operation_type | String | Order update type (Should be one of: [insert delete replace update invalidate]) |
orderbook | DerivativeLimitOrderbook | DerivativeLimitOrderbook object |
timestamp | Integer | Operation timestamp in UNIX millis |
market_id | String | Filter by market ID |
DerivativeLimitOrderbook
Parameter | Type | Description |
---|---|---|
buys | PriceLevel | PriceLevel object |
sells | PriceLevel | PriceLevel object |
PriceLevel
Parameter | Type | Description |
---|---|---|
quantity | String | Quantity of the price level |
timestamp | Integer | Price level last updated timestamp in UNIX millis |
price | String | Price number of the price level |
SubaccountOrdersList
Get the derivative orders of a specific subaccount.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
skip = 10
limit = 10
orders = await client.get_derivative_subaccount_orders(
subaccount_id=subaccount_id,
market_id=market_id,
skip=skip,
limit=limit
)
print(orders)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
skip := uint64(0)
limit := int32(2)
req := derivativeExchangePB.SubaccountOrdersListRequest{
MarketId: marketId,
SubaccountId: subaccountId,
Skip: skip,
Limit: limit,
}
res, err := exchangeClient.GetSubaccountDerivativeOrdersList(ctx, req)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const subaccountId = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const marketId = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce";
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const subaccountOrders = await exchangeClient.derivatives.fetchSubaccountOrdersList(
{
subaccountId: subaccountId,
marketId: marketId,
pagination: pagination,
}
);
console.log(protoObjectToJson(subaccountOrders));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
market_id | String | Filter by market ID | No |
skip | Integer | Skip the last orders, you can use this to fetch all orders since the API caps at 100 | No |
limit | Integer | Limit the orders returned | No |
Response Parameters
Response Example:
orders {
order_hash: "0x962af5e492a2ce4575616dbcf687a063ef9c4b33a047a9fb86794804923337c8"
order_side: "buy"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
margin: "35000000000"
price: "35000000000"
quantity: "1"
unfilled_quantity: "1"
trigger_price: "0"
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
state: "booked"
created_at: 1652786114544
updated_at: 1652786114544
}
orders {
order_hash: "0x457aadf92c40e5b2c4c7e6c3176872e72f36e11e7d4e718222b94a08a35ab071"
order_side: "buy"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
margin: "155000000"
price: "31000000000"
quantity: "0.01"
unfilled_quantity: "0.01"
trigger_price: "0"
fee_recipient: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
state: "booked"
created_at: 1652701438661
updated_at: 1652701438661
}
{
"orders": [
{
"order_hash": "0x8af0b619d31acda68d04b8a14e1488eee3c28792ded6fbb7393a489a4a8dbb58",
"order_side": "buy",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"margin": "36000000000",
"price": "36000000000",
"quantity": "1",
"unfilled_quantity": "1",
"trigger_price": "0",
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"created_at": 1652792829016,
"updated_at": 1652792829016
},
{
"order_hash": "0x457aadf92c40e5b2c4c7e6c3176872e72f36e11e7d4e718222b94a08a35ab071",
"order_side": "buy",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"margin": "155000000",
"price": "31000000000",
"quantity": "0.01",
"unfilled_quantity": "0.01",
"trigger_price": "0",
"fee_recipient": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"state": "booked",
"created_at": 1652701438661,
"updated_at": 1652701438661
}
]
}
{
"ordersList": [
{
"orderHash": "0xad5c1943f034b4587f8482b029e97c078848f30acad40bcceab3dc174d62ba40",
"orderSide": "buy",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"isReduceOnly": false,
"margin": "30000000000",
"price": "30000000000",
"quantity": "1",
"unfilledQuantity": "1",
"triggerPrice": "0",
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
"state": "booked",
"createdAt": 1654246251978,
"updatedAt": 1654246251978
}
]
}
Parameter | Type | Description |
---|---|---|
orders | DerivativeLimitOrder | DerivativeLimitOrder object |
DerivativeLimitOrder
Parameter | Type | Description |
---|---|---|
fee_recipient | String | Fee recipient address |
order_hash | String | Hash of the order |
quantity | String | Quantity of the order |
state | String | Order state (Should be one of: [booked partial_filled filled canceled]) |
trigger_price | String | The price used by stop/take orders |
market_id | String | The market ID |
created_at | Integer | Order committed timestamp in UNIX millis |
price | String | Price of the order |
subaccount_id | String | The subaccount ID this order belongs to |
updated_at | Integer | Order updated timestamp in UNIX millis |
is_reduce_only | Boolean | True if the order is a reduce-only order |
margin | String | Margin of the order |
order_side | String | The type of the order (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell]) |
unfilled_quantity | String | The amount of the quantity remaining unfilled |
SubaccountTradesList
Get the derivative trades for a specific subaccount.
Trade execution types
- Market for market orders
- limitFill for a resting limit order getting filled by a market order
- LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
- LimitMatchNewOrder for the other way around (new limit order getting matched)
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
execution_type = "market"
direction = "sell"
skip = 10
limit = 10
trades = await client.get_derivative_subaccount_trades(
subaccount_id=subaccount_id,
market_id=market_id,
execution_type=execution_type,
direction=direction,
skip=skip,
limit=limit
)
print(trades)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
skip := uint64(0)
limit := int32(2)
req := derivativeExchangePB.SubaccountTradesListRequest{
MarketId: marketId,
SubaccountId: subaccountId,
Skip: skip,
Limit: limit,
}
res, err := exchangeClient.GetSubaccountDerivativeTradesList(ctx, req)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson, TradeDirection, TradeExecutionType } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const subaccountId = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const marketId = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce";
const direction = TradeDirection.Buy;
const executionType = TradeExecutionType.Market;
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const subaccountTrades = await exchangeClient.derivatives.fetchSubaccountTradesList(
{
subaccountId: subaccountId,
marketId: marketId,
direction: direction,
executionType: executionType,
pagination: pagination,
}
);
console.log(protoObjectToJson(subaccountTrades));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by Subaccount ID | Yes |
market_id | String | Filter by Market ID | No |
direction | String | Filter by the direction of the trades (Should be one of: [buy sell]) | No |
execution_type | String | Filter by the execution type of the trades (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder]) | No |
skip | Integer | Skip the last trades, you can use this to fetch all trades since the API caps at 100 | No |
limit | Integer | Limit the trades returned | No |
Response Parameters
Response Example:
trades {
order_hash: "0x67e1479e04a050f211dac0e0feeb0b9b6c52d634ecd90f98304ddb07cb7d85cf"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
trade_execution_type: "market"
position_delta {
trade_direction: "sell"
execution_price: "40208900000"
execution_quantity: "0.01"
execution_margin: "400100000"
}
payout: "0"
fee: "482506.8"
executed_at: 1651497909274
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
}
trades {
order_hash: "0xa049d9b5950b5a4a3a1560503ab22e191ad3f03d211629359cbdc844e8a05d91"
subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
trade_execution_type: "market"
position_delta {
trade_direction: "sell"
execution_price: "38221371000"
execution_quantity: "1"
execution_margin: "37732000000"
}
payout: "0"
fee: "45865645.2"
executed_at: 1651491831613
fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
}
{
"trades": [
{
"order_hash": "0xb131b0a095a8e72ad2fe0897001dbf6277f7ee9b8da868a9eedf9814e181da82",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"trade_execution_type": "market",
"position_delta": {
"trade_direction": "buy",
"execution_price": "42710340000",
"execution_quantity": "0.15",
"execution_margin": "0"
},
"payout": "1105814219.16406340684465003",
"fee": "7687861.2",
"executed_at": 1652793510591,
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
{
"order_hash": "0xa049d9b5950b5a4a3a1560503ab22e191ad3f03d211629359cbdc844e8a05d91",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"trade_execution_type": "market",
"position_delta": {
"trade_direction": "sell",
"execution_price": "38221371000",
"execution_quantity": "1",
"execution_margin": "37732000000"
},
"payout": "0",
"fee": "45865645.2",
"executed_at": 1651491831613,
"fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
}
]
}
{
"tradesList": [
{
"orderHash": "0xa84da1f4286c72b38556c751bf572200ae70d2390c5e0be9677d2ae787bea8d8",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "market",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "41951760760",
"executionQuantity": "1",
"executionMargin": "42161500000"
},
"payout": "0",
"fee": "50342112.912",
"executedAt": 1654246228747,
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
{
"orderHash": "0xfa3e2016812532fe1e867557997c27805462d3be3dc0b646f19a1a0a6c172fb8",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "market",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "38965000000",
"executionQuantity": "0.001",
"executionMargin": "28000000"
},
"payout": "36823936.837719129360630081",
"fee": "46758",
"executedAt": 1651517007785,
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
},
{
"orderHash": "0x482966d12d3339cc573f2f9d57aeddf6ece2929933eb26efdeb6dec2a6308b1f",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"tradeExecutionType": "market",
"isLiquidation": false,
"positionDelta": {
"tradeDirection": "buy",
"executionPrice": "41332500000",
"executionQuantity": "0.01",
"executionMargin": "415400000"
},
"payout": "343739533.621037542065851015",
"fee": "495990",
"executedAt": 1651497901928,
"feeRecipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
}
]
}
Parameter | Type | Description |
---|---|---|
trades | DerivativeTrade | DerivativeTrade object |
DerivativeTrade
Parameter | Type | Description |
---|---|---|
executed_at | Integer | Timestamp of trade execution in UNIX millis |
position_delta | PositionDelta | PositionDelta object |
subaccount_id | String | The subaccount ID that executed the trade |
trade_execution_type | String | The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder]) |
fee | String | The fee associated with the trade |
is_liquidation | Boolean | True if the trade is a liquidation |
market_id | String | The market ID |
order_hash | String | The order hash |
payout | String | The payout associated with the trade |
fee_recipient | String | The address that received 40% of the fees |
PositionDelta
Parameter | Type | Description |
---|---|---|
execution_price | String | Execution price of the trade |
execution_quantity | String | Execution quantity of the trade |
trade_direction | String | The direction the trade (Should be one of: [buy sell]) |
execution_margin | String | Execution margin of the trade |
FundingPayments
Get the funding payments for a subaccount.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
skip=0
limit=10
funding = await client.get_funding_payments(
market_id=market_id,
subaccount_id=subaccount_id,
skip=skip,
limit=limit
)
print(funding)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccountId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
req := derivativeExchangePB.FundingPaymentsRequest{
MarketId: marketId,
SubaccountId: subaccountId,
}
res, err := exchangeClient.GetDerivativeFundingPayments(ctx, req)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const subaccountId = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
const marketId = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce";
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const fundingPayments = await exchangeClient.derivatives.fetchFundingPayments(
{
marketId: marketId,
subaccountId: subaccountId,
pagination: pagination,
}
);
console.log(protoObjectToJson(fundingPayments));
})();
Parameter | Type | Description | Required |
---|---|---|---|
subaccount_id | String | Filter by subaccount ID | Yes |
market_id | String | Filter by market ID | No |
skip | Integer | Skip the last funding payments, you can use this to fetch all payments since the API caps at 100 | No |
limit | Integer | Limit the funding payments returned | No |
Response Parameters
Response Example:
payments {
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccount_id: "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
amount: "-5056943.056576"
timestamp: 1652767200634
}
payments {
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccount_id: "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
amount: "-1179953.379867"
timestamp: 1652763601436
}
payments {
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
subaccount_id: "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
amount: "-4888378.288023"
timestamp: 1652760001559
}
{
"payments": [
{
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"amount": "9904406.085347",
"timestamp": 1652511601035
},
{
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"amount": "5811676.298013",
"timestamp": 1652508000824
},
{
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"amount": "6834858.744846",
"timestamp": 1652504401219
}
]
}
{
"paymentsList": [
{
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"amount": "-4895705.795221",
"timestamp": 1654246801786
},
{
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"amount": "-20882.994228",
"timestamp": 1653818400878
},
{
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"subaccountId": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
"amount": "-20882.994228",
"timestamp": 1653814800643
}
]
}
Parameter | Type | Description |
---|---|---|
market_id | String | The market ID |
subaccount_id | String | The subaccount ID |
amount | String | The amount of the funding payment |
timestamp | Integer | Operation timestamp in UNIX millis |
FundingRates
Get the historical funding rates for a specific market.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
market_id = "0x90e662193fa29a3a7e6c07be4407c94833e762d9ee82136a2cc712d6b87d7de3"
skip=0
limit=10
funding_rates = await client.get_funding_rates(
market_id=market_id,
skip=skip,
limit=limit
)
print(funding_rates)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
derivativeExchangePB "github.com/InjectiveLabs/sdk-go/exchange/derivative_exchange_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
panic(err)
}
ctx := context.Background()
marketId := "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
req := derivativeExchangePB.FundingRatesRequest{
MarketId: marketId,
}
res, err := exchangeClient.GetDerivativeFundingRates(ctx, req)
if err != nil {
panic(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const marketId = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce";
const pagination = {
skip: 0,
limit: 10,
key: ""
};
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const fundingRates = await exchangeClient.derivatives.fetchFundingRates(
{
marketId,
pagination: pagination,
}
);
console.log(protoObjectToJson(fundingRates));
})();
Parameter | Type | Description | Required |
---|---|---|---|
market_id | String | Filter by market ID | Yes |
skip | Integer | Skip the last funding rates, you can use this to fetch all funding rates since the API caps at 100 | No |
limit | Integer | Limit the funding rates returned | No |
Response Parameters
Response Example:
funding_rates {
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
rate: "0.000042"
timestamp: 1652763601436
}
funding_rates {
market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
rate: "0.000174"
timestamp: 1652760001559
}
{
"funding_rates": [
{
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"rate": "0.000142",
"timestamp": 1652508000824
},
{
"market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"rate": "0.000167",
"timestamp": 1652504401219
}
]
}
{
"fundingRatesList": [
{
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"rate": "0.000122",
"timestamp": 1654246801786
},
{
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"rate": "0.000109",
"timestamp": 1654243201239
},
{
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"rate": "0.00014",
"timestamp": 1654239601537
},
{
"marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
"rate": "0.000115",
"timestamp": 1654236001211
}
]
}
Parameter | Type | Description |
---|---|---|
market_id | String | The market ID |
rate | String | The funding rate |
timestamp | Integer | Timestamp in UNIX millis |
- InjectiveOracleRPC
InjectiveOracleRPC defines the gRPC API of the Exchange Oracle provider.
OracleList
Get a list with oracles and feeds.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
oracle_list = await client.get_oracle_list()
print(oracle_list)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
res, err := exchangeClient.GetOracleList(ctx)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const oracleList = await exchangeClient.oracle.fetchOracleList(
);
console.log(protoObjectToJson(oracleList));
})();
Response Parameters
Response Example:
oracles {
symbol: "ANC"
oracle_type: "bandibc"
price: "2.212642692"
}
oracles {
symbol: "ATOM"
oracle_type: "bandibc"
price: "24.706861402"
}
{
"oracles": [
{
"symbol": "ANC",
"oracle_type": "bandibc",
"price": "2.212642692"
},
{
"symbol": "ATOM",
"oracle_type": "bandibc",
"price": "24.706861402"
},
{
"symbol": "ZRX",
"oracle_type": "coinbase",
"price": "0.9797"
}
]
}
{
"oraclesList": [
{
"symbol": "ANC",
"baseSymbol": "",
"quoteSymbol": "",
"oracleType": "bandibc",
"price": "2.212642692"
},
{
"symbol": "ATOM",
"baseSymbol": "",
"quoteSymbol": "",
"oracleType": "bandibc",
"price": "24.706861402"
},
{
"symbol": "ZRX",
"baseSymbol": "",
"quoteSymbol": "",
"oracleType": "coinbase",
"price": "0.398902"
}
]
}
Parameter | Type | Description |
---|---|---|
oracles | Oracle | Oracle object |
Oracle
Parameter | Type | Description |
---|---|---|
symbol | String | The symbol of the asset |
oracle_type | String | The oracle provider |
price | String | The price of the asset |
Price
Get the oracle price of an asset.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
base_symbol = 'BTC'
quote_symbol = 'USDT'
oracle_type = 'bandibc'
oracle_scale_factor = 6
oracle_prices = await client.get_oracle_prices(
base_symbol=base_symbol,
quote_symbol=quote_symbol,
oracle_type=oracle_type,
oracle_scale_factor=oracle_scale_factor
)
print(oracle_prices)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
baseSymbol := "BTC"
quoteSymbol := "USDT"
oracleType := "BandIBC"
oracleScaleFactor := uint32(6)
res, err := exchangeClient.GetPrice(ctx, baseSymbol, quoteSymbol, oracleType, oracleScaleFactor)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const baseSymbol = "BTC";
const quoteSymbol = "USDT";
const oracleType = "bandibc";
const oracleScaleFactor = 6;
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const oraclePrice = await exchangeClient.oracle.fetchOraclePrice(
{
baseSymbol,
quoteSymbol,
oracleType,
oracleScaleFactor
}
);
console.log(protoObjectToJson(oraclePrice));
})();
Parameter | Type | Description | Required |
---|---|---|---|
base_symbol | String | Oracle base currency | Yes |
quote_symbol | String | Oracle quote currency | Yes |
oracle_type | String | The oracle provider | Yes |
oracle_scale_factor | Integer | Oracle scale factor for the quote asset | Yes |
Response Parameters
Response Example:
price: "40128736026.4094317665"
{
"price": "40128736026.4094317665"
}
{
"price": "40128736026.4094317665"
}
Parameter | Type | Description |
---|---|---|
price | String | The price of the oracle asset |
StreamPrices
Stream oracle prices for an asset.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
base_symbol = 'BTC'
quote_symbol = 'USDT'
oracle_type = 'bandibc'
oracle_prices = await client.stream_oracle_prices(
base_symbol=base_symbol,
quote_symbol=quote_symbol,
oracle_type=oracle_type
)
async for oracle in oracle_prices:
print(oracle)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
baseSymbol := "BTC"
quoteSymbol := "USDT"
oracleType := "BandIBC"
stream, err := exchangeClient.StreamPrices(ctx, baseSymbol, quoteSymbol, oracleType)
if err != nil {
fmt.Println(err)
}
for {
select {
case <-ctx.Done():
return
default:
res, err := stream.Recv()
if err != nil {
fmt.Println(err)
return
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
}
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcStreamClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcStreamClient";;
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const baseSymbol = "BTC";
const quoteSymbol = "USDT";
const oracleType = "bandibc";
const exchangeClient = new ExchangeGrpcStreamClient(
network.exchangeApi
);
await exchangeClient.oracle.streamOraclePrices(
{
oracleType,
baseSymbol,
quoteSymbol,
callback: (streamPrices) => {
console.log(protoObjectToJson(streamPrices));
},
onEndCallback: (status) => {
console.log("Stream has ended with status: " + status);
},
});
})();
Parameter | Type | Description | Required |
---|---|---|---|
base_symbol | String | Oracle base currency | Yes |
quote_symbol | String | Oracle quote currency | Yes |
oracle_type | String | The oracle provider | Yes |
Response Parameters
Streaming Response Example:
price: "40128.7360264094317665"
timestamp: 1652808740072
{
"price": "40128.7360264094317665",
"timestamp": 1653038843915
}
{
"price": "40128.7360264094317665",
"timestamp": 1654180847704
}
Parameter | Type | Description |
---|---|---|
price | String | The price of the oracle asset |
timestamp | Integer | Operation timestamp in UNIX millis. |
- InjectiveInsuranceRPC
InjectiveInsuranceRPC defines the gRPC API of the Insurance Exchange provider.
InsuranceFunds
Get all the insurance funds.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
insurance_funds = await client.get_insurance_funds()
print(insurance_funds)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
insurancePB "github.com/InjectiveLabs/sdk-go/exchange/insurance_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
req := insurancePB.FundsRequest{}
res, err := exchangeClient.GetInsuranceFunds(ctx, req)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const insuranceFunds = await exchangeClient.insuranceFund.fetchInsuranceFunds(
);
console.log(protoObjectToJson(insuranceFunds))
})();
Response Parameters
Response Example:
funds {
market_ticker: "OSMO/UST PERP"
market_id: "0x8c7fd5e6a7f49d840512a43d95389a78e60ebaf0cde1af86b26a785eb23b3be5"
deposit_denom: "ibc/B448C0CA358B958301D328CCDC5D5AD642FC30A6D3AE106FF721DB315F3DDE5C"
pool_token_denom: "share19"
redemption_notice_period_duration: 1209600
balance: "1000000"
total_share: "1000000000000000000"
oracle_base: "OSMO"
oracle_quote: "UST"
oracle_type: "bandibc"
}
{
"funds": [
{
"market_ticker": "OSMO/UST PERP",
"market_id": "0x8c7fd5e6a7f49d840512a43d95389a78e60ebaf0cde1af86b26a785eb23b3be5",
"deposit_denom": "ibc/B448C0CA358B958301D328CCDC5D5AD642FC30A6D3AE106FF721DB315F3DDE5C",
"pool_token_denom": "share19",
"redemption_notice_period_duration": 1209600,
"balance": "1000000",
"total_share": "1000000000000000000",
"oracle_base": "OSMO",
"oracle_quote": "UST",
"oracle_type": "bandibc"
}
]
}
{
"fundsList": [
{
"marketTicker": "OSMO/UST PERP",
"marketId": "0x8c7fd5e6a7f49d840512a43d95389a78e60ebaf0cde1af86b26a785eb23b3be5",
"depositDenom": "ibc/B448C0CA358B958301D328CCDC5D5AD642FC30A6D3AE106FF721DB315F3DDE5C",
"poolTokenDenom": "share19",
"redemptionNoticePeriodDuration": 1209600,
"balance": "6000000",
"totalShare": "6000000000000000000",
"oracleBase": "OSMO",
"oracleQuote": "UST",
"oracleType": "bandibc",
"expiry": 0
},
{
"marketTicker": "Frontrunner Futures: Expires 5.21.2022",
"marketId": "0xeb0964ef12b4bde6febd99a44b562e4f4301ec69a4052e63b6aac73fa6e5e1d0",
"depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"poolTokenDenom": "share20",
"redemptionNoticePeriodDuration": 1209600,
"balance": "10000000",
"totalShare": "1000000000000000000",
"oracleBase": "FRNT",
"oracleQuote": "USDT",
"oracleType": "pricefeed",
"expiry": 1653147605
},
{
"marketTicker": "Frontrunner Futures: Expires 5.21.2023",
"marketId": "0x00030df39180df04a873cb4aadc50d4135640af5c858ab637dbd4d31b147478c",
"depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"poolTokenDenom": "share21",
"redemptionNoticePeriodDuration": 1209600,
"balance": "10000000",
"totalShare": "1000000000000000000",
"oracleBase": "FRNT",
"oracleQuote": "USDT",
"oracleType": "pricefeed",
"expiry": 1684600043
},
{
"marketTicker": "BTC/USDT PERP",
"marketId": "0x784cf40cff2d3cc60ee12fd707af460e49e2a5f8d1b4b8097395deb7d60d39f3",
"depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"poolTokenDenom": "share22",
"redemptionNoticePeriodDuration": 1209600,
"balance": "20000000000",
"totalShare": "1000000000000000000",
"oracleBase": "BTC",
"oracleQuote": "USDT",
"oracleType": "bandibc",
"expiry": 0
},
{
"marketTicker": "ETH/USDT PERP",
"marketId": "0x54d4505adef6a5cef26bc403a33d595620ded4e15b9e2bc3dd489b714813366a",
"depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"poolTokenDenom": "share23",
"redemptionNoticePeriodDuration": 1209600,
"balance": "20000000000",
"totalShare": "1000000000000000000",
"oracleBase": "ETH",
"oracleQuote": "USDT",
"oracleType": "bandibc",
"expiry": 0
},
{
"marketTicker": "BNB/USDT PERP",
"marketId": "0x1c79dac019f73e4060494ab1b4fcba734350656d6fc4d474f6a238c13c6f9ced",
"depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"poolTokenDenom": "share24",
"redemptionNoticePeriodDuration": 1209600,
"balance": "20000000000",
"totalShare": "1000000000000000000",
"oracleBase": "BNB",
"oracleQuote": "USDT",
"oracleType": "bandibc",
"expiry": 0
},
{
"marketTicker": "INJ/USDT PERP",
"marketId": "0x9b9980167ecc3645ff1a5517886652d94a0825e54a77d2057cbbe3ebee015963",
"depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"poolTokenDenom": "share25",
"redemptionNoticePeriodDuration": 1209600,
"balance": "20000000000",
"totalShare": "1000000000000000000",
"oracleBase": "INJ",
"oracleQuote": "USDT",
"oracleType": "bandibc",
"expiry": 0
},
{
"marketTicker": "LUNA/UST PERP",
"marketId": "0x8158e603fb80c4e417696b0e98765b4ca89dcf886d3b9b2b90dc15bfb1aebd51",
"depositDenom": "ibc/B448C0CA358B958301D328CCDC5D5AD642FC30A6D3AE106FF721DB315F3DDE5C",
"poolTokenDenom": "share26",
"redemptionNoticePeriodDuration": 1209600,
"balance": "20000000000",
"totalShare": "1000000000000000000",
"oracleBase": "LUNA",
"oracleQuote": "UST",
"oracleType": "bandibc",
"expiry": 0
}
]
}
Parameter | Type | Description |
---|---|---|
funds | InsuranceFund | InsuranceFund object |
InsuranceFund
Parameter | Type | Description |
---|---|---|
oracle_type | String | Oracle Type |
pool_token_denom | String | Pool token denom |
total_share | String | Total share |
balance | String | The balance |
oracle_base | String | Oracle base currency |
market_id | String | The market ID |
market_ticker | String | Ticker of the derivative market |
oracle_quote | String | Oracle quote currency |
redemption_notice_period_duration | Integer | Redemption notice period duration in seconds |
deposit_denom | String | Coin denom used to underwrite the insurance fund |
Redemptions
Get the pending redemptions.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
redeemer = "inj1gxqdj76ul07w4ujsl8403nhhzyvug2h66qk057"
redemption_denom = "share2"
status = "disbursed"
insurance_redemptions = await client.get_redemptions(
redeemer=redeemer,
redemption_denom=redemption_denom,
status=status
)
print(insurance_redemptions)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
insurancePB "github.com/InjectiveLabs/sdk-go/exchange/insurance_rpc/pb"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
req := insurancePB.RedemptionsRequest{}
res, err := exchangeClient.GetRedemptions(ctx, req)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const denom = "share25";
const address = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku";
const status = "pending";
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const redemptions = await exchangeClient.insuranceFund.fetchRedemptions(
{
denom,
address,
status
}
);
console.log(protoObjectToJson(redemptions))
})();
Parameter | Type | Description | Required |
---|---|---|---|
redeemer | String | Filter by account address | No |
redemption_denom | String | Filter by insurance pool denom | No |
status | String | Filter by redemption status (Should be one of: [disbursed pending]) | No |
Response Parameters
Response Example:
redemption_schedules: {
redemption_id: 1,
status: "disbursed",
redeemer: "inj17ruhpkury0n9el2azce32cucvgql43eresspnp",
claimable_redemption_time: 1627450463607000,
redemption_amount: "10000000000000000000",
redemption_denom: "share1",
requested_at: 1626240863607000,
disbursed_amount: "50000000",
disbursed_denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
disbursed_at: 1627450465211000
},
redemption_schedules: {
redemption_id: 2,
status: "disbursed",
redeemer: "inj1g6grlgchxw95mxc5c3949ygw75hqpghqhgkj0k",
claimable_redemption_time: 1628874830848000,
redemption_amount: "960000000000000000",
redemption_denom: "share1",
requested_at: 1627665230848000,
disbursed_amount: "4800000",
disbursed_denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
disbursed_at: 1628874832996000
}
{
"redemption_schedules": [
{
"redemption_id": 1,
"status": "pending",
"redeemer": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"claimable_redemption_time": 1654247935923000,
"redemption_amount": "1000000000000000000",
"redemption_denom": "share19",
"requested_at": 1653038335923000
}
]
}
{
"redemptionSchedulesList": [
{
"redemptionId": 2,
"status": "pending",
"redeemer": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"claimableRedemptionTime": 1655446154111000,
"redemptionAmount": "100000000000000000",
"redemptionDenom": "share25",
"requestedAt": 1654236554111000,
"disbursedAmount": "",
"disbursedDenom": "",
"disbursedAt": 0
}
]
}
Parameter | Type | Description |
---|---|---|
redemption_schedules | RedemptionSchedule | RedemptionSchedule object |
RedemptionSchedule
Parameter | Type | Description |
---|---|---|
claimable_redemption_time | Integer | Claimable redemption time in seconds |
redeemer | String | Account address of the redemption owner |
redemption_denom | String | Pool token denom being redeemed |
requested_at | Integer | Redemption request time in unix milliseconds |
status | String | Status of the redemption (Should be one of: [disbursed pending]) |
redemption_amount | String | Amount of pool tokens being redeemed |
redemption_id | Integer | Redemption ID |
disbursed_amount | String | Amount of quote tokens disbursed |
disbursed_at | Integer | Redemption disbursement time in unix milliseconds |
disbursed_denom | String | Denom of the quote tokens disbursed |
- InjectiveAuctionRPC
InjectiveAuctionRPC defines the gRPC API of the Auction provider.
Auction
Get the details of a specific auction.
Request Parameters
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
bid_round = 12
auction = await client.get_auction(bid_round=bid_round)
print(auction)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
round := int64(13534)
res, err := exchangeClient.GetAuction(ctx, round)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const round = 19532;
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const auction = await exchangeClient.auction.fetchAuction(round);
console.log(protoObjectToJson(auction));
})();
Parameter | Type | Description | Required |
---|---|---|---|
bid_round | Integer | The auction round | Yes |
Response Parameters
Response Example:
auction: {
winner: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
basket: {
denom: "peggy0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
amount: "300100663"
},
basket: {
denom: "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
amount: "8084075059004"
},
winning_bid_amount: "1000000000000000000000",
round: 12,
end_timestamp: 1639999020325,
updated_at: 1639999022779,
},
bids: {
bidder: "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
amount: "1000000000000000000000",
timestamp: 1640000366576
}
{
"auction": {
"basket": [
{
"denom": "ibc/B448C0CA358B958301D328CCDC5D5AD642FC30A6D3AE106FF721DB315F3DDE5C",
"amount": "20541163349"
},
{
"denom": "peggy0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
"amount": "3736040925000000"
},
{
"denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"amount": "383119139180"
}
],
"round": 13534,
"end_timestamp": 1650635285000,
"updated_at": 1650978958302
}
}
{
"auction": {
"winner": "",
"basketList": [
{
"denom": "ibc/B448C0CA358B958301D328CCDC5D5AD642FC30A6D3AE106FF721DB315F3DDE5C",
"amount": "203444237"
},
{
"denom": "peggy0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"amount": "4062154364"
},
{
"denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
"amount": "5440816238"
}
],
"winningBidAmount": "",
"round": 19532,
"endTimestamp": 1654234085000,
"updatedAt": 1654233490496
},
"bidsList": [
{
"bidder": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"amount": "1000000000000000000",
"timestamp": 1654233511715
},
{
"bidder": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku",
"amount": "3000000000000000000",
"timestamp": 1654233530633
}
]
}
Parameter | Type | Description |
---|---|---|
auction | Auction | Auction object |
bids | Bids | Bids object |
Auction
Parameter | Type | Description |
---|---|---|
winner | String | The Injective Chain address with the highest bid |
basket | Basket | Basket object |
winning_bid_amount | String | The highest bid |
round | Integer | The auction round |
end_timestamp | Integer | The auction's ending timestamp |
updated_at | Integer | The timestamp of the last submitted bid |
Bids
Parameter | Type | Description |
---|---|---|
bidder | String | The Injective Chain address |
amount | String | The bid amount |
timestamp | Integer | The timestamp at which the bid was submitted |
Basket
Parameter | Type | Description |
---|---|---|
denom | String | Token denominator |
amount | String | Token quantity |
Auctions
Get the details of previous auctions.
Request Example:
import asyncio
import logging
from pyinjective.async_client import AsyncClient
from pyinjective.constant import Network
async def main() -> None:
# select network: local, testnet, mainnet
network = Network.testnet()
client = AsyncClient(network, insecure=False)
auctions = await client.get_auctions()
print(auctions)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
asyncio.get_event_loop().run_until_complete(main())
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/InjectiveLabs/sdk-go/client/common"
exchangeclient "github.com/InjectiveLabs/sdk-go/client/exchange"
)
func main() {
//network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
exchangeClient, err := exchangeclient.NewExchangeClient(network.ExchangeGrpcEndpoint, common.OptionTLSCert(network.ExchangeTlsCert))
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
res, err := exchangeClient.GetAuctions(ctx)
if err != nil {
fmt.Println(err)
}
str, _ := json.MarshalIndent(res, "", " ")
fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson } from "@injectivelabs/sdk-ts";
import { ExchangeGrpcClient } from "@injectivelabs/sdk-ts/dist/client/exchange/ExchangeGrpcClient";
(async () => {
const network = getNetworkInfo(Network.TestnetK8s);
const exchangeClient = new ExchangeGrpcClient(
network.exchangeApi
);
const auction = await exchangeClient.auction.fetchAuctions();
console.log(protoObjectToJson(auction));
})();
Response Parameters
Response Example:
auctions: {
winner: "inj14au322k9munkmx5wrchz9q30juf