NAV
Python

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

Installation

Install injective-py from PyPI using pip.

pip install injective-py

Reference

InjectiveLabs/sdk-python.

Golang Client

Examples are under construction, stay tuned.

Installation

Install sdk-go using go get.

go get -u github.com/InjectiveLabs/sdk-go

Reference

InjectiveLabs/sdk-go.

Typescript Client

Examples are under construction, stay tuned.

Installation

Install exchange-consumer using yarn.

yarn add @InjectiveLabs/exchange-consumer

Reference

InjectiveLabs/injective-ts.

Overview

Injective Protocol is a fully decentralized layer-2 DEX protocol 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 layer-2 fully decentralized exchange protocol 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.

Exchange API

- 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 grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    account_address = "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
    subacc_list = client.get_subaccount_list(account_address)
    print(subacc_list)
Parameter Type Description Required
account_address string The Injective Chain address Yes

Response Parameters

Response Example:

{
  "subaccounts": [
    "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000000",
    "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000001",
    "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002"
  ]
}
Parameter Type Description
subaccounts Array

SubaccountHistory

Get the subaccount's transfer history

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    denom = "inj"
    transfer_types = ["withdraw", "deposit"] # "withdraw", "deposit", "internal", "external"
    subacc_history = client.get_subaccount_history(subaccount_id=subaccount, denom=denom, transfer_types=transfer_types)
    print(subacc_history)
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

Response Parameters

Response Example:

{
  "transfers": [
    {
      "amount": {
        "amount": "10000000000000000000",
        "denom": "inj"
      },
      "dstAccountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "dstSubaccountID": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "executedAt": 1544614248000,
      "srcAccountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "srcSubaccountID": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "transferType": "deposit"
    },
    {
      "amount": {
        "amount": "10000000000000000000",
        "denom": "inj"
      },
      "dstAccountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "dstSubaccountID": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "executedAt": 1544614248000,
      "srcAccountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "srcSubaccountID": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "transferType": "deposit"
    }
  ]
}
Parameter Type Description
transfers Array of SubaccountBalanceTransfer List of subaccount transfers

SubaccountBalanceTransfer:

Parameter Type Description
amount CosmosCoin
dstAccountAddress string Account address of the receiving side
dstSubaccountID string Subaccount ID of the receiving side
executedAt integer Timestamp of the transfer in UNIX millis
srcAccountAddress string Account address of the sending side
srcSubaccountID string Subaccount ID of the sending side
transferType string Type of the subaccount balance transfer (Should be one of: [internal external withdraw deposit])

CosmosCoin:

Parameter Type Description
amount string Coin amount (big int)
denom string Coin denominator

SubaccountBalance

Get the balance of a subaccount for a specific denom

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    denom = "inj"
    balance = client.get_subaccount_balance(subaccount_id=subaccount_id, denom=denom)
    print(balance)
Parameter Type Description Required
subaccount_id string Filter by Subaccount ID Yes
denom string Filter by denom Yes

Response Parameters

Response Example:

{
  "balance": {
    "accountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
    "denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
    "deposit": {
      "availableBalance": "1000000000000000000",
      "totalBalance": "1960000000000000000"
    },
    "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002"
  }
}
Parameter Type Description
balance SubaccountBalance

SubaccountBalance:

Parameter Type Description
denom string Coin denom on the chain.
deposit SubaccountDeposit
subaccountId string Related subaccount ID
accountAddress string Account address, owner of this subaccount

SubaccountDeposit:

Parameter Type Description
availableBalance string
totalBalance string

SubaccountBalancesList

List the subaccount's balances for all denoms

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    subacc_balances_list = client.get_subaccount_balances_list(subaccount)
    print(subacc_balances_list)
Parameter Type Description Required
subaccount_id string Filter by Subaccount ID Yes

Response Parameters

Response Example:

{
  "balances": [
    {
      "accountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "deposit": {
        "availableBalance": "1000000000000000000",
        "totalBalance": "1960000000000000000"
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002"
    },
    {
      "accountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "deposit": {
        "availableBalance": "1000000000000000000",
        "totalBalance": "1960000000000000000"
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002"
    },
    {
      "accountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "deposit": {
        "availableBalance": "1000000000000000000",
        "totalBalance": "1960000000000000000"
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002"
    }
  ]
}
Parameter Type Description
balances Array of SubaccountBalance List of subaccount balances

SubaccountBalance:

Parameter Type Description
accountAddress string Account address, owner of this subaccount
denom string Coin denom on the chain.
deposit SubaccountDeposit
subaccountId string Related subaccount ID

SubaccountDeposit:

Parameter Type Description
availableBalance string
totalBalance string

SubaccountOrderSummary

Get the subaccount's orders summary

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    order_direction = "buy" #buy or sell
    subacc_order_summary = client.get_subaccount_order_summary(subaccount_id=subaccount, order_direction=order_direction, market_id=market_id)
    print(subacc_order_summary)
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:

{
  "derivativeOrdersTotal": 10,
  "spotOrdersTotal": 11
}
Parameter Type Description
derivativeOrdersTotal integer Total count of subaccount's derivative orders in given market and direction
spotOrdersTotal integer Total count of subaccount's spot orders in given market and direction

StreamSubaccountBalance

Stream the subaccount's balance for all denoms

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    subaccount = client.stream_subaccount_balance(subaccount_id)
    for balance in subaccount:
        print("Subaccount balance Update:\n")
        print(balance)
Parameter Type Description Required
subaccount_id string Filter by Subaccount ID Yes

Response Parameters

Streaming Response Example:

{
  "balance": {
    "accountAddress": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
    "denom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
    "deposit": {
      "availableBalance": "1000000000000000000",
      "totalBalance": "1960000000000000000"
    },
    "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002"
  },
  "timestamp": 1544614248000
}
Parameter Type Description
balance SubaccountBalance
timestamp integer Operation timestamp in UNIX millis.

SubaccountBalance:

Parameter Type Description
denom string Coin denom on the chain.
deposit SubaccountDeposit
subaccountId string Related subaccount ID
accountAddress string Account address, owner of this subaccount

SubaccountDeposit:

Parameter Type Description
availableBalance string
totalBalance string

- InjectiveSpotExchangeRPC

InjectiveSpotExchangeRPC defines the gRPC API of the Spot Exchange provider.

Market

Get details of a spot market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    market = client.get_spot_market(market_id=market_id)
    print(market)
Parameter Type Description Required
market_id string Filter by Market ID Yes

Response Parameters

Response Example:

{
  "market": {
    "baseDenom": "inj",
    "baseTokenMeta": {
      "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "decimals": 18,
      "logo": "https://static.alchemyapi.io/images/assets/825.png",
      "name": "Tether",
      "symbol": "USDT",
      "updatedAt": 1544614248000
    },
    "makerFeeRate": "0.001",
    "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
    "marketStatus": "active",
    "minPriceTickSize": "0.001",
    "minQuantityTickSize": "0.001",
    "quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
    "quoteTokenMeta": {
      "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "decimals": 18,
      "logo": "https://static.alchemyapi.io/images/assets/825.png",
      "name": "Tether",
      "symbol": "USDT",
      "updatedAt": 1544614248000
    },
    "serviceProviderFee": "0.4",
    "takerFeeRate": "0.002",
    "ticker": "INJ/USDC"
  }
}
Parameter Type Description
market SpotMarketInfo

SpotMarketInfo:

Parameter Type Description
baseDenom string Coin denom used for the base asset.
marketId string SpotMarket ID is keccak265(baseDenom
marketStatus string The status of the market (Should be one of: [active paused suspended demolished expired])
minQuantityTickSize string Defines the minimum required tick size for the order's quantity
quoteTokenMeta TokenMeta
serviceProviderFee string Percentage of the transaction fee shared with the service provider
baseTokenMeta TokenMeta
makerFeeRate string Defines the fee percentage makers pay when trading (in quote asset)
minPriceTickSize string Defines the minimum required tick size for the order's price
quoteDenom string Coin denom used for the quote asset.
takerFeeRate string Defines the fee percentage takers pay when trading (in 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 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 grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_status = "active" # active, paused, suspended, demolished or expired
    base_denom = "inj"
    quote_denom = "peggy0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08"
    market = client.get_spot_markets(market_status=market_status, base_denom=base_denom, quote_denom=quote_denom)
    print(market)
Parameter Type Description Required
base_denom string Filter by the Coin denomination of 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 Coin denomination of the quote currency No

Response Parameters

Response Example:

{
  "markets": [
    {
      "baseDenom": "inj",
      "baseTokenMeta": {
        "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
        "decimals": 18,
        "logo": "https://static.alchemyapi.io/images/assets/825.png",
        "name": "Tether",
        "symbol": "USDT",
        "updatedAt": 1544614248000
      },
      "makerFeeRate": "0.001",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "marketStatus": "active",
      "minPriceTickSize": "0.001",
      "minQuantityTickSize": "0.001",
      "quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "quoteTokenMeta": {
        "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
        "decimals": 18,
        "logo": "https://static.alchemyapi.io/images/assets/825.png",
        "name": "Tether",
        "symbol": "USDT",
        "updatedAt": 1544614248000
      },
      "serviceProviderFee": "0.4",
      "takerFeeRate": "0.002",
      "ticker": "INJ/USDC"
    },
  ]
}
Parameter Type Description
markets Array of SpotMarketInfo Spot Markets list

SpotMarketInfo:

Parameter Type Description
takerFeeRate string Defines the fee percentage takers pay when trading (in quote asset)
ticker string A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset.
baseTokenMeta TokenMeta
makerFeeRate string Defines the fee percentage makers pay when trading (in quote asset)
minPriceTickSize string Defines the minimum required tick size for the order's price
quoteDenom string Coin denom used for the quote asset.
quoteTokenMeta TokenMeta
serviceProviderFee string Percentage of the transaction fee shared with the service provider
baseDenom string Coin denom used for the base asset.
marketId string SpotMarket ID is keccak265(baseDenom
marketStatus string The status of the market (Should be one of: [active paused suspended demolished expired])
minQuantityTickSize string Defines the minimum required tick size for the order's quantity

TokenMeta:

Parameter Type Description
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
updatedAt integer Token metadata fetched timestamp in UNIX millis.

StreamMarkets

Stream live updates of spot markets

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    markets = client.stream_spot_markets()
    for market in markets:
        print(market)

Response Parameters

Streaming Response Example:

{
  "market": {
    "baseDenom": "inj",
    "baseTokenMeta": {
      "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "decimals": 18,
      "logo": "https://static.alchemyapi.io/images/assets/825.png",
      "name": "Tether",
      "symbol": "USDT",
      "updatedAt": 1544614248000
    },
    "makerFeeRate": "0.001",
    "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
    "marketStatus": "active",
    "minPriceTickSize": "0.001",
    "minQuantityTickSize": "0.001",
    "quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
    "quoteTokenMeta": {
      "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "decimals": 18,
      "logo": "https://static.alchemyapi.io/images/assets/825.png",
      "name": "Tether",
      "symbol": "USDT",
      "updatedAt": 1544614248000
    },
    "serviceProviderFee": "0.4",
    "takerFeeRate": "0.002",
    "ticker": "INJ/USDC"
  },
  "operationType": "update",
  "timestamp": 1544614248000
}
Parameter Type Description
market SpotMarketInfo
operationType string Update type (Should be one of: [insert replace update invalidate])
timestamp integer Operation timestamp in UNIX millis.

SpotMarketInfo:

Parameter Type Description
baseTokenMeta TokenMeta
makerFeeRate string Defines the fee percentage makers pay when trading (in quote asset)
minPriceTickSize string Defines the minimum required tick size for the order's price
quoteDenom string Coin denom used for the quote asset.
takerFeeRate string Defines the fee percentage takers pay when trading (in quote asset)
ticker string A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset.
baseDenom string Coin denom used for the base asset.
marketId string SpotMarket ID is keccak265(baseDenom
marketStatus string The status of the market (Should be one of: [active paused suspended demolished expired])
minQuantityTickSize string Defines the minimum required tick size for the order's quantity
quoteTokenMeta TokenMeta
serviceProviderFee string Percentage of the transaction fee shared with the service provider

TokenMeta:

Parameter Type Description
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.
address string Token Ethereum contract address

Orders

Get orders of a spot market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    order_side = "sell" # buy or sell
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    orders = client.get_spot_orders(market_id=market_id, order_side=order_side, subaccount_id=subaccount_id)
    print(orders)
Parameter Type Description Required
market_id string Filter by Market ID Yes
order_side string Look for specific order side (Should be one of: [buy sell]) No
subaccount_id string Filter by Subaccount ID No

Response Parameters

Response Example:

{
  "orders": [
    {
      "createdAt": 1544614248000,
      "feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "marketId": "0x01e920e081b6f3b2e5183399d5b6733bb6f80319e6be3805b95cb7236910ff0e",
      "orderHash": "0x4f4391f8ee11f656d0a9396370c6991f59c4bb491214e8b6ab2011a1bcf1c44e",
      "orderSide": "buy",
      "price": "0.000000003156",
      "quantity": "28000000000000000.00000000000000000",
      "state": "partial_filled",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "triggerPrice": "0",
      "unfilledQuantity": "28000000000000000.00000000000000000",
      "updatedAt": 1544614248000
    },
    {
      "createdAt": 1544614248000,
      "feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "marketId": "0x01e920e081b6f3b2e5183399d5b6733bb6f80319e6be3805b95cb7236910ff0e",
      "orderHash": "0x4f4391f8ee11f656d0a9396370c6991f59c4bb491214e8b6ab2011a1bcf1c44e",
      "orderSide": "buy",
      "price": "0.000000003156",
      "quantity": "28000000000000000.00000000000000000",
      "state": "partial_filled",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "triggerPrice": "0",
      "unfilledQuantity": "28000000000000000.00000000000000000",
      "updatedAt": 1544614248000
    },
  ]
}
Parameter Type Description
orders Array of SpotLimitOrder List of spot market orders

SpotLimitOrder:

Parameter Type Description
unfilledQuantity string The amount of the quantity remaining unfilled
createdAt integer Order committed timestamp in UNIX millis.
marketId string Spot Market ID is keccak265(baseDenom + quoteDenom)
orderHash string Hash of the order
orderSide string The type of the order (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell])
state string Order state (Should be one of: [booked partial_filled filled canceled])
subaccountId string The subaccountId that this order belongs to
feeRecipient string Fee recipient address
price string Price of the order
quantity string Quantity of the order
triggerPrice string Trigger price is the trigger price used by stop/take orders. 0 if the trigger price is not set.
updatedAt integer Order updated timestamp in UNIX millis.

StreamOrders

Stream order updates of a spot market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    order_side = "sell" # sell or buy
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    orders = client.stream_spot_orders(market_id=market_id, order_side=order_side, subaccount_id=subaccount_id)
    for order in orders:
        print(order)
Parameter Type Description Required
market_id string Filter by Market ID Yes
order_side string Look for specific order side (Should be one of: [buy sell]) No
subaccount_id string Filter by Subaccount ID No

Response Parameters

Streaming Response Example:

{
  "operationType": "update",
  "order": {
    "createdAt": 1544614248000,
    "feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
    "marketId": "0x01e920e081b6f3b2e5183399d5b6733bb6f80319e6be3805b95cb7236910ff0e",
    "orderHash": "0x4f4391f8ee11f656d0a9396370c6991f59c4bb491214e8b6ab2011a1bcf1c44e",
    "orderSide": "buy",
    "price": "0.000000003156",
    "quantity": "28000000000000000.00000000000000000",
    "state": "partial_filled",
    "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
    "triggerPrice": "0",
    "unfilledQuantity": "28000000000000000.00000000000000000",
    "updatedAt": 1544614248000
  },
  "timestamp": 1544614248000
}
Parameter Type Description
operationType string Order update type (Should be one of: [insert replace update invalidate])
order SpotLimitOrder
timestamp integer Operation timestamp in UNIX millis.

SpotLimitOrder:

Parameter Type Description
unfilledQuantity string The amount of the quantity remaining unfilled
createdAt integer Order committed timestamp in UNIX millis.
marketId string Spot Market ID is keccak265(baseDenom + quoteDenom)
orderHash string Hash of the order
orderSide string The type of the order (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell])
state string Order state (Should be one of: [booked partial_filled filled canceled])
subaccountId string The subaccountId that this order belongs to
feeRecipient string Fee recipient address
price string Price of the order
quantity string Quantity of the order
triggerPrice string Trigger price is the trigger price used by stop/take orders. 0 if the trigger price is not set.
updatedAt integer Order updated timestamp in UNIX millis.

Trades

Get trades of a spot market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    direction = "buy" # buy or sell
    execution_side = "taker" # taker or maker

    orders = client.get_spot_trades(market_id=market_id, execution_side=execution_side, direction=direction, subaccount_id=subaccount_id)
    print(orders)
Parameter Type Description Required
market_id string Market ID of the market to fetch Yes
subaccount_id string Subaccount ID to filter trades 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

Response Parameters

Response Example:

{
  "trades": [
    {
      "executedAt": 1544614248000,
      "fee": "1960000000000000",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "orderHash": "0x482ce078117d4835fe005b643056d2d3f439e3010db40f68449d9e5b77e911bc",
      "price": {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "tradeDirection": "buy",
      "tradeExecutionType": "market"
    },
  ]
}
Parameter Type Description
trades Array of SpotTrade Trades of a Spot Market

SpotTrade:

Parameter Type Description
tradeDirection string The direction the trade (Should be one of: [buy sell])
tradeExecutionType string The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder])
executedAt integer Timestamp of trade execution in UNIX millis
fee string The fee associated with the trade (quote asset denom)
marketId string The ID of the market that this trade is in
orderHash string Maker order hash.
price PriceLevel
subaccountId string The subaccountId that executed the trade

PriceLevel:

Parameter Type Description
price string Price 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

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    execution_side = "maker" # maker or taker
    direction = "sell" # sell or buy
    trades = client.stream_spot_trades(market_id=market_id, execution_side=execution_side, direction=direction, subaccount_id=subaccount_id)
    for trade in trades:
        print(trade)
Parameter Type Description Required
market_id string Filter by Market ID Yes
subaccount_id string Filter by Subaccount ID 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

Response Parameters

Streaming Response Example:

{
  "operationType": "insert",
  "timestamp": 1544614248000,
  "trade": {
    "executedAt": 1544614248000,
    "fee": "1960000000000000",
    "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
    "orderHash": "0x482ce078117d4835fe005b643056d2d3f439e3010db40f68449d9e5b77e911bc",
    "price": {
      "price": "1960000000000000000",
      "quantity": "40",
      "timestamp": 1544614248000
    },
    "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
    "tradeDirection": "buy",
    "tradeExecutionType": "market"
  }
}
Parameter Type Description
operationType string Executed trades update type (Should be one of: [insert invalidate])
timestamp integer Operation timestamp in UNIX millis.
trade SpotTrade

SpotTrade:

Parameter Type Description
fee string The fee associated with the trade (quote asset denom)
marketId string The ID of the market that this trade is in
orderHash string Maker order hash.
price PriceLevel
subaccountId string The subaccountId that executed the trade
tradeDirection string The direction the trade (Should be one of: [buy sell])
tradeExecutionType string The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder])
executedAt integer Timestamp of trade execution in UNIX millis

PriceLevel:

Parameter Type Description
price string Price 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 grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    orderbook = client.get_spot_orderbook(market_id=market_id)
    print(orderbook)
Parameter Type Description Required
market_id string Filter by Market ID Yes

Response Parameters

Response Example:

{
  "orderbook": {
    "buys": [
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      }
    ],
    "sells": [
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      }
    ]
  }
}
Parameter Type Description
orderbook SpotLimitOrderbook

SpotLimitOrderbook:

Parameter Type Description
buys Array of PriceLevel Array of price levels for buys
sells Array of PriceLevel Array of price levels for sells

PriceLevel:

Parameter Type Description
price string Price number of the price level.
quantity string Quantity of the price level.
timestamp integer Price level last updated timestamp in UNIX millis.

StreamOrderbook

Stream the orderbook of a spot market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    orderbook = client.stream_spot_orderbook(market_id=market_id)
    for orders in orderbook:
        print(orders)
Parameter Type Description Required
market_id string Filter by Market ID Yes

Response Parameters

Streaming Response Example:

{
  "operationType": "update",
  "orderbook": {
    "buys": [
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
    ]
  },
  "timestamp": 1544614248000
}
Parameter Type Description
operationType string Order update type (Should be one of: [insert replace update invalidate])
orderbook SpotLimitOrderbook
timestamp integer Operation timestamp in UNIX millis.

SpotLimitOrderbook:

Parameter Type Description
buys Array of PriceLevel Array of price levels for buys
sells Array of PriceLevel Array of price levels for sells

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 orders of a subaccount

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    orders = client.get_spot_subaccount_orders(subaccount_id=subaccount_id, market_id=market_id)
    print(orders)
Parameter Type Description Required
subaccount_id string Filter by Subaccount ID Yes
market_id string Filter by Market ID No

Response Parameters

Response Example:

{
  "orders": [
    {
      "createdAt": 1544614248000,
      "feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "marketId": "0x01e920e081b6f3b2e5183399d5b6733bb6f80319e6be3805b95cb7236910ff0e",
      "orderHash": "0x4f4391f8ee11f656d0a9396370c6991f59c4bb491214e8b6ab2011a1bcf1c44e",
      "orderSide": "buy",
      "price": "0.000000003156",
      "quantity": "28000000000000000.00000000000000000",
      "state": "partial_filled",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "triggerPrice": "0",
      "unfilledQuantity": "28000000000000000.00000000000000000",
      "updatedAt": 1544614248000
    },
    {
      "createdAt": 1544614248000,
      "feeRecipient": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "marketId": "0x01e920e081b6f3b2e5183399d5b6733bb6f80319e6be3805b95cb7236910ff0e",
      "orderHash": "0x4f4391f8ee11f656d0a9396370c6991f59c4bb491214e8b6ab2011a1bcf1c44e",
      "orderSide": "buy",
      "price": "0.000000003156",
      "quantity": "28000000000000000.00000000000000000",
      "state": "partial_filled",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "triggerPrice": "0",
      "unfilledQuantity": "28000000000000000.00000000000000000",
      "updatedAt": 1544614248000
    },
  ]
}
Parameter Type Description
orders Array of SpotLimitOrder List of spot orders

SpotLimitOrder:

Parameter Type Description
state string Order state (Should be one of: [booked partial_filled filled canceled])
subaccountId string The subaccountId that this order belongs to
unfilledQuantity string The amount of the quantity remaining unfilled
createdAt integer Order committed timestamp in UNIX millis.
marketId string Spot Market ID is keccak265(baseDenom + quoteDenom)
orderHash string Hash of the order
orderSide string The type of the order (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell])
updatedAt integer Order updated timestamp in UNIX millis.
feeRecipient string Fee recipient address
price string Price of the order
quantity string Quantity of the order
triggerPrice string Trigger price is the trigger price used by stop/take orders. 0 if the trigger price is not set.

SubaccountTradesList

Get trades of a subaccount

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    direction = "buy" # buy or sell
    execution_type = "market" # market, limitFill, limitMatchRestingOrder or limitMatchNewOrder
    trades = client.get_spot_subaccount_trades(subaccount_id=subaccount_id, market_id=market_id, execution_type=execution_type, direction=direction)
    print(trades)
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

Response Parameters

Response Example:

{
  "trades": [
    {
      "executedAt": 1544614248000,
      "fee": "1960000000000000",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "orderHash": "0x482ce078117d4835fe005b643056d2d3f439e3010db40f68449d9e5b77e911bc",
      "price": {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "tradeDirection": "buy",
      "tradeExecutionType": "market"
    },
    {
      "executedAt": 1544614248000,
      "fee": "1960000000000000",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "orderHash": "0x482ce078117d4835fe005b643056d2d3f439e3010db40f68449d9e5b77e911bc",
      "price": {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "tradeDirection": "buy",
      "tradeExecutionType": "market"
    }
  ]
}
Parameter Type Description
trades Array of SpotTrade List of spot market trades

SpotTrade:

Parameter Type Description
price PriceLevel
subaccountId string The subaccountId that executed the trade
tradeDirection string The direction the trade (Should be one of: [buy sell])
tradeExecutionType string The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder])
executedAt integer Timestamp of trade execution in UNIX millis
fee string The fee associated with the trade (quote asset denom)
marketId string The ID of the market that this trade is in
orderHash string Maker order hash.

PriceLevel:

Parameter Type Description
price string Price 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 grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    market = client.get_derivative_market(market_id=market_id)
    print(market)
Parameter Type Description Required
market_id string Filter by Market ID Yes

Response Parameters

Response Example:

{
  "market": {
    "expiryFuturesMarketInfo": {
      "expirationTimestamp": 1544614248,
      "settlementPrice": "0.05"
    },
    "initialMarginRatio": "0.05",
    "isPerpetual": false,
    "maintenanceMarginRatio": "0.025",
    "makerFeeRate": "0.001",
    "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
    "marketStatus": "active",
    "minPriceTickSize": "0.001",
    "minQuantityTickSize": "0.001",
    "oracleBase": "inj-band",
    "oracleQuote": "usdt-band",
    "oracleScaleFactor": 6,
    "oracleType": "band",
    "perpetualMarketFunding": {
      "cumulativeFunding": "0.05",
      "cumulativePrice": "-22.93180251",
      "lastTimestamp": 1622930400
    },
    "perpetualMarketInfo": {
      "fundingInterval": 3600,
      "hourlyFundingRateCap": "0.000625",
      "hourlyInterestRate": "0.00000416666",
      "nextFundingTimestamp": 1622930400
    },
    "quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
    "quoteTokenMeta": {
      "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "decimals": 18,
      "logo": "https://static.alchemyapi.io/images/assets/825.png",
      "name": "Tether",
      "symbol": "USDT",
      "updatedAt": 1544614248000
    },
    "serviceProviderFee": "0.4",
    "takerFeeRate": "0.002",
    "ticker": "INJ/USDC"
  }
}
Parameter Type Description
market DerivativeMarketInfo

DerivativeMarketInfo:

Parameter Type Description
oracleQuote string Oracle quote currency
oracleType string Oracle Type
quoteDenom string Coin denom used for the quote asset.
isPerpetual boolean True if the market is a perpetual swap market
makerFeeRate string Defines the fee percentage makers pay when trading (in quote asset)
minPriceTickSize string Defines the minimum required tick size for the order's price
minQuantityTickSize string Defines the minimum required tick size for the order's quantity
oracleScaleFactor integer OracleScaleFactor
takerFeeRate string Defines the fee percentage takers pay when trading (in quote asset)
expiryFuturesMarketInfo ExpiryFuturesMarketInfo
initialMarginRatio string Defines the initial margin ratio of a derivative market
marketStatus string The status of the market (Should be one of: [active paused suspended demolished expired])
serviceProviderFee string Percentage of the transaction fee shared with the service provider
oracleBase string Oracle base currency
perpetualMarketFunding PerpetualMarketFunding
perpetualMarketInfo PerpetualMarketInfo
ticker string A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset.
maintenanceMarginRatio string Defines the maintenance margin ratio of a derivative market
marketId string DerivativeMarket ID is crypto.Keccak256Hash([]byte((oracleType.String() + ticker + quoteDenom + oracleBase + oracleQuote))) for perpetual markets and crypto.Keccak256Hash([]byte((oracleType.String() + ticker + quoteDenom + oracleBase + oracleQuote + strconv.Itoa(int(expiry))))) for expiry futures markets
quoteTokenMeta TokenMeta

ExpiryFuturesMarketInfo:

Parameter Type Description
expirationTimestamp integer Defines the expiration time for a time expiry futures market in UNIX seconds.
settlementPrice string Defines the settlement price for a time expiry futures market.

PerpetualMarketFunding:

Parameter Type Description
cumulativeFunding string Defines the cumulative funding of a perpetual market.
cumulativePrice string Defines defines the cumulative price for the current hour up to the last timestamp.
lastTimestamp integer Defines the last funding timestamp in seconds of a perpetual market in UNIX seconds.

PerpetualMarketInfo:

Parameter Type Description
hourlyFundingRateCap string Defines the default maximum absolute value of the hourly funding rate of the perpetual market.
hourlyInterestRate string Defines the hourly interest rate of the perpetual market.
nextFundingTimestamp integer Defines the next funding timestamp in seconds of a perpetual market in UNIX seconds.
fundingInterval integer Defines the funding interval in seconds of a perpetual market in seconds.

TokenMeta:

Parameter Type Description
updatedAt 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 grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_status = "active" # active, paused, suspended, demolished or expired
    quote_denom = "peggy0x69efCB62D98f4a6ff5a0b0CFaa4AAbB122e85e08"
    market = client.get_derivative_markets(market_status=market_status, quote_denom=quote_denom)
    print(market)
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": [
    {
      "expiryFuturesMarketInfo": {
        "expirationTimestamp": 1544614248,
        "settlementPrice": "0.05"
      },
      "initialMarginRatio": "0.05",
      "isPerpetual": false,
      "maintenanceMarginRatio": "0.025",
      "makerFeeRate": "0.001",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "marketStatus": "active",
      "minPriceTickSize": "0.001",
      "minQuantityTickSize": "0.001",
      "oracleBase": "inj-band",
      "oracleQuote": "usdt-band",
      "oracleScaleFactor": 6,
      "oracleType": "band",
      "perpetualMarketFunding": {
        "cumulativeFunding": "0.05",
        "cumulativePrice": "-22.93180251",
        "lastTimestamp": 1622930400
      },
      "perpetualMarketInfo": {
        "fundingInterval": 3600,
        "hourlyFundingRateCap": "0.000625",
        "hourlyInterestRate": "0.00000416666",
        "nextFundingTimestamp": 1622930400
      },
      "quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "quoteTokenMeta": {
        "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
        "decimals": 18,
        "logo": "https://static.alchemyapi.io/images/assets/825.png",
        "name": "Tether",
        "symbol": "USDT",
        "updatedAt": 1544614248000
      },
      "serviceProviderFee": "0.4",
      "takerFeeRate": "0.002",
      "ticker": "INJ/USDC"
    }
  ]
}
Parameter Type Description
markets Array of DerivativeMarketInfo Derivative Markets list

DerivativeMarketInfo:

Parameter Type Description
oracleBase string Oracle base currency
perpetualMarketFunding PerpetualMarketFunding
perpetualMarketInfo PerpetualMarketInfo
serviceProviderFee string Percentage of the transaction fee shared with the service provider
maintenanceMarginRatio string Defines the maintenance margin ratio of a derivative market
marketId string DerivativeMarket ID is crypto.Keccak256Hash([]byte((oracleType.String() + ticker + quoteDenom + oracleBase + oracleQuote))) for perpetual markets and crypto.Keccak256Hash([]byte((oracleType.String() + ticker + quoteDenom + oracleBase + oracleQuote + strconv.Itoa(int(expiry))))) for expiry futures markets
quoteTokenMeta TokenMeta
ticker string A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset.
isPerpetual boolean True if the market is a perpetual swap market
makerFeeRate string Defines the fee percentage makers pay when trading (in quote asset)
minPriceTickSize string Defines the minimum required tick size for the order's price
oracleQuote string Oracle quote currency
oracleType string Oracle Type
quoteDenom string Coin denom used for the quote asset.
expiryFuturesMarketInfo ExpiryFuturesMarketInfo
initialMarginRatio string Defines the initial margin ratio of a derivative market
marketStatus string The status of the market (Should be one of: [active paused suspended demolished expired])
minQuantityTickSize string Defines the minimum required tick size for the order's quantity
oracleScaleFactor integer OracleScaleFactor
takerFeeRate string Defines the fee percentage takers pay when trading (in quote asset)

PerpetualMarketFunding:

Parameter Type Description
cumulativePrice string Defines defines the cumulative price for the current hour up to the last timestamp.
lastTimestamp integer Defines the last funding timestamp in seconds of a perpetual market in UNIX seconds.
cumulativeFunding string Defines the cumulative funding of a perpetual market.

PerpetualMarketInfo:

Parameter Type Description
fundingInterval integer Defines the funding interval in seconds of a perpetual market in seconds.
hourlyFundingRateCap string Defines the default maximum absolute value of the hourly funding rate of the perpetual market.
hourlyInterestRate string Defines the hourly interest rate of the perpetual market.
nextFundingTimestamp integer Defines the next funding timestamp in seconds of a perpetual market in UNIX seconds.

TokenMeta:

Parameter Type Description
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.
address string Token Ethereum contract address

ExpiryFuturesMarketInfo:

Parameter Type Description
expirationTimestamp integer Defines the expiration time for a time expiry futures market in UNIX seconds.
settlementPrice string Defines the settlement price for a time expiry futures market.

StreamMarket

Stream live updates of derivative markets

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    markets = client.stream_derivative_markets()
    for market in markets:
        print(market)

Response Parameters

Streaming Response Example:

{
  "market": {
    "expiryFuturesMarketInfo": {
      "expirationTimestamp": 1544614248,
      "settlementPrice": "0.05"
    },
    "initialMarginRatio": "0.05",
    "isPerpetual": false,
    "maintenanceMarginRatio": "0.025",
    "makerFeeRate": "0.001",
    "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
    "marketStatus": "active",
    "minPriceTickSize": "0.001",
    "minQuantityTickSize": "0.001",
    "oracleBase": "inj-band",
    "oracleQuote": "usdt-band",
    "oracleScaleFactor": 6,
    "oracleType": "band",
    "perpetualMarketFunding": {
      "cumulativeFunding": "0.05",
      "cumulativePrice": "-22.93180251",
      "lastTimestamp": 1622930400
    },
    "perpetualMarketInfo": {
      "fundingInterval": 3600,
      "hourlyFundingRateCap": "0.000625",
      "hourlyInterestRate": "0.00000416666",
      "nextFundingTimestamp": 1622930400
    },
    "quoteDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
    "quoteTokenMeta": {
      "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "decimals": 18,
      "logo": "https://static.alchemyapi.io/images/assets/825.png",
      "name": "Tether",
      "symbol": "USDT",
      "updatedAt": 1544614248000
    },
    "serviceProviderFee": "0.4",
    "takerFeeRate": "0.002",
    "ticker": "INJ/USDC"
  },
  "operationType": "update",
  "timestamp": 1544614248000
}
Parameter Type Description
operationType string Update type (Should be one of: [insert delete replace update invalidate])
timestamp integer Operation timestamp in UNIX millis.
market DerivativeMarketInfo

DerivativeMarketInfo:

Parameter Type Description
maintenanceMarginRatio string Defines the maintenance margin ratio of a derivative market
marketId string DerivativeMarket ID is crypto.Keccak256Hash([]byte((oracleType.String() + ticker + quoteDenom + oracleBase + oracleQuote))) for perpetual markets and crypto.Keccak256Hash([]byte((oracleType.String() + ticker + quoteDenom + oracleBase + oracleQuote + strconv.Itoa(int(expiry))))) for expiry futures markets
quoteTokenMeta TokenMeta
ticker string A name of the pair in format AAA/BBB, where AAA is base asset, BBB is quote asset.
isPerpetual boolean True if the market is a perpetual swap market
makerFeeRate string Defines the fee percentage makers pay when trading (in quote asset)
minPriceTickSize string Defines the minimum required tick size for the order's price
oracleQuote string Oracle quote currency
oracleType string Oracle Type
quoteDenom string Coin denom used for the quote asset.
expiryFuturesMarketInfo ExpiryFuturesMarketInfo
initialMarginRatio string Defines the initial margin ratio of a derivative market
marketStatus string The status of the market (Should be one of: [active paused suspended demolished expired])
minQuantityTickSize string Defines the minimum required tick size for the order's quantity
oracleScaleFactor integer OracleScaleFactor
takerFeeRate string Defines the fee percentage takers pay when trading (in quote asset)
oracleBase string Oracle base currency
perpetualMarketFunding PerpetualMarketFunding
perpetualMarketInfo PerpetualMarketInfo
serviceProviderFee string Percentage of the transaction fee shared with the service provider

TokenMeta:

Parameter Type Description
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
updatedAt integer Token metadata fetched timestamp in UNIX millis.

ExpiryFuturesMarketInfo:

Parameter Type Description
settlementPrice string Defines the settlement price for a time expiry futures market.
expirationTimestamp integer Defines the expiration time for a time expiry futures market in UNIX seconds.

PerpetualMarketFunding:

Parameter Type Description
cumulativeFunding string Defines the cumulative funding of a perpetual market.
cumulativePrice string Defines defines the cumulative price for the current hour up to the last timestamp.
lastTimestamp integer Defines the last funding timestamp in seconds of a perpetual market in UNIX seconds.

PerpetualMarketInfo:

Parameter Type Description
fundingInterval integer Defines the funding interval in seconds of a perpetual market in seconds.
hourlyFundingRateCap string Defines the default maximum absolute value of the hourly funding rate of the perpetual market.
hourlyInterestRate string Defines the hourly interest rate of the perpetual market.
nextFundingTimestamp integer Defines the next funding timestamp in seconds of a perpetual market in UNIX seconds.

Orders

Get orders of a derivative market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    subaccount_id= "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    order_side = "buy" # buy or sell
    orders = client.get_derivative_orders(market_id=market_id, order_side=order_side, subaccount_id=subaccount_id)
    print(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

Response Parameters

Response Example:

{
  "orders": [
    {
      "createdAt": 1544614248000,
      "feeRecipient": "inj15gnk95hvqrsr343ecqjuv7yf2af9rkdqeax52d",
      "isReduceOnly": false,
      "margin": "20000000000.000000000000000000",
      "marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
      "orderHash": "0x92da72606d9d26bbc5a8a5578373c6bbe11e39d0944788b5cd142a14d01f9d36",
      "orderSide": "buy",
      "price": "50900000000.000000000000000000",
      "quantity": "0.200000000000000000",
      "state": "partial_filled",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "triggerPrice": "0",
      "unfilledQuantity": "0.200000000000000000",
      "updatedAt": 1544614248000
    },
    {
      "createdAt": 1544614248000,
      "feeRecipient": "inj15gnk95hvqrsr343ecqjuv7yf2af9rkdqeax52d",
      "isReduceOnly": false,
      "margin": "20000000000.000000000000000000",
      "marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
      "orderHash": "0x92da72606d9d26bbc5a8a5578373c6bbe11e39d0944788b5cd142a14d01f9d36",
      "orderSide": "buy",
      "price": "50900000000.000000000000000000",
      "quantity": "0.200000000000000000",
      "state": "partial_filled",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "triggerPrice": "0",
      "unfilledQuantity": "0.200000000000000000",
      "updatedAt": 1544614248000
    }
  ]
}
Parameter Type Description
orders Array of DerivativeLimitOrder List of derivative market orders

DerivativeLimitOrder:

Parameter Type Description
feeRecipient string Fee recipient address
orderHash string Hash of the order
quantity string Quantity of the order
state string Order state (Should be one of: [booked partial_filled filled canceled])
triggerPrice string Trigger price is the trigger price used by stop/take orders
marketId string Derivative Market ID
createdAt integer Order committed timestamp in UNIX millis.
price string Price of the order
subaccountId string The subaccountId that this order belongs to
updatedAt integer Order updated timestamp in UNIX millis.
isReduceOnly boolean True if the order is a reduce-only order
margin string Margin of the order
orderSide string The type of the order (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell])
unfilledQuantity string The amount of the quantity remaining unfilled

StreamOrders

Stream order updates of a derivative market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    order_side = "buy" # buy or sell
    orders = client.stream_derivative_orders(market_id=market_id, order_side=order_side, subaccount_id=subaccount_id)
    for order in orders:
        print(order)
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:

{
  "operationType": "update",
  "order": {
    "createdAt": 1544614248000,
    "feeRecipient": "inj15gnk95hvqrsr343ecqjuv7yf2af9rkdqeax52d",
    "isReduceOnly": false,
    "margin": "20000000000.000000000000000000",
    "marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
    "orderHash": "0x92da72606d9d26bbc5a8a5578373c6bbe11e39d0944788b5cd142a14d01f9d36",
    "orderSide": "buy",
    "price": "50900000000.000000000000000000",
    "quantity": "0.200000000000000000",
    "state": "partial_filled",
    "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
    "triggerPrice": "0",
    "unfilledQuantity": "0.200000000000000000",
    "updatedAt": 1544614248000
  },
  "timestamp": 1544614248000
}
Parameter Type Description
timestamp integer Operation timestamp in UNIX millis.
operationType string Order update type (Should be one of: [insert delete replace update invalidate])
order DerivativeLimitOrder

DerivativeLimitOrder:

Parameter Type Description
subaccountId string The subaccountId that this order belongs to
updatedAt integer Order updated timestamp in UNIX millis.
createdAt integer Order committed timestamp in UNIX millis.
price string Price of the order
orderSide string The type of the order (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell])
unfilledQuantity string The amount of the quantity remaining unfilled
isReduceOnly boolean True if the order is a reduce-only order
margin string Margin of the order
quantity string Quantity of the order
state string Order state (Should be one of: [booked partial_filled filled canceled])
triggerPrice string Trigger price is the trigger price used by stop/take orders
feeRecipient string Fee recipient address
orderHash string Hash of the order
marketId string Derivative Market ID

Trades

Get trades of a derivative market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    trades = client.get_derivative_trades(market_id=market_id, subaccount_id=subaccount_id)
    print(trades)
Parameter Type Description Required
market_id string Filter by Market ID Yes
subaccount_id string Filter by Subaccount ID No

Response Parameters

Response Example:

{
  "trades": [
    {
      "executedAt": 1544614248000,
      "fee": "150428.571428571428571429",
      "isLiquidation": false,
      "marketId": "0xb6fa659501d170f3bfbbc16f9e3e46e8435d3b13cb2ceeed5945ddd16df435ef",
      "orderHash": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "payout": "0",
      "positionDelta": {
        "executionMargin": "50000000",
        "executionPrice": "12535714.285714285714285714",
        "executionQuantity": "6",
        "tradeDirection": "buy"
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "tradeExecutionType": "market"
    },
    {
      "executedAt": 1544614248000,
      "fee": "150428.571428571428571429",
      "isLiquidation": false,
      "marketId": "0xb6fa659501d170f3bfbbc16f9e3e46e8435d3b13cb2ceeed5945ddd16df435ef",
      "orderHash": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "payout": "0",
      "positionDelta": {
        "executionMargin": "50000000",
        "executionPrice": "12535714.285714285714285714",
        "executionQuantity": "6",
        "tradeDirection": "buy"
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "tradeExecutionType": "market"
    }
  ]
}
Parameter Type Description
trades Array of DerivativeTrade Trades of a Derivative Market

DerivativeTrade:

Parameter Type Description
executedAt integer Timestamp of trade execution in UNIX millis
positionDelta PositionDelta
subaccountId string The subaccountId that executed the trade
tradeExecutionType string The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder])
fee string The fee associated with the trade
isLiquidation boolean True if the trade is a liquidation
marketId string The ID of the market that this trade is in
orderHash string Order hash.
payout string The payout associated with the trade

PositionDelta:

Parameter Type Description
executionPrice string Execution Price of the trade.
executionQuantity string Execution Quantity of the trade.
tradeDirection string The direction the trade (Should be one of: [buy sell])
executionMargin string Execution Margin of the trade.

StreamTrades

Stream trades of a derivative market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    trades = client.stream_derivative_trades(market_id=market_id, subaccount_id=subaccount_id)
    for trade in trades:
        print(trade)
Parameter Type Description Required
market_id string Filter by Market ID Yes
subaccount_id string Filter by Subaccount ID No

Response Parameters

Streaming Response Example:

{
  "operationType": "insert",
  "timestamp": 1544614248000,
  "trade": {
    "executedAt": 1544614248000,
    "fee": "150428.571428571428571429",
    "isLiquidation": false,
    "marketId": "0xb6fa659501d170f3bfbbc16f9e3e46e8435d3b13cb2ceeed5945ddd16df435ef",
    "orderHash": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
    "payout": "0",
    "positionDelta": {
      "executionMargin": "50000000",
      "executionPrice": "12535714.285714285714285714",
      "executionQuantity": "6",
      "tradeDirection": "buy"
    },
    "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
    "tradeExecutionType": "market"
  }
}
Parameter Type Description
operationType string Executed trades update type (Should be one of: [insert invalidate])
timestamp integer Operation timestamp in UNIX millis.
trade DerivativeTrade

DerivativeTrade:

Parameter Type Description
fee string The fee associated with the trade
isLiquidation boolean True if the trade is a liquidation
marketId string The ID of the market that this trade is in
orderHash string Order hash.
payout string The payout associated with the trade
subaccountId string The subaccountId that executed the trade
tradeExecutionType string The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder])
executedAt integer Timestamp of trade execution in UNIX millis
positionDelta PositionDelta

PositionDelta:

Parameter Type Description
executionMargin string Execution Margin of the trade.
executionPrice string Execution Price of the trade.
executionQuantity string Execution Quantity of the trade.
tradeDirection string The direction the trade (Should be one of: [buy sell])

Positions

Get the positions of a market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    positions = client.get_derivative_positions(market_id=market_id, subaccount_id=subaccount_id)
    print(positions)
Parameter Type Description Required
market_id string Filter by Market ID Yes
subaccount_id string Filter by Subaccount ID No

Response Parameters

Response Example:

{
  "positions": [
    {
      "aggregateReduceOnlyQuantity": "0",
      "direction": "long",
      "entryPrice": "15333333.333333333333333333",
      "liquidationPrice": "23420479",
      "margin": "77000000",
      "markPrice": "14000000",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "quantity": "9",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "ticker": "INJ/USDT-PERP"
    },
    {
      "aggregateReduceOnlyQuantity": "0",
      "direction": "long",
      "entryPrice": "15333333.333333333333333333",
      "liquidationPrice": "23420479",
      "margin": "77000000",
      "markPrice": "14000000",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "quantity": "9",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "ticker": "INJ/USDT-PERP"
    },
  ]
}
Parameter Type Description
positions Array of DerivativePosition List of derivative positions

DerivativePosition:

Parameter Type Description
direction string Direction of the position (Should be one of: [long short])
marketId string Derivative Market ID
subaccountId string The subaccountId that the position belongs to
ticker string Ticker of the derivative market
aggregateReduceOnlyQuantity string Aggregate Quantity of the Reduce Only orders associated with the position
entryPrice string Price of the position
liquidationPrice string LiquidationPrice of the position
margin string Margin of the position
markPrice string MarkPrice of the position
quantity string Quantity of the position

StreamPositions

Stream position updates for a specific market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    subaccount_id = "0xc6fe5d33615a1c52c08018c47e8bc53646a0e101000000000000000000000000"
    positions = client.stream_derivative_positions(market_id=market_id, subaccount_id=subaccount_id)
    for position in positions:
        print(position)
Parameter Type Description Required
market_id string Filter by Market ID Yes
subaccount_id string Filter by Subaccount ID No

Response Parameters

Streaming Response Example:

{
  "position": {
    "aggregateReduceOnlyQuantity": "0",
    "direction": "long",
    "entryPrice": "15333333.333333333333333333",
    "liquidationPrice": "23420479",
    "margin": "77000000",
    "markPrice": "14000000",
    "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
    "quantity": "9",
    "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
    "ticker": "INJ/USDT-PERP"
  },
  "timestamp": 1544614248000
}
Parameter Type Description
position DerivativePosition
timestamp integer Operation timestamp in UNIX millis.

DerivativePosition:

Parameter Type Description
aggregateReduceOnlyQuantity string Aggregate Quantity of the Reduce Only orders associated with the position
entryPrice string Price of the position
liquidationPrice string LiquidationPrice of the position
margin string Margin of the position
markPrice string MarkPrice of the position
quantity string Quantity of the position
direction string Direction of the position (Should be one of: [long short])
marketId string Derivative Market ID
subaccountId string The subaccountId that the position belongs to
ticker string Ticker of the derivative market

Orderbook

Get the orderbook of a derivative market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    market = client.get_derivative_orderbook(market_id=market_id)
    print(market)
Parameter Type Description Required
market_id string Filter by Market ID Yes

Response Parameters

Response Example:

{
  "orderbook": {
    "buys": [
      {
        "price": "41236062000",
        "quantity": "0.15",
        "timestamp": 1632184552530
      },
      {
        "price": "41186284000",
        "quantity": "0.15",
        "timestamp": 1632183950930
      }
    ],
    "sells": [
      {
        "price": "43015302000",
        "quantity": "0.05",
        "timestamp": 1632241829042
      },
      {
        "price": "43141817000",
        "quantity": "0.3",
        "timestamp": 1632242197021
      }
    ]
  }
}
Parameter Type Description
orderbook DerivativeLimitOrderbook

DerivativeLimitOrderbook:

Parameter Type Description
buys Array of PriceLevel Array of price levels for buys
sells Array of PriceLevel Array of price levels for sells

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.

StreamOrderbook

Stream orderbook updates for a derivative market

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    markets = client.stream_derivative_orderbook(market_id=market_id)
    for market in markets:
        print(market)
Parameter Type Description Required
market_id string Filter by Market ID Yes

Response Parameters

Streaming Response Example:

{
  "operationType": "update",
  "orderbook": {
    "buys": [
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      }
    ],
    "sells": [
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      },
      {
        "price": "1960000000000000000",
        "quantity": "40",
        "timestamp": 1544614248000
      }
    ]
  },
  "timestamp": 1544614248000
}
Parameter Type Description
operationType string Order update type (Should be one of: [insert delete replace update invalidate])
orderbook DerivativeLimitOrderbook
timestamp integer Operation timestamp in UNIX millis.

DerivativeLimitOrderbook:

Parameter Type Description
buys Array of PriceLevel Array of price levels for buys
sells Array of PriceLevel Array of price levels for sells

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.

LiquidablePositions

Get the positions that are subject to liquidation

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    liquidable_positions = client.get_derivative_liquidable_positions(market_id=market_id)
    print(liquidable_positions)
Parameter Type Description Required
market_id string Filter by Market ID No

Response Parameters

Response Example:

{
  "positions": [
    {
      "aggregateReduceOnlyQuantity": "0",
      "direction": "long",
      "entryPrice": "15333333.333333333333333333",
      "liquidationPrice": "23420479",
      "margin": "77000000",
      "markPrice": "14000000",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "quantity": "9",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "ticker": "INJ/USDT-PERP"
    },
    {
      "aggregateReduceOnlyQuantity": "0",
      "direction": "long",
      "entryPrice": "15333333.333333333333333333",
      "liquidationPrice": "23420479",
      "margin": "77000000",
      "markPrice": "14000000",
      "marketId": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "quantity": "9",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "ticker": "INJ/USDT-PERP"
    }
  ]
}
Parameter Type Description
positions Array of DerivativePosition List of derivative positions

DerivativePosition:

Parameter Type Description
subaccountId string The subaccountId that the position belongs to
ticker string Ticker of the derivative market
direction string Direction of the position (Should be one of: [long short])
marketId string Derivative Market ID
liquidationPrice string LiquidationPrice of the position
margin string Margin of the position
markPrice string MarkPrice of the position
quantity string Quantity of the position
aggregateReduceOnlyQuantity string Aggregate Quantity of the Reduce Only orders associated with the position
entryPrice string Price of the position

SubaccountOrdersList

Get the derivative orders of a specific subaccount

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    market_id = "0x897519d4cf8c460481638b3ff64871668d0a7f6afea10c1b0a952c0b5927f48f"
    orders = client.get_derivative_subaccount_orders(subaccount_id=subaccount_id, market_id=market_id)
    print(orders)
Parameter Type Description Required
subaccount_id string Filter by Subaccount ID Yes
market_id string Filter by Market ID No

Response Parameters

Response Example:

{
  "orders": [
    {
      "createdAt": 1544614248000,
      "feeRecipient": "inj15gnk95hvqrsr343ecqjuv7yf2af9rkdqeax52d",
      "isReduceOnly": false,
      "margin": "20000000000.000000000000000000",
      "marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
      "orderHash": "0x92da72606d9d26bbc5a8a5578373c6bbe11e39d0944788b5cd142a14d01f9d36",
      "orderSide": "buy",
      "price": "50900000000.000000000000000000",
      "quantity": "0.200000000000000000",
      "state": "partial_filled",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "triggerPrice": "0",
      "unfilledQuantity": "0.200000000000000000",
      "updatedAt": 1544614248000
    },
    {
      "createdAt": 1544614248000,
      "feeRecipient": "inj15gnk95hvqrsr343ecqjuv7yf2af9rkdqeax52d",
      "isReduceOnly": false,
      "margin": "20000000000.000000000000000000",
      "marketId": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
      "orderHash": "0x92da72606d9d26bbc5a8a5578373c6bbe11e39d0944788b5cd142a14d01f9d36",
      "orderSide": "buy",
      "price": "50900000000.000000000000000000",
      "quantity": "0.200000000000000000",
      "state": "partial_filled",
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "triggerPrice": "0",
      "unfilledQuantity": "0.200000000000000000",
      "updatedAt": 1544614248000
    }
  ]
}
Parameter Type Description
orders Array of DerivativeLimitOrder List of derivative orders

DerivativeLimitOrder:

Parameter Type Description
marketId string Derivative Market ID
createdAt integer Order committed timestamp in UNIX millis.
price string Price of the order
subaccountId string The subaccountId that this order belongs to
updatedAt integer Order updated timestamp in UNIX millis.
isReduceOnly boolean True if the order is a reduce-only order
margin string Margin of the order
orderSide string The type of the order (Should be one of: [buy sell stop_buy stop_sell take_buy take_sell])
unfilledQuantity string The amount of the quantity remaining unfilled
feeRecipient string Fee recipient address
orderHash string Hash of the order
quantity string Quantity of the order
state string Order state (Should be one of: [booked partial_filled filled canceled])
triggerPrice string Trigger price is the trigger price used by stop/take orders

SubaccountTradesList

Get the derivative trades for a specific subaccount

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    market_id = "0x0f4209dbe160ce7b09559c69012d2f5fd73070f8552699a9b77aebda16ccdeb1"
    execution_type = "market" # market, limitFill, limitMatchRestingOrder or limitMatchNewOrder
    direction = "sell" # buy or sell
    trades = client.get_derivative_subaccount_trades(subaccount_id=subaccount_id, market_id=market_id, execution_type=execution_type, direction=direction)
    print(trades)
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

Response Parameters

Response Example:

{
  "trades": [
    {
      "executedAt": 1544614248000,
      "fee": "150428.571428571428571429",
      "isLiquidation": false,
      "marketId": "0xb6fa659501d170f3bfbbc16f9e3e46e8435d3b13cb2ceeed5945ddd16df435ef",
      "orderHash": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "payout": "0",
      "positionDelta": {
        "executionMargin": "50000000",
        "executionPrice": "12535714.285714285714285714",
        "executionQuantity": "6",
        "tradeDirection": "buy"
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "tradeExecutionType": "market"
    },
    {
      "executedAt": 1544614248000,
      "fee": "150428.571428571428571429",
      "isLiquidation": false,
      "marketId": "0xb6fa659501d170f3bfbbc16f9e3e46e8435d3b13cb2ceeed5945ddd16df435ef",
      "orderHash": "0x3bdb3d8b5eb4d362371b72cf459216553d74abdb55eb0208091f7777dd85c8bb",
      "payout": "0",
      "positionDelta": {
        "executionMargin": "50000000",
        "executionPrice": "12535714.285714285714285714",
        "executionQuantity": "6",
        "tradeDirection": "buy"
      },
      "subaccountId": "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1000000000000000000000002",
      "tradeExecutionType": "market"
    },
  ]
}
Parameter Type Description
trades Array of DerivativeTrade List of derivative market trades

DerivativeTrade:

Parameter Type Description
orderHash string Order hash.
payout string The payout associated with the trade
subaccountId string The subaccountId that executed the trade
tradeExecutionType string The execution type of the trade (Should be one of: [market limitFill limitMatchRestingOrder limitMatchNewOrder])
fee string The fee associated with the trade
isLiquidation boolean True if the trade is a liquidation
marketId string The ID of the market that this trade is in
executedAt integer Timestamp of trade execution in UNIX millis
positionDelta PositionDelta

PositionDelta:

Parameter Type Description
executionPrice string Execution Price of the trade.
executionQuantity string Execution Quantity of the trade.
tradeDirection string The direction the trade (Should be one of: [buy sell])
executionMargin string Execution Margin of the trade.

FundingPayments

Get the funding payments for a subaccount

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    network = Network.testnet()
    client = Client(network, insecure=True)
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    subaccount_id = "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    funding = client.get_funding_payments(market_id=market_id, subaccount_id=subaccount_id)
    print(funding)
Parameter Type Description Required
subaccount_id string Filter by Subaccount ID Yes
market_id string Filter by Market ID No

Response Parameters

Streaming Response Example:

{
"payments": {
  "market_id": "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce",
  "subaccount_id": "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000",
  "amount": "79677138",
  "timestamp": 1634515200458
}

}
Parameter Type Description
market_id string Derivative Market ID
subaccount_id string The subaccountId of the funding payments
amount string The amount of the funding payment
timestamp integer Operation 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 grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    oracle_list = client.get_oracle_list()
    print(oracle_list)

Response Parameters

Response Example:

{
   "oracles" {
  "symbol": "ADA",
  "oracle_type": "band",
  "price": "2.797398",
}
"oracles" {
  "symbol": "AKRO",
  "oracle_type": "band",
  "price": "0.0333066"
}
"oracles" {
  "symbol": "AMPL",
  "oracle_type": "band",
  "price": "0.955257"
}

}

Parameter Type Description
oracles Array of Oracle

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 grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    base_symbol = 'BTC'
    quote_symbol = 'USD'
    oracle_type = 'coinbase'
    oracle_scale_factor = 6
    oracle_prices = 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)
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": "46361990000"
}
Parameter Type Description
price string The price of the oracle asset

StreamPrices

Stream oracle prices for an asset

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    base_symbol = 'BTC'
    quote_symbol = 'USD'
    oracle_type = 'coinbase'
    oracle_prices = client.stream_oracle_prices(
        base_symbol=base_symbol,
        quote_symbol=quote_symbol,
        oracle_type=oracle_type
    )
    for oracle in oracle_prices:
        print(oracle)
Parameter Type Description Required
base_symbol string Oracle base currency Yes
quote_symbol string Oracle quote currency Yes
oracle_type string The oracle provider Yes

Response Parameters

Streaming Response Example:

{
  "price": "14.01",
  "timestamp": 1544614248000
}
Parameter Type Description
price string The price of the oracle asset
timestamp integer Operation timestamp in UNIX millis.

- InjectiveInsuranceRPC

InjectiveInsuranceRPC defines the gRPC API of the Insurance Exchange provider.

Funds

Funds lists all insurance funds.

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    insurance_funds = client.get_insurance_funds()
    print(insurance_funds)

Response Parameters

Response Example:

{
  "funds": [
    {
      "balance": "10000000000",
      "depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "depositTokenMeta": {
        "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
        "decimals": 18,
        "logo": "https://static.alchemyapi.io/images/assets/825.png",
        "name": "Tether",
        "symbol": "USDT",
        "updatedAt": 1544614248000
      },
      "expiry": 0,
      "marketId": "0x682410b0003227bb0eb3fb5bb0ad0f176cb9356c5177f234f4ff0002f339c763",
      "marketTicker": "INJ/USDT PERP",
      "oracleBase": "INJ",
      "oracleQuote": "USDT",
      "oracleType": "band",
      "poolTokenDenom": "share2",
      "redemptionNoticePeriodDuration": 1209600,
      "totalShare": "100000000000000000"
    },
    {
      "balance": "10000000000",
      "depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "depositTokenMeta": {
        "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
        "decimals": 18,
        "logo": "https://static.alchemyapi.io/images/assets/825.png",
        "name": "Tether",
        "symbol": "USDT",
        "updatedAt": 1544614248000
      },
      "expiry": 0,
      "marketId": "0x682410b0003227bb0eb3fb5bb0ad0f176cb9356c5177f234f4ff0002f339c763",
      "marketTicker": "INJ/USDT PERP",
      "oracleBase": "INJ",
      "oracleQuote": "USDT",
      "oracleType": "band",
      "poolTokenDenom": "share2",
      "redemptionNoticePeriodDuration": 1209600,
      "totalShare": "100000000000000000"
    },
    {
      "balance": "10000000000",
      "depositDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "depositTokenMeta": {
        "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
        "decimals": 18,
        "logo": "https://static.alchemyapi.io/images/assets/825.png",
        "name": "Tether",
        "symbol": "USDT",
        "updatedAt": 1544614248000
      },
      "expiry": 0,
      "marketId": "0x682410b0003227bb0eb3fb5bb0ad0f176cb9356c5177f234f4ff0002f339c763",
      "marketTicker": "INJ/USDT PERP",
      "oracleBase": "INJ",
      "oracleQuote": "USDT",
      "oracleType": "band",
      "poolTokenDenom": "share2",
      "redemptionNoticePeriodDuration": 1209600,
      "totalShare": "100000000000000000"
    }
  ]
}
Parameter Type Description
funds Array of InsuranceFund

InsuranceFund:

Parameter Type Description
oracleType string Oracle Type
poolTokenDenom string Pool token denom
totalShare string
balance string
oracleBase string Oracle base currency
expiry integer Defines the expiry, if any
marketId string Derivative Market ID
marketTicker string Ticker of the derivative market.
oracleQuote string Oracle quote currency
redemptionNoticePeriodDuration integer Redemption notice period duration in seconds.
depositDenom string Coin denom used for the underwriting of the insurance fund.
depositTokenMeta TokenMeta

TokenMeta:

Parameter Type Description
updatedAt 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

Redemptions

PendingRedemptions lists all pending redemptions according to a filter

Request Parameters

Request Example:

import grpc

from pyinjective.client import Client
from pyinjective.constant import Network

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    client = Client(network, insecure=True)
    redeemer = "inj1gxqdj76ul07w4ujsl8403nhhzyvug2h66qk057"
    redemption_denom = "share2"
    status = "disbursed" # disbursed or pending
    insurance_redemptions = client.get_redemptions(redeemer=redeemer, redemption_denom=redemption_denom, status=status)
    print(insurance_redemptions)
Parameter Type Description Required
redeemer string Filter by Account Address No
redemptionDenom string Filter by Insurance Pool Denom No
status string Filter by Redemption Status (Should be one of: [disbursed pending]) No

Response Parameters

Response Example:

{
  "redemptionSchedules": [
    {
      "claimableRedemptionTime": 1628625970303000,
      "disbursedAmount": "1000",
      "disbursedAt": 1621243123000,
      "disbursedDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "redeemer": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "redemptionAmount": "1000",
      "redemptionDenom": "share2",
      "redemptionId": 4,
      "requestedAt": 1621243113000,
      "status": "pending"
    },
    {
      "claimableRedemptionTime": 1628625970303000,
      "disbursedAmount": "1000",
      "disbursedAt": 1621243123000,
      "disbursedDenom": "peggy0xdAC17F958D2ee523a2206206994597C13D831ec7",
      "redeemer": "inj1cml96vmptgw99syqrrz8az79xer2pcgp0a885r",
      "redemptionAmount": "1000",
      "redemptionDenom": "share2",
      "redemptionId": 4,
      "requestedAt": 1621243113000,
      "status": "pending"
    }
  ]
}
Parameter Type Description
redemptionSchedules Array of RedemptionSchedule

RedemptionSchedule:

Parameter Type Description
claimableRedemptionTime integer Claimable redemption time in seconds
redeemer string Account address of the redemption owner
redemptionDenom string Pool token denom being redeemed.
requestedAt integer Redemption request time in unix milliseconds.
status string Status of the redemption. Either pending or disbursed.
disbursedAmount string Amount of quote tokens disbursed
disbursedAt integer Redemption disbursement time in unix milliseconds.
disbursedDenom string Denom of the quote tokens disbursed
redemptionAmount string Amount of pool tokens being redeemed.
redemptionId integer Redemption ID.

Chain API

Initialize Client

Import dependencies from injective-py and configure the gRPC client in order to send messages to the Injective Chain. You can include multiple messages in a single transaction.

from pyinjective.composer import Composer as ProtoMsgComposer
from pyinjective.client import Client
from pyinjective.transaction import Transaction
from pyinjective.constant import Network
from pyinjective.wallet import PrivateKey, PublicKey, Address

async def main() -> None:
    # select network: local, testnet, mainnet
    network = Network.testnet()
    composer = ProtoMsgComposer(network=network.string())

    # initialize grpc client
    client = Client(network, insecure=True)

    # load account
    priv_key = PrivateKey.from_hex("5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e")
    pub_key =  priv_key.to_public_key()
    address = await pub_key.to_address().init_num_seq(network.lcd_endpoint)
    subaccount_id = address.get_subaccount_id(index=0)

    print(subaccount_id)

- Derivatives

Includes all the messages related to derivative markets.

MsgCreateDerivativeMarketOrder

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"

    # prepare tx msg
    msg = composer.MsgCreateDerivativeMarketOrder(
        sender=address.to_acc_bech32(),
        market_id=market_id,
        subaccount_id=subaccount_id,
        fee_recipient=fee_recipient,
        price=60000,
        quantity=0.01,
        leverage=3,
        isBuy=True
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
sender string The inj address of the sender Yes
subaccount_id string The subaccount we want to send an order from Yes
fee_recipient string The address that will receive 40% of the trading fees, this could be set to your own address Yes
price float The price of the base asset Yes
quantity float The quantity of the base asset Yes
leverage float The leverage factor for the order Yes
isBuy boolean Set to true or false for buy and sell orders respectively Yes

Response Example:

{

"simulation msg response"
["order_hash:" "0x6cc1c3d7653a1b526a332024b12b5e09d0ff306ce842d1ebb3599faff23b06fd"]
"tx response"
"txhash:" "E1C0F4B6C2F0AF2C256373AB648F58E3F63DEA1BCD2EB5AD323002E99DF83B4D"

"tx msg response"
[]

}

MsgCreateDerivativeLimitOrder

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"

    # prepare tx msg
    msg = composer.MsgCreateDerivativeLimitOrder(
        sender=address.to_acc_bech32(),
        market_id=market_id,
        subaccount_id=subaccount_id,
        fee_recipient=fee_recipient,
        price=44054.48,
        quantity=0.01,
        leverage=0.7,
        isBuy=True
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
sender string The inj address of the sender Yes
subaccount_id string The subaccount we want to send an order from Yes
fee_recipient string The address that will receive 40% of the fees, this could be set to your own address Yes
price float The price of the base asset Yes
quantity float The quantity of the base asset Yes
leverage float The leverage factor for the order Yes
isBuy boolean Set to true or false for buy and sell orders respectively Yes

Response Example:

{

"simulation msg response"
["order_hash:" "0x0531e3c17cbdc5c535a0a0cfa20d354187ee1256236c3a7d47db227b107aa6dd"]
"tx response"
"txhash:" "95AE4D127F8F6FB4C2ACA0D5063624B124B938B298E4661FB3C5FE1F53A2A90F",

"tx msg response"
"[]"

}

MsgCancelDerivativeOrder

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    order_hash = "0x7d0b95cfc0fb5901ba4d686060074107eaff6bbcc9eba25823d16fa21508bfeb"

    # prepare tx msg
    msg = composer.MsgCancelDerivativeOrder(
        sender=address.to_acc_bech32(),
        market_id=market_id,
        subaccount_id=subaccount_id,
        order_hash=order_hash
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
sender string The inj address of the sender Yes
subaccount_id string The subaccount we want to send an order from Yes
order_hash string The order hash of a specific order Yes

Response Example:

{

"tx response"
"txhash:" "20A3DC0B931D54DC20991FE2727249DBB2CFB00364C03DAAD4099263871F5D0D"

}

MsgBatchCreateDerivativeLimitOrders

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"

    orders = [
        composer.DerivativeOrder(
            market_id=market_id,
            subaccount_id=subaccount_id,
            fee_recipient=fee_recipient,
            price=41027,
            quantity=0.01,
            leverage=0.7,
            isBuy=True
        ),
        composer.DerivativeOrder(
            market_id=market_id,
            subaccount_id=subaccount_id,
            fee_recipient=fee_recipient,
            price=62140,
            quantity=0.01,
            leverage=1.4,
            isBuy=False
        ),
    ]

    # prepare tx msg
    msg = composer.MsgBatchCreateDerivativeLimitOrders(
        sender=address.to_acc_bech32(),
        orders=orders
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
sender string The inj address of the sender Yes
orders Array Yes

orders:

Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
subaccount_id string The subaccount we want to send an order from Yes
fee_recipient string The address that will receive 40% of the fees this could be set to your own address Yes
price float The price of the base asset Yes
quantity float The quantity of the base asset Yes
leverage float The leverage factor for a specific order Yes
isBuy boolean Set to true or false for buy and sell orders respectively Yes

Response Example:

{

"simulation msg response"
["order_hashes:" "0xfcbedb1f8135204e7d8b8e6e683042e61834435fb7841b9ef243ef7196ec6938",
"order_hashes:" "0x0d19f6a10ad017abeac1b14070fec5d044128e40902085654f4da4055a8f6510"]
"tx response"
"txhash:" "B74104A1EC4C7000C421236D78EE29157DE1B857268EC834024BD44401B2B9B2"

"tx msg response"
"[]"

}

MsgBatchCancelDerivativeOrders

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xd0f46edfba58827fe692aab7c8d46395d1696239fdf6aeddfa668b73ca82ea30"
    orders = [
        composer.OrderData(
            market_id=market_id,
            subaccount_id=subaccount_id,
            order_hash="0xfcbedb1f8135204e7d8b8e6e683042e61834435fb7841b9ef243ef7196ec6938"
        ),
        composer.OrderData(
            market_id=market_id,
            subaccount_id=subaccount_id,
            order_hash="0x0d19f6a10ad017abeac1b14070fec5d044128e40902085654f4da4055a8f6510"
        )
    ]

    # prepare tx msg
    msg = composer.MsgBatchCancelDerivativeOrders(
        sender=address.to_acc_bech32(),
        data=orders
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
sender string The inj address of the sender Yes
orders Array Yes

orders:

Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
subaccount_id string The subaccount we want to send an order from Yes
order_hash string The order hash of a specific order Yes

Response Example:

{

"simulation msg response"
["success:" "true"
"success:" "true"]
"tx response"
"txhash:" "03F2EE49F66731C8DA70958093F0EDF24D046EF31AED3A0C79D639D67F7A1ADB"

"tx msg response"
"[]"

}

MsgIncreasePositionMargin

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0x0f4209dbe160ce7b09559c69012d2f5fd73070f8552699a9b77aebda16ccdeb1"

    # prepare tx msg
    msg = composer.MsgIncreasePositionMargin(
        sender=address.to_acc_bech32(),
        market_id=market_id,
        source_subaccount_id=subaccount_id,
        destination_subaccount_id=subaccount_id,
        amount=2
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
Parameter Type Description Required
sender string The inj address of the sender Yes
market_id string MarketId of the market we want to increase the margin Yes
source_subaccount_id string The subaccount to send funds from Yes
destination_subaccount_id string The subaccount to send funds to Yes
amount string The amount of tokens to be used as additional margin Yes

Response Example:

{

"height": "8735988",
"txhash": "54AA465B6FEABE1A08BDD0AD156D5FE9E4AE43AF453CE6E5B6449D233BAEA05F",
"data": "0A370A352F696E6A6563746976652E65786368616E67652E763162657461312E4D7367496E637265617365506F736974696F6E4D617267696E",
"raw_log": "[{\"events\":[{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"/injective.exchange.v1beta1.MsgIncreasePositionMargin\"}]}]}]",
"logs" {
  "events" {
    "type": "message",
    "attributes" {
      "key": "action",
      "value": "/injective.exchange.v1beta1.MsgIncreasePositionMargin"
    }
  }
}
"gas_wanted": "200000",
"gas_used": "91580"

}

MsgLiquidatePosition

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0x31200279ada822061217372150d567be124f02df157650395d1d6ce58a8207aa"

    # prepare tx msg
    msg = composer.MsgLiquidatePosition(
        sender=address.to_acc_bech32(),
        market_id=market_id,
        subaccount_id="0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000"
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
sender string The inj address of the sender Yes
market_id string MarketId of the market we want to increase the margin Yes
subaccount_id string The subaccount with the liquidable position Yes

Response Example:

{


}

- Spot

Includes all the messages related to spot markets.

MsgCreateSpotMarketOrder

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"

    # prepare tx msg
    msg = composer.MsgCreateSpotMarketOrder(
        sender=address.to_acc_bech32(),
        market_id=market_id,
        subaccount_id=subaccount_id,
        fee_recipient=fee_recipient,
        price=10.522,
        quantity=0.01,
        isBuy=True
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
sender string The inj address of the sender Yes
subaccount_id string The subaccount we want to send an order from Yes
fee_recipient string The address that will receive 40% of the fees, this could be set to your own address Yes
price float The price of the base asset Yes
quantity float The quantity of the base asset Yes
isBuy boolean Set to true or false for buy and sell orders respectively Yes

Response Example:

{

"simulation msg response"
["order_hash:" "0x61fa86cbc82d6892d066ca340a5e547469a4bd8d00d76cdc05b43e0c37a09505"]
"tx response"
"txhash:" "288403B6A767BC04212234395A6DF935AA6D711E58008391E4A1BF0003F868D1"

"tx msg response"
"[]"


}

MsgCreateSpotLimitOrder

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"

    # prepare tx msg
    msg = composer.MsgCreateSpotLimitOrder(
        sender=address.to_acc_bech32(),
        market_id=market_id,
        subaccount_id=subaccount_id,
        fee_recipient=fee_recipient,
        price=7.523,
        quantity=0.01,
        isBuy=True
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
sender string The inj address of the sender Yes
subaccount_id string The subaccount we want to send an order from Yes
fee_recipient string The address that will receive 40% of the fees, this could be set to your own address Yes
price float The price of the base asset Yes
quantity float The quantity of the base asset Yes
isBuy boolean Set to true or false for buy and sell orders respectively Yes

Response Example:

{

"simulation msg response"
["order_hash:" "0x6f24ab1a2ae1d772562239146090df0d6a7b6e503296ebbf7fbc9517d607e7b0"]
"tx response"
"txhash:" "E59DD5C4AFF42A55E7864F854EB2163AA178E348C6F258813A5F7CE7FADC9192"

"tx msg response"
"[]"



}

MsgCancelSpotOrder

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    order_hash = "0x9b250eacd9bde566506b811e02847059ba7a5eff54c04ec369f06d2de6b7f8fd"

    # prepare tx msg
    msg = composer.MsgCancelSpotOrder(
        sender=address.to_acc_bech32(),
        market_id=market_id,
        subaccount_id=subaccount_id,
        order_hash=order_hash
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
sender string The inj address of the sender Yes
subaccount_id string The subaccount we want to send an order from Yes
order_hash string The order hash of a specific order Yes

Response Example:

{

"tx response"
"txhash:" "4E12342489EB934F368855AE2BC8A2860A435D3A5A1F0C0AB5A4AA4DE8F05B0B"

}

MsgBatchCreateSpotLimitOrders

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    fee_recipient = "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"

    orders = [
        composer.SpotOrder(
            market_id=market_id,
            subaccount_id=subaccount_id,
            fee_recipient=fee_recipient,
            price=7.523,
            quantity=0.01,
            isBuy=True
        ),
        composer.SpotOrder(
            market_id=market_id,
            subaccount_id=subaccount_id,
            fee_recipient=fee_recipient,
            price=27.92,
            quantity=0.01,
            isBuy=False
        ),
    ]

    # prepare tx msg
    msg = composer.MsgBatchCreateSpotLimitOrders(
        sender=address.to_acc_bech32(),
        orders=orders
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
sender string The inj address of the sender Yes
orders Array Yes

orders:

Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
subaccount_id string The subaccount we want to send an order from Yes
fee_recipient string The address that will receive 40% of the fees, this could be set to your own address Yes
price float The price of the base asset Yes
quantity float The quantity of the base asset Yes
isBuy boolean Set to true or false for buy and sell orders respectively Yes

Response Example:

{

"simulation msg response"
["order_hashes:" "0x101ee98abc9a5922689ae070f64fedae78728bf73a822a91498b68793ac7b7e7"
"order_hashes:" "0x3d2750114faabe76c2433fd0eeb1e4e9be771ee3acac63c3689b880fb27227a2"]
"tx response"
"txhash:" "EE44F89530C1EAD7598872B86F73621190381A2DCE9A9446F9C5A839960DD323"

"tx msg response"
"[]"

}

MsgBatchCancelSpotOrders

Request Parameters

Request Example:

    # prepare trade info
    market_id = "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0"
    orders = [
        composer.OrderData(
            market_id=market_id,
            subaccount_id=subaccount_id,
            order_hash="0x3d2750114faabe76c2433fd0eeb1e4e9be771ee3acac63c3689b880fb27227a2"
        ),
        composer.OrderData(
            market_id=market_id,
            subaccount_id=subaccount_id,
            order_hash="0x101ee98abc9a5922689ae070f64fedae78728bf73a822a91498b68793ac7b7e7"
        ),
        composer.OrderData(
            market_id=market_id,
            subaccount_id=subaccount_id,
            order_hash="0x8d4e111127f91011bf77dea8b625948a14c1ae55d8c5d3f5af3dadbd6bec591d"
        )
    ]

    # prepare tx msg
    msg = composer.MsgBatchCancelSpotOrders(
        sender=address.to_acc_bech32(),
        data=orders
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    simResMsg = ProtoMsgComposer.MsgResponses(simRes.result.data, simulation=True)
    print("simulation msg response")
    print(simResMsg)

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
    print("tx msg response")
    print(resMsg)
Parameter Type Description Required
sender string The inj address of the sender Yes
orders Array Yes

orders:

Parameter Type Description Required
market_id string MarketId of the market we want to send an order Yes
subaccount_id string The subaccount we want to send an order from Yes
order_hash string The order hash of a specific order Yes

Response Example:

{

"simulation msg response"
["success:" "true"
"success:" "true"
"success:" "false"]
"tx response"
"txhash:" "24723C0EEF0157EA9C294B2CF66EF1BF97440F3CE965AFE1EC00A226E2EE4A7F"

"tx msg response"
"[]"

}

- Account

Includes all the messages related to accounts and transfers.

MsgSend

Request Parameters

Request Example:

    # prepare tx msg
    msg = composer.MsgSend(
        from_address=address.to_acc_bech32(),
        to_address='inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r',
        amount=0.000000000000000001,
        denom='INJ'
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)

    # print tx response
    print(res)
Parameter Type Description Required
from_address string The inj address of the sender Yes
to_address string The inj address of the receiver Yes
amount int The amount of tokens to send Yes
denom string The denom of that token Yes

Response Example:

{

"height": "8581276",
"txhash": "ED1A31933449525712EEFB2B27929117E291CC81E0827233E5C892F5D03EB9AB",
"data": "0A1E0A1C2F636F736D6F732E62616E6B2E763162657461312E4D736753656E64",
"raw_log": "[{\"events\":[{\"type\":\"coin_received\",\"attributes\":[{\"key\":\"receiver\",\"value\":\"inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]},{\"type\":\"coin_spent\",\"attributes\":[{\"key\":\"spender\",\"value\":\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]},{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"/cosmos.bank.v1beta1.MsgSend\"},{\"key\":\"sender\",\"value\":\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\"},{\"key\":\"module\",\"value\":\"bank\"}]},{\"type\":\"transfer\",\"attributes\":[{\"key\":\"recipient\",\"value\":\"inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku\"},{\"key\":\"sender\",\"value\":\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]}]}]",
"logs" {
  "events" {
    "type": "coin_received",
    "attributes" {
      "key": "receiver",
      "value": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
  "events" {
    "type": "coin_spent",
    "attributes" {
      "key": "spender",
      "value": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
  "events" {
    "type": "message",
    "attributes" {
      "key": "action",
      "value": "/cosmos.bank.v1beta1.MsgSend"
    }
    "attributes" {
      "key": "sender",
      "value": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
    }
    "attributes" {
      "key": "module",
      "value": "bank"
    }
  }
  "events" {
    "type": "transfer",
    "attributes" {
      "key": "recipient",
      "value": "inj14au322k9munkmx5wrchz9q30juf5wjgz2cfqku"
    }
    "attributes" {
      "key": "sender",
      "value": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
}
"gas_wanted": "200000",
"gas_used": "86357"


}

MsgDeposit

Request Parameters

Request Example:

    # prepare tx msg
    msg = composer.MsgDeposit(
        sender=address.to_acc_bech32(),
        subaccount_id=subaccount_id,
        amount=0.000001,
        denom='USDT'
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)

    # print tx response
    print(res)
Parameter Type Description Required
sender string The inj address of the sender Yes
subaccount_id string The subaccount_id to receive the funds Yes
amount int The amount of tokens to send Yes
denom string The denom of that token Yes

Response Example:

{

"height": "8581522",
"txhash": "E2E0A4F8DF9E6C93DACF591A542B5677B70D17E3E46418668CE39828E3694DC6",
"data": "0A280A262F696E6A6563746976652E65786368616E67652E763162657461312E4D73674465706F736974",
"raw_log": "[{\"events\":[{\"type\":\"coin_received\",\"attributes\":[{\"key\":\"receiver\",\"value\":\"inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]},{\"type\":\"coin_spent\",\"attributes\":[{\"key\":\"spender\",\"value\":\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]},{\"type\":\"injective.exchange.v1beta1.EventSubaccountDeposit\",\"attributes\":[{\"key\":\"amount\",\"value\":\"{\\\"denom\\\":\\\"inj\\\",\\\"amount\\\":\\\"1000000000000000000\\\"}\"},{\"key\":\"src_address\",\"value\":\"\\\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\\\"\"},{\"key\":\"subaccount_id\",\"value\":\"\\\"va7eyV1WP7BSQNbgGCEAhFTCTDYAAAAAAAAAAAAAAAA=\\\"\"}]},{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"/injective.exchange.v1beta1.MsgDeposit\"},{\"key\":\"sender\",\"value\":\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\"}]},{\"type\":\"transfer\",\"attributes\":[{\"key\":\"recipient\",\"value\":\"inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk\"},{\"key\":\"sender\",\"value\":\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]}]}]",
"logs" {
  "events" {
    "type": "coin_received",
    "attributes" {
      "key": "receiver",
      "value": "inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
  "events" {
    "type": "coin_spent",
    "attributes" {
      "key": "spender",
      "value": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
  "events" {
    "type": "injective.exchange.v1beta1.EventSubaccountDeposit",
    "attributes" {
      "key": "amount",
      "value": "{\"denom\":\"inj\",\"amount\":\"1000000000000000000\"}"
    }
    "attributes" {
      "key": "src_address",
      "value": "\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\""
    }
    "attributes" {
      "key": "subaccount_id",
      "value": "\"va7eyV1WP7BSQNbgGCEAhFTCTDYAAAAAAAAAAAAAAAA=\""
    }
  }
  "events" {
    "type": "message",
    "attributes" {
      "key": "action",
      "value": "/injective.exchange.v1beta1.MsgDeposit"
    }
    "attributes" {
      "key": "sender",
      "value": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
    }
  }
  "events" {
    "type": "transfer",
    "attributes" {
      "key": "recipient",
      "value": "inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk"
    }
    "attributes" {
      "key": "sender",
      "value": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
}
"gas_wanted": "200000",
"gas_used": "93162"


}

MsgWithdraw

Request Parameters

Request Example:

    # prepare tx msg
    msg = composer.MsgWithdraw(
        sender=address.to_acc_bech32(),
        subaccount_id=subaccount_id,
        amount=1,
        denom="USDT"
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
Parameter Type Description Required
sender string The inj address of the sender Yes
subaccount_id string The subaccount_id to receive the funds Yes
amount int The amount of tokens to send Yes
denom string The denom of that token Yes

Response Example:

{
"height": "8739822",
"txhash": "1E015C6B0D3CEFA5C9729415E4462B3BF2EF56F9D01E68C0653658F00B1D8A5E",
"data": "0A290A272F696E6A6563746976652E65786368616E67652E763162657461312E4D73675769746864726177",
"raw_log": "[{\"events\":[{\"type\":\"coin_received\",\"attributes\":[{\"key\":\"receiver\",\"value\":\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]},{\"type\":\"coin_spent\",\"attributes\":[{\"key\":\"spender\",\"value\":\"inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]},{\"type\":\"injective.exchange.v1beta1.EventSubaccountWithdraw\",\"attributes\":[{\"key\":\"dst_address\",\"value\":\"\\\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\\\"\"},{\"key\":\"amount\",\"value\":\"{\\\"denom\\\":\\\"inj\\\",\\\"amount\\\":\\\"1000000000000000000\\\"}\"},{\"key\":\"subaccount_id\",\"value\":\"\\\"va7eyV1WP7BSQNbgGCEAhFTCTDYAAAAAAAAAAAAAAAA=\\\"\"}]},{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"/injective.exchange.v1beta1.MsgWithdraw\"},{\"key\":\"sender\",\"value\":\"inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk\"}]},{\"type\":\"transfer\",\"attributes\":[{\"key\":\"recipient\",\"value\":\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\"},{\"key\":\"sender\",\"value\":\"inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk\"},{\"key\":\"amount\",\"value\":\"1000000000000000000inj\"}]}]}]",
"logs" {
  "events" {
    "type": "coin_received",
    "attributes" {
      "key": "receiver",
      "value": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
  "events" {
    "type": "coin_spent",
    "attributes" {
      "key": "spender",
      "value": "inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
  "events" {
    "type": "injective.exchange.v1beta1.EventSubaccountWithdraw",
    "attributes" {
      "key": "dst_address",
      "value": "\"inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r\""
    }
    "attributes" {
      "key": "amount",
      "value": "{\"denom\":\"inj\",\"amount\":\"1000000000000000000\"}"
    }
    "attributes" {
      "key": "subaccount_id",
      "value": "\"va7eyV1WP7BSQNbgGCEAhFTCTDYAAAAAAAAAAAAAAAA=\""
    }
  }
  "events" {
    "type": "message",
    "attributes" {
      "key": "action",
      "value": "/injective.exchange.v1beta1.MsgWithdraw"
    }
    "attributes" {
      "key": "sender",
      "value": "inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk"
    }
  }
  "events" {
    "type": "transfer",
    "attributes" {
      "key": "recipient",
      "value": "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r"
    }
    "attributes" {
      "key": "sender",
      "value": "inj14vnmw2wee3xtrsqfvpcqg35jg9v7j2vdpzx0kk"
    }
    "attributes" {
      "key": "amount",
      "value": "1000000000000000000inj"
    }
  }
}
"gas_wanted": "200000",
"gas_used": "91833"
}

MsgSubaccountTransfer

Request Parameters

Request Example:

    dest_subaccount_id = address.get_subaccount_id(index=1)

    # prepare tx msg
    msg = composer.MsgSubaccountTransfer(
        sender=address.to_acc_bech32(),
        source_subaccount_id=subaccount_id,
        destination_subaccount_id=dest_subaccount_id,
        amount=1000000000000000000,
        denom="inj"
    )

    # build sim tx
    tx = (
        Transaction()
        .with_messages(msg)
        .with_sequence(address.get_sequence())
        .with_account_num(address.get_number())
        .with_chain_id(network.chain_id)
    )
    sim_sign_doc = tx.get_sign_doc(pub_key)
    sim_sig = priv_key.sign(sim_sign_doc.SerializeToString())
    sim_tx_raw_bytes = tx.get_tx_data(sim_sig, pub_key)

    # simulate tx
    (simRes, success) = client.simulate_tx(sim_tx_raw_bytes)
    if not success:
        print(simRes)
        return

    # build tx
    gas_price = 500000000
    gas_limit = simRes.gas_info.gas_used + 15000 # add 15k for gas, fee computation
    fee = [composer.Coin(
        amount=str(gas_price * gas_limit),
        denom=network.fee_denom,
    )]
    tx = tx.with_gas(gas_limit).with_fee(fee).with_memo("").with_timeout_height(0)
    sign_doc = tx.get_sign_doc(pub_key)
    sig = priv_key.sign(sign_doc.SerializeToString())
    tx_raw_bytes = tx.get_tx_data(sig, pub_key)

    # broadcast tx: send_tx_async_mode, send_tx_sync_mode, send_tx_block_mode
    res = client.send_tx_block_mode(tx_raw_bytes)
    resMsg = ProtoMsgComposer.MsgResponses(res.data)
    print("tx response")
    print(res)
Parameter Type Description Required
sender string The inj address of the sender Yes
source_subaccount_id string The subaccount_id to send the funds from Yes
destination_subaccount_id string The subaccount_id to receive the funds Yes
amount int The amount of tokens to send Yes
denom string The denom of that token Yes

Response Example:

{
"height": "8739976",
"txhash": "4D1EA75A18B967F3A5E35277DFF03D724D85A1DB77168F562CC26AD4C1BE0EA3",
"data": "0A330A312F696E6A6563746976652E65786368616E67652E763162657461312E4D73675375626163636F756E745472616E73666572",
"raw_log": "[{\"events\":[{\"type\":\"injective.exchange.v1beta1.EventSubaccountBalanceTransfer\",\"attributes\":[{\"key\":\"src_subaccount_id\",\"value\":\"\\\"0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000000\\\"\"},{\"key\":\"dst_subaccount_id\",\"value\":\"\\\"0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000001\\\"\"},{\"key\":\"amount\",\"value\":\"{\\\"denom\\\":\\\"inj\\\",\\\"amount\\\":\\\"1000000000000000000\\\"}\"}]},{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"/injective.exchange.v1beta1.MsgSubaccountTransfer\"}]}]}]",
"logs" {
  "events" {
    "type": "injective.exchange.v1beta1.EventSubaccountBalanceTransfer",
    "attributes" {
      "key": "src_subaccount_id",
      "value": "\"0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000000\""
    }
    "attributes" {
      "key": "dst_subaccount_id",
      "value": "\"0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000001\""
    }
    "attributes" {
      "key": "amount",
      "value": "{\"denom\":\"inj\",\"amount\":\"1000000000000000000\"}"
    }
  }
  "events" {
    "type": "message",
    "attributes" {
      "key": "action",
      "value": "/injective.exchange.v1beta1.MsgSubaccountTransfer"
    }
  }
}
"gas_wanted": "200000",
"gas_used": "86552"

}