1.5.4 • Published 2 years ago

@orionprotocol/orion-trading-sdk v1.5.4

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Orion Trading SDK

code style: eslint Actions Status npm version

Attention! For the correct work of the SDK, you need to update the package to the latest version and follow updated instructions below.

Installation

npm install @orionprotocol/orion-trading-sdk

Methods with parameters per module

Module Chain

getWalletBalance(ticker)

ParameterTypeRequiredDescription
tickerstringnoempty ticker field return balance for all tokens

@return token balance on wallet (uint)

Module OrionAggregator

createOrder({...params})

ParameterTypeRequiredDescription
fromCurrencystringyestoken symbol
toCurrencystringyestoken symbol
sidestringyes'buy' or 'sell'
pricenumberyesany number
amountnumberyesany number
priceDeviationnumberyesit's percents, 0 < priceDeviation < 50
needWithdrawbooleannofalse by default, feature in process
chainPricesobjectno

chainPrices is optional (use it if you already knew prices):

ParameterTypeRequiredDescription
gasWeistringyesgas price in wei
baseAssetstring/numberyesaka 'fromCurrency'
networkAssetstring/numberyes
feeAssetstring/numberyes

@return prepared and signed order

sendOrder(order, isCreateInternalOrder)

ParameterTypeRequiredDescription
orderobjectyesOrder object from createOrder()
isCreateInternalOrderbooleannoExecution only in the internal order book; false by default

@return orderId

cancelOrder(orderId)

ParameterTypeRequiredDescription
orderIdstringyes

@return orderId of cancelled order

getOrderById(orderId, owner)

ParameterTypeRequiredDescription
orderIdstringyes
ownerstringnoby default owner address is a current wallet address

@return order with requested id

getTradeHistory({...options}) Parameter | Type | Required | Description --- | --- | --- | --- baseAsset | string | no | token address quoteAsset | string | no | token address startTime | number | no | endTime | number | no | limit | number | no | default 1000

@return list of orders

Module Exchange

getContractBalance(ticker)

ParameterTypeRequiredDescription
tickerstringnoempty ticker field return balance for all tokens

@return token balance on smart contract (bignumber)

deposit(token, amount)

ParameterTypeRequiredDescription
tokenstringyes
amountstringyes

@return transaction hash

withdraw(token, amount)

ParameterTypeRequiredDescription
tokenstringyes
amountstringyes

@return transaction hash

Module WS

priceFeedAll()

  • no params

@return subscriber for all tickers price feed

priceFeedTicker(ticker)

ParameterTypeRequiredDescription
tickerstringyes

@return subscriber for specific ticker price feed

orderBooks(pair)

ParameterTypeRequiredDescription
pairstringyes

@return subscriber for orderbooks

How to use

Important note! you should always wrap your async functions in a try-catch block, so you could handle errors in a right way.

try {
   // place here your async functions
   /* Example
       const chain = new Chain(privateKey, networkParams)
       await chain.init() // get blockchain info
    */

} catch(error) {
   // handle errors
}

First step: Create base Chain instance

import { Chain, Constants } from '@orionprotocol/orion-trading-sdk'

// Set params for Chain constructor

const privateKey = 'your_private_key'

// in Constants.NETWORK you should choose mode (MAIN | TEST) and then chain (BSC | ETH)
const networkParams = Constants.NETWORK.TEST.BSC

// By default networkParams is NETWORK.TEST.BSC

try {
    const chain = new Chain(privateKey, networkParams)

    await chain.init() // get blockchain info
} catch (error) {
    // handle error
}

In examples below we hide try-catch blocks, because they are wrappers. But you should always use them.

Now you ready to go.

Examples

(previous steps are required)

Get wallet balance:

const walletBalance = await chain.getWalletBalance('ORN') // by ticker

const walletBalanceSummary = await chain.getWalletBalance() // summary

/*
    Example:
    { ORN: '13890000000000' } // uint
*/

