NAV
Python Golang TypeScript

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

InjectiveLabs/sdk-python.

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

InjectiveLabs/sdk-go.

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:

  1. The Injective Chain node (the Chain API)
  2. The Injective Exchange API

The trading lifecycle is as follows:

  1. First, traders cryptographically sign a transaction containing one or more order messages (e.g. MsgBatchCreateDerivativeLimitOrders, MsgCreateSpotMarketOrder, MsgCancelDerivativeLimitOrder, etc. ).
  2. Then the transaction is broadcasted to an Injective Chain node.
  3. The transaction is then added to the mempool and becomes included in a block. More details on this process can be found here.
  4. 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.
  5. 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.
  6. The funds are settled accordingly, with positions being created for derivative trades and assets being swapped for spot trades.
  7. Events containing the trade and settlement information are emitted by the Chain.
  8. The Injective Exchange API backend indexes the events and pushes updates to all subscribed traders.

Key Differences To CEX

To summarize the sequence of state changes on the Injective Chain:

  1. Mempool: A queue of pending transactions.
  2. 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).
  3. Handler: Code that is executed when a transaction is included in a block.
  4. 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:

  1. 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.
  2. 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.

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:

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:

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.

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

  1. partially closed
  2. fully closed
  3. 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:

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

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

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

→ 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:

Adding a Spot Market Sell Order

→ 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:

Adding a Spot Limit Buy Order

→ 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:

If Matched Immediately: (assuming an FBA clearing price of 1,900 USDT)

If Filled Later By Market Order:

Adding a Spot Limit Sell Order

→ 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:

If Matched Immediately: (assuming an FBA clearing price of 2,100 USDT)

If Filled Later By Market Order:

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

→ 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):

If Matched:

Assuming:

Would result in:

1. Closing existing position with proportional order margin for closing:

2. Opening new position in opposite direction:

3. Refunding fee difference from order price vs. clearing price:

Market Order Matching

Existing Orderbook

Sells Buys
PriceQuantity
$64,3900.3 BTC
$64,3700.2 BTC
$64,3600.5 BTC
PriceQuantity
$64,2100.1 BTC
$64,2050.4 BTC
$64,2000.2 BTC

New Orders

Resulting Orderbook

Sells Buys
PriceQuantity
$64,3900.3 BTC
$64,3700.2 BTC
PriceQuantity
$64,2050.2 BTC
$64,2000.2 BTC

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
PriceQuantity
$64,3900.3 BTC
$64,3700.2 BTC
$64,3600.5 BTC
PriceQuantity
$64,2100.1 BTC
$64,2050.3 BTC
$64,2000.2 BTC

New Orders

Sells Buys
PriceQuantity
$64,2000.1 BTC
$64,1800.2 BTC
PriceQuantity
$64,3700.4 BTC
$64,3600.2 BTC

Matching Orders

All new orders are incorporated into the existing orderbook. In our case this results in a negative spread:

Sells Buys
PriceQuantity
$64,3900.3 BTC
$64,3700.2 BTC
$64,3600.5 BTC
$64,2000.1 BTC
$64,1800.2 BTC
PriceQuantity
$64,3700.4 BTC
$64,3600.1 BTC
$64,2100.1 BTC
$64,2050.3 BTC
$64,2000.2 BTC

As long as negative spread exists, orders are matched against each other. The first buy order is fully matched:

Sells Buys
PriceQuantity
$64,3900.3 BTC
$64,3700.2 BTC
$64,3600.4 BTC
PriceQuantity
$64,3600.1 BTC
$64,2100.1 BTC
$64,2050.3 BTC
$64,2000.2 BTC

Now the second buy order can still be fully matched:

Sells Buys
PriceQuantity
$64,3900.3 BTC
$64,3700.2 BTC
$64,3600.3 BTC
PriceQuantity
$64,2100.1 BTC
$64,2050.3 BTC
$64,2000.2 BTC

This is the end of the matching, since no more negative spread exists (64,360 > 62,210).

All orders will be matched with a clearing price of

for a total quantity of 0.5 BTC. In edge cases where this clearing price violates any order price, it is instead calculated as the average of the last matched order on buy and sell side.

Swagger

A REST interface for state queries, legacy transactions

Swagger Mainnet

Swagger Testnet

Explorer

A Web interface that allows you to search for information on the Injective Chain

Explorer Mainnet

Explorer Testnet

Faucet

A web-based service that provides free tokens to users on testnet and allows them to experiment on the Injective Chain.

Faucet

Exchange API

The Exchange 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 Exchange API which reconstructs state from events emitted by chain.

On a high-level the end-user trading applications and Injective Products use the Exchange 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 Exchange 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"] # Enum with values "withdraw", "deposit", "internal", "external"
    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 = "inj1uzg3kpezm8ju70qd0twr8eh20zph2jt8dh0p6a"
    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 = "0x0511ddc4e6586f3bfe1acb2dd905f8b8a82c97e1edaef654b12ca7e6031ca0fa"
    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"  # active, paused, suspended, demolished or expired
    base_denom = "inj"
    quote_denom = "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
    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

Orders

Get orders 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 = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    order_side = "buy" # buy or sell
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    skip = 10
    limit = 2
    orders = await client.get_spot_orders(
        market_id=market_id,
        order_side=order_side,
        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())
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"
  skip := uint64(0)
  limit := int32(2)

  req := spotExchangePB.OrdersRequest{
    MarketId: marketId,
    Skip:     skip,
    Limit:    limit,
  }

  res, err := exchangeClient.GetSpotOrders(ctx, req)
  if err != nil {
    fmt.Println(err)
  }

  str, _ := json.MarshalIndent(res, "", " ")
  fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson, SpotOrderSide } 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 orderSide = SpotOrderSide.Buy;
  const pagination = {
    skip: 0,
    limit: 10,
    key: ""
  };

  const exchangeClient = new ExchangeGrpcClient(
    network.exchangeApi
  );

  const market = await exchangeClient.spot.fetchOrders(
    {
      marketId: marketId,
      subaccountId: subaccountId,
      orderSide: orderSide,
      pagination: pagination,
    }
  );

  console.log(protoObjectToJson(market));
})();
Parameter Type Description Required
market_id String Filter by market ID Yes
order_side String Filter by order side (Should be one of: [buy sell]) No
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

Response Parameters

Response Example:

orders {
  order_hash: "0xbad0d22c46e76a8569092617bae2e5d95a2a086b2a70e270c6f16fd8e025d83e"
  order_side: "buy"
  market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
  subaccount_id: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
  price: "0.0000000000012"
  quantity: "3000000000000000000"
  unfilled_quantity: "3000000000000000000"
  trigger_price: "0"
  fee_recipient: "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8"
  state: "booked"
  created_at: 1652809260554
  updated_at: 1652809260554
}
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": "0xbf5cf18a5e73c61d465a60ca550c5fbe0ed37b9ca0a49f7bd1de012e983fe55e",
   "order_side": "sell",
   "market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
   "subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
   "price": "0.000000000002305",
   "quantity": "30000000000000000000",
   "unfilled_quantity": "28000000000000000000",
   "trigger_price": "0",
   "fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
   "state": "partial_filled",
   "created_at": 1652774849587,
   "updated_at": 1652809734211
  },
  {
   "order_hash": "0xd86f3a01d291b15294f25c9463fd51cf6b8883776ae7911da3fbd967faa69ea4",
   "order_side": "buy",
   "market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
   "subaccount_id": "0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000000",
   "price": "0.000000000000001",
   "quantity": "1000000000000000",
   "unfilled_quantity": "1000000000000000",
   "trigger_price": "0",
   "fee_recipient": "inj17vytdwqczqz72j65saukplrktd4gyfme5agf6c",
   "state": "booked",
   "created_at": 1649838645114,
   "updated_at": 1649838645114
  }
 ]
}
{
  "ordersList": [
    {
      "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
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])
state String The state of the order (Should be one of: [booked partial_filled filled canceled])
subaccount_id String The subaccount ID this order belongs to
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. This will be 0 if the trigger price is not set
created_at Integer Order committed timestamp in UNIX millis

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:
    network = Network.testnet()
    client = AsyncClient(network, insecure=False)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    subaccount_id = "0xed8c4C43E03E24b7F12975472da771Ce2f8b857c000000000000000000000000"
    skip = 10
    limit = 2
    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
order_type String Filter by order type No
direction String Filter by direction No
start_time Integer Search for orders createdAt >= startTime, time in millisecond No
end_time Integer Search for orders createdAt <= startTime, time in millisecond No

Response Parameters

Response Example:

orders {
  order_hash: "0x5978bcee7098a4dcf0199c69e96127e1946d8345b7a30a60ee11dfa651f04ef9"
  market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
  subaccount_id: "0xed8c4c43e03e24b7f12975472da771ce2f8b857c000000000000000000000000"
  execution_type: "limit"
  order_type: "sell"
  price: "0.000000000002128"
  trigger_price: "0"
  quantity: "51761000000000000000"
  filled_quantity: "0"
  state: "canceled"
  created_at: 1660246239165
  updated_at: 1660246243667
  direction: "sell"
}
orders {
  order_hash: "0x75a1153a1eaf1e929007fd12fcc388d328f9abcbb9425687c835011575d90dab"
  market_id: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
  subaccount_id: "0xed8c4c43e03e24b7f12975472da771ce2f8b857c000000000000000000000000"
  execution_type: "limit"
  order_type: "sell"
  price: "0.000000000002128"
  trigger_price: "0"
  quantity: "258806000000000000000"
  filled_quantity: "0"
  state: "canceled"
  created_at: 1660246239165
  updated_at: 1660246243667
  direction: "sell"
}



Parameter Type Description
orders Order Order object

Order

Parameter Type Description
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 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
price String Price of the order
subaccount_id String The subaccountId that this order belongs to
updated_at Integer Order updated timestamp in UNIX millis.
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])

StreamOrders

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:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = AsyncClient(network, insecure=False)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    order_side = "sell"  # sell or buy
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    orders = await client.stream_spot_orders(
        market_id=market_id,
        order_side=order_side,
        subaccount_id=subaccount_id
    )
    async for order in orders:
        print(order)

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"
  orderSide := "buy"

  req := spotExchangePB.StreamOrdersRequest{
    MarketId:     marketId,
    SubaccountId: subaccountId,
    OrderSide:    orderSide,
  }
  stream, err := exchangeClient.StreamSpotOrders(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, SpotOrderSide } 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 orderSide = SpotOrderSide.Buy;

  const exchangeClient = new ExchangeGrpcStreamClient(
    network.exchangeApi
  );

  await exchangeClient.spot.streamSpotOrders(
    {
      marketId,
      orderSide,
      subaccountId,
      callback: (streamSpotOrders) => {
        console.log(protoObjectToJson(streamSpotOrders));
      },
      onEndCallback: (status) => {
        console.log("Stream has ended with status: " + status);
      },
    });
})();
Parameter Type Description Required
market_id String Filter by market ID Yes
order_side String Filter by order side (Should be one of: [buy sell]) No
subaccount_id String Filter by subaccount ID No

Response Parameters

Streaming Response Example:

order {
  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
}
operation_type: "insert"
timestamp: 1652809321000
{
 "order": {
  "order_hash": "0x07c8064b1d8875c75d81d9770dd5508d3d97fd2bafc67a6213448a4479753cda",
  "order_side": "buy",
  "market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
  "subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
  "price": "0.0000000000015",
  "quantity": "1000000000000000000",
  "unfilled_quantity": "1000000000000000000",
  "trigger_price": "0",
  "fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
  "state": "booked",
  "created_at": 1653041941027,
  "updated_at": 1653041941027
 },
 "operation_type": "insert",
 "timestamp": 1653041948000
}{
 "order": {
  "order_hash": "0xacb6fd422effd0d9f06dfd373d742a0d24a3c862384a2e9736fc52d2221f9cc4",
  "order_side": "buy",
  "market_id": "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
  "subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
  "price": "0.000000000001",
  "quantity": "2000000000000000000",
  "unfilled_quantity": "2000000000000000000",
  "trigger_price": "0",
  "fee_recipient": "inj1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8dkncm8",
  "state": "booked",
  "created_at": 1653041984130,
  "updated_at": 1653041984130
 },
 "operation_type": "insert",
 "timestamp": 1653041988000
}
{
  "order": {
    "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
  },
  "operationType": "insert",
  "timestamp": 1654079385000
}
{
  "order": {
    "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
  },
  "operationType": "insert",
  "timestamp": 1654079412000
}
Parameter Type Description
order SpotLimitOrder SpotLimitOrder object
operation_type String Order update type (Should be one of: [insert replace update invalidate])
timestamp Integer Operation timestamp in UNIX millis

SpotLimitOrder

Parameter Type Description
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])
state String The state of the order (Should be one of: [booked partial_filled filled canceled])
subaccount_id String The subaccount ID this order belongs to
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. This will be 0 if the trigger price is not set
created_at Integer Order committed timestamp in UNIX millis

Trades

Get trades of a spot market.

Trade execution types

  1. Market for market orders
  2. limitFill for a resting limit order getting filled by a market order
  3. LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
  4. 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" # taker or maker
    direction = "buy" # buy or sell
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    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

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

  1. Market for market orders
  2. limitFill for a resting limit order getting filled by a market order
  3. LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
  4. 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 = [
        "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
        "0x26413a70c9b78a495023e5ab8003c9cf963ef963f6755f8b57255feb5744bf31"
    ]
    execution_side = "taker"  # maker or taker
    direction = "sell"  # sell or buy
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    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 = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    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 = [
        "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0",
        "0x26413a70c9b78a495023e5ab8003c9cf963ef963f6755f8b57255feb5744bf31"
    ]

    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_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    orderbook = await client.stream_spot_orderbook(market_id=market_id)
    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 = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    skip = 10
    limit = 2
    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

  1. Market for market orders
  2. limitFill for a resting limit order getting filled by a market order
  3. LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
  4. 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 = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    execution_type = "market"  # market, limitFill, limitMatchRestingOrder or limitMatchNewOrder
    direction = "buy"  # buy or sell
    skip = 10
    limit = 2
    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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    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

Orders

Get orders 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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    order_side = "buy"  # buy or sell
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    skip = 10
    limit = 2
    orders = await client.get_derivative_orders(
        market_id=market_id,
        order_side=order_side,
        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())
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.OrdersRequest{
    MarketId: marketId,
    Skip:     skip,
    Limit:    limit,
  }

  res, err := exchangeClient.GetDerivativeOrders(ctx, req)
  if err != nil {
    panic(err)
  }

  str, _ := json.MarshalIndent(res, "", " ")
  fmt.Print(string(str))
}
import { getNetworkInfo, Network } from "@injectivelabs/networks";
import { protoObjectToJson, DerivativeOrderSide } 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 orderSide = DerivativeOrderSide.Buy;
  const pagination = {
    skip: 0,
    limit: 10,
    key: ""
  };

  const exchangeClient = new ExchangeGrpcClient(
    network.exchangeApi
  );

  const orders = await exchangeClient.derivatives.fetchOrders({
    marketId: marketId,
    subaccountId: subaccountId,
    orderSide: orderSide,
    pagination: pagination,
  });

  console.log(protoObjectToJson(orders));
})();
Parameter Type Description Required
market_id String Filter by market ID Yes
subaccount_id String Filter by subaccount ID No
order_side String Filter by order side (Should be one of: [buy sell]) 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: "0x7907940675bea98d7e7d3e6b7373d93e92258a00a016b7444d1004516a9066b2"
  order_side: "buy"
  market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
  subaccount_id: "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
  margin: "4540956000"
  price: "37841300000"
  quantity: "0.12"
  unfilled_quantity: "0.12"
  trigger_price: "0"
  fee_recipient: "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
  state: "booked"
  created_at: 1650974417291
  updated_at: 1650974417291
}
orders {
  order_hash: "0x986650d57a99624ba7422a4e71885a30ceb72879ce939a0f8a91f70e1e38256d"
  order_side: "buy"
  market_id: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
  subaccount_id: "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
  margin: "7151733000"
  price: "37640700000"
  quantity: "0.19"
  unfilled_quantity: "0.19"
  trigger_price: "0"
  fee_recipient: "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r"
  state: "booked"
  created_at: 1650974417291
  updated_at: 1650974417291
}
{
 "orders": [
  {
   "order_hash": "0x986650d57a99624ba7422a4e71885a30ceb72879ce939a0f8a91f70e1e38256d",
   "order_side": "buy",
   "market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
   "subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
   "margin": "7151733000",
   "price": "37640700000",
   "quantity": "0.19",
   "unfilled_quantity": "0.1399",
   "trigger_price": "0",
   "fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
   "state": "partial_filled",
   "created_at": 1650974417291,
   "updated_at": 1652793291276
  },
  {
   "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
  },
  }
 ]
}
{
  "ordersList": [
    {
      "orderHash": "0x121996113fe1ddceb01e9fc92178359010efd46642ef814652a99e4036a50251",
      "orderSide": "buy",
      "marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
      "subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
      "isReduceOnly": false,
      "margin": "3213504000",
      "price": "40168800000",
      "quantity": "0.08",
      "unfilledQuantity": "0.03",
      "triggerPrice": "0",
      "feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "state": "partial_filled",
      "createdAt": 1654246073718,
      "updatedAt": 1654246118791
    },
    {
      "orderHash": "0x78ed5c5a82fd4506f06cd9f7be05cd41014f2d00d118e0895b2efceefe165206",
      "orderSide": "buy",
      "marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
      "subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
      "isReduceOnly": false,
      "margin": "1970320000",
      "price": "39406400000",
      "quantity": "0.05",
      "unfilledQuantity": "0.03",
      "triggerPrice": "0",
      "feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "state": "partial_filled",
      "createdAt": 1654245977964,
      "updatedAt": 1654246024203
    },
    {
      "orderHash": "0x3cb132bbaf9370a241f0b483739ccab3365bc4bbff890c138c5577ddbbcbffdb",
      "orderSide": "buy",
      "marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
      "subaccountId": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
      "isReduceOnly": false,
      "margin": "6041776000",
      "price": "37761100000",
      "quantity": "0.16",
      "unfilledQuantity": "0.16",
      "triggerPrice": "0",
      "feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "state": "booked",
      "createdAt": 1652961978151,
      "updatedAt": 1652961978151
    }
  ]
}

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 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
price String Price of the order
subaccount_id String The subaccountId that 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

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:
    network = Network.testnet()
    client = AsyncClient(network, insecure=False)
    market_id = "0x54d4505adef6a5cef26bc403a33d595620ded4e15b9e2bc3dd489b714813366a"
    subaccount_id = "0x1b99514e320ae0087be7f87b1e3057853c43b799000000000000000000000000"
    skip = 10
    limit = 2
    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
order_type String Filter by order type No
direction String Filter by direction No
start_time Integer Search for orders createdAt >= startTime, time in millisecond No
end_time Integer Search for orders createdAt <= startTime, time in millisecond No

Response Parameters

Response Example:

orders {
  order_hash: "0x0f62edfb64644762c20490d9573034c2f319e87e857401c41eea1fe373045dd7"
  market_id: "0x54d4505adef6a5cef26bc403a33d595620ded4e15b9e2bc3dd489b714813366a"
  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: "0x54d4505adef6a5cef26bc403a33d595620ded4e15b9e2bc3dd489b714813366a"
  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"
}



Parameter Type Description
orders Order Order object

Order

Parameter Type Description
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 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
price String Price of the order
subaccount_id String The subaccountId that this order belongs to
updated_at Integer Order updated timestamp in UNIX millis.
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])

StreamOrders

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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    order_side = "buy"  # buy or sell
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    orders = await client.stream_derivative_orders(
        market_id=market_id,
        order_side=order_side,
        subaccount_id=subaccount_id
    )
    async for order in orders:
        print(order)

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"
  orderSide := "buy"

  req := derivativeExchangePB.StreamOrdersRequest{
    MarketId:     marketId,
    SubaccountId: subaccountId,
    OrderSide:    orderSide,
  }
  stream, err := exchangeClient.StreamDerivativeOrders(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, DerivativeOrderSide } 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 = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000";
  const orderSide = DerivativeOrderSide.Buy;

  const exchangeClient = new ExchangeGrpcStreamClient(
    network.exchangeApi
  );

  await exchangeClient.derivatives.streamDerivativeOrders(
    {
      marketId: marketId,
      subaccountId: subaccountId,
      orderSide: orderSide,
      callback: (streamDerivativeOrders) => {
        console.log(protoObjectToJson(streamDerivativeOrders));
      },
      onEndCallback: (status) => {
        console.log("Stream has ended with status: " + status);
      },
    });
})();
Parameter Type Description Required
market_id String Filter by market ID Yes
order_side String Filter by order side (Should be one of: [buy sell]) No
subaccount_id String Filter by subaccount ID No

Response Parameters

Streaming Response Example:

order {
  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
}
operation_type: "insert"
timestamp: 1652792833000
{
 "order": {
  "order_hash": "0x87a4d806842b102f1a67fad6816fdbf378a2702b94171de0e8b5d953bd8891ec",
  "order_side": "buy",
  "market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
  "subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
  "margin": "2036530000",
  "price": "40730600000",
  "quantity": "0.05",
  "unfilled_quantity": "0.05",
  "trigger_price": "0",
  "fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
  "state": "booked",
  "created_at": 1653039983803,
  "updated_at": 1653039983803
 },
 "operation_type": "insert",
 "timestamp": 1653039988000
}{
 "order": {
  "order_hash": "0x87a4d806842b102f1a67fad6816fdbf378a2702b94171de0e8b5d953bd8891ec",
  "order_side": "buy",
  "market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
  "subaccount_id": "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000",
  "margin": "2036530000",
  "price": "40730600000",
  "quantity": "0.05",
  "unfilled_quantity": "0",
  "trigger_price": "0",
  "fee_recipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
  "state": "filled",
  "created_at": 1653039983803,
  "updated_at": 1653040007897
 },
 "operation_type": "update",
 "timestamp": 1653040014000
}
{
  "order": {
    "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
  },
  "operationType": "insert",
  "timestamp": 1654246255000
}
Parameter Type Description
order DerivativeLimitOrder DerivativeLimitOrder object
operation_type String Order update type (Should be one of: [insert delete replace update invalidate])
timestamp Integer Operation timestamp in UNIX millis

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

Trades

Get trades of a derivative market.

Trade execution types

  1. Market for market orders
  2. limitFill for a resting limit order getting filled by a market order
  3. LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
  4. 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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    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

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

  1. Market for market orders
  2. limitFill for a resting limit order getting filled by a market order
  3. LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
  4. 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 = [
        "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
        "0x1f73e21972972c69c03fb105a5864592ac2b47996ffea3c500d1ea2d20138717"
    ]
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    positions = await client.get_derivative_positions(
        market_id=market_id,
        subaccount_id=subaccount_id,
    )
    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 Yes
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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    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 = [
        "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
        "0x1f73e21972972c69c03fb105a5864592ac2b47996ffea3c500d1ea2d20138717"
    ]
    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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    skip = 10
    limit = 2
    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

  1. Market for market orders
  2. limitFill for a resting limit order getting filled by a market order
  3. LimitMatchRestingOrder for a resting limit order getting matched with another new limit order
  4. 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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    execution_type = "market"  # market, limitFill, limitMatchRestingOrder or limitMatchNewOrder
    direction = "sell"  # buy or sell
    skip = 10
    limit = 2
    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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    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 = "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce"
    skip=0
    limit=2
    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