For further operations, network tokens are required to pay for transactions, as well as tokens for deposit / withdrawal / exchange.

Deposit token:

import { Exchange } from '@orionprotocol/orion-trading-sdk'

const exchange = new Exchange(chain)

const deposit = await exchange.deposit('ORN', '10')
// Should return transaction object

Get smart contract balance:

const contractBalance = await exchange.getContractBalance('ORN') // by ticker

const contractBalanceSummary = await exchange.getContractBalance() // summary

/*
    Example:
     {
        ORN: {
          total: [BigNumber],
          locked: [BigNumber],
          available: [BigNumber]
        }
      }
*/

Withdraw token:

const withdraw = await exchange.withdraw('ORN', '10')
// Should return transaction object

Work with OrionAggregator:

Creating, sending, canceling orders and getting info

import { OrionAggregator } from '@orionprotocol/orion-trading-sdk'

orionAggregator = new OrionAggregator(chain)

// There is no need to call deprecated method orionAggregator.init() now,
// module is ready to use. But this method is left for backward compatibility.

Create, sign and send order to OrionAggregator:

// create order
const order = {
    fromCurrency: 'ORN',
    toCurrency: 'DAI',
    feeCurrency: 'ORN', // available fee tokens you can find in chain.tokensFee
    side: 'sell',   // 'buy' or 'sell'
    price: 12,
    amount: 10,
    priceDeviation: 1,   // it's percents: 0 < priceDeviation < 50
    // 'chainPrices' is optional, use it when prices are already known
    // to increase request speed
    chainPrices: {
        networkAsset: 57,  // // 'networkAsset' price against ORN
        baseAsset: 1,    // 'fromCurrency' price against ORN
        feeAsset: 1,    // 'feeCurrency' price against ORN
        gasWei: '10000000000'
    }
}

// create and sign order
const signedOrder = await orionAggregator.createOrder(order)

// send order
const sentOrderResponse = await orionAggregator.sendOrder(signedOrder)
// Should return order id if successful

Cancel order:

const orderCancelation = await orionAggregator.cancelOrder(sentOrderResponse.orderId)
// Should return order id if cancelation is successful

Get orders history/status:

// getTradeHistory returns list of orders
const history = await orionAggregator.getTradeHistory()

// getOrderById returns order object
const order = await orionAggregator.getOrderById(sentOrderResponse.orderId)
// const status = order.status

Websockets

Create WS instance:

import { WS, Constants } from '@orionprotocol/orion-trading-sdk'

// Create ws instance

// in Constants.ORION_WS you should choose mode (MAIN | TEST) and then chain (BSC | ETH)
const wsUrl = Constants.ORION_WS.TEST.BSC

// wsUrl by default is ORION_WS.TEST.BSC
const ws = new WS(wsUrl)

// There is no need to call deprecated method ws.init() now,
// module is ready to use. But this method is left for backward compatibility.

To subscribe to the price feed:

// Subscribe for all tickers
const subscriberForAll = ws.priceFeedAll()

// Subscribe for specified ticker
const subscriberForTicker = ws.priceFeedTicker('ORN-USDT')

subscriberForAll.on('message', (message) => {
    // do something with message data
});

subscriberForTicker.on('message', (message) => {
    // do something with message data
});

// Unsubscribe
subscriberForAll.close()
subscriberForTicker.close()

To subscribe to the orderbooks:

// Subscribe for orderbooks
const subscriberForOrderbooks = ws.orderBooks('ORN-USDT')

subscriberForOrderbooks.on('message', (message) => {
    // do something with message data
});

// Unsubscribe
subscriberForOrderbooks.close()

Testing

To run the tests, follow these steps. You must have at least node v10 installed.

Clone repository

git clone https://github.com/orionprotocol/trading-sdk

Move into the trading-sdk working directory

cd trading-sdk/

Install dependencies

npm install

Run tests

npm run test

You should see output with all test passed

Resources