NAV Navbar
shell

Introduction

Tyche Exchange provides both HTTP and websocket APIs for interacting with the exchange. Both allow read access to public market data and private read access to your account. Private write access to your account is available via the private HTTP API.

The public HTTP endpoint is accessed via GET requests while the private endpoint is accessed via HMAC-SHA512 signed POST requests using API keys. Both types of HTTP endpoints return results in JSON format.

The websocket API allows push notifications about the public order books, lend books and your private account. Similarly to the HTTP API, it requires HMAC-SHA512 signed requests using API keys for requests related to your private account.

Public HTTP API Methods

The public HTTP API allows read access to public market data.

There are seven public methods, all of which take HTTP GET requests and return output in JSON format. No authentication is necessary but you must not excessively use any API endpoint.

returnTicker

Retrieves summary information for each currency pair listed on the exchange. Fields include:

curl "https://trade.tyche.exchange/api/v1/public/returnTicker"

Example output:

...
{ BTC_BCN:
   { id: 7,
     last: '0.00000024',
     lowestAsk: '0.00000025',
     highestBid: '0.00000024',
     percentChange: '0.04347826',
     baseVolume: '58.19056621',
     quoteVolume: '245399098.35236773',
     isFrozen: '0',
     high24hr: '0.00000025',
     low24hr: '0.00000022' },
  USDC_BTC:
   { id: 224,
     last: '6437.65329245',
     lowestAsk: '6436.73575054',
     highestBid: '6425.68259132',
     percentChange: '0.00744080',
     baseVolume: '1193053.18913982',
     quoteVolume: '185.43611063',
     isFrozen: '0',
     high24hr: '6499.09114231',
     low24hr: '6370.00000000' },
...
Field Description
id Id of the currency pair.
last Execution price for the most recent trade for this pair.
lowestAsk Lowest current purchase price for this asset.
highestBid Highest current sale price for this asset.
percentChange Price change percentage.
baseVolume Base units traded in the last 24 hours.
quoteVolume Quoted units traded in the last 24 hours.
isFrozen Indicates if this market is currently trading or not.
high24hr The highest execution price for this pair within the last 24 hours.
low24hr The lowest execution price for this pair within the last 24 hours.

return24Volume

curl "https://trade.tyche.exchange/api/v1/public/return24hVolume"

Example output:

{ BTC_LTC: { BTC: '38.13504038', LTC: '4662.34229096' },
  BTC_MAID: { BTC: '10.38010322', MAID: '359919.71515255' },
...
  USDC_BTC: { USDC: '481389.13175764', BTC: '74.73988488' },
  USDC_ETH: { USDC: '72302.27016210', ETH: '357.72884034' },
  totalBTC: '2340.96441558',
  totalETH: '2771.63218462',
  totalUSDC: '681255.56961992',
  totalXMR: '267.83601213' }

Returns the 24-hour volume for all markets as well as totals for primary currencies.

Primary currencies include BTC, ETH, USDT, USDC and XMR and show the total amount of those tokens that have traded within the last 24 hours.

returnOrderBook

curl "https://trade.tyche.exchange/api/v1/public/returnOrderBook?currencyPair=ETH_BTC&depth=10"

Example output for a selected market:

{ asks: 
   [ [ '0.03142500', 16.5322 ],
     [ '0.03143140', 0.14561998 ],
     [ '0.03144000', 149.2466 ],
...
     [ '0.03175915', 3.95025486 ],
     [ '0.03176634', 0.01579061 ] ],
  bids: 
   [ [ '0.03141658', 4.75222193 ],
     [ '0.03141644', 0.05252027 ],
     [ '0.03141608', 0.20943191 ],
...
     [ '0.03129457', 0.01861854 ],
     [ '0.03128648', 0.47593681 ] ],
  isFrozen: '0',
  seq: 595100792 }

Example output for all markets:

{ BTC_ETH: 
   { asks: 
      [ [ '0.03143500', 46.84591041 ],
        [ '0.03144000', 100.086388 ],
        [ '0.03144865', 6.01683252 ],
...
        [ '0.03132669', 0.01619218 ] ],
     isFrozen: '0',
     seq: 130962406 },
  BTC_LTC: 
   { asks: 
      [ [ '0.00812000', 6.82726987 ],
        [ '0.00812253', 6.6911383 ],
        [ '0.00812500', 84.1323 ],
...
        [ '1.06900000', 0.0162 ],
        [ '1.06800000', 0.0162 ],
        [ '1.06700000', 0.0162 ] ],
     isFrozen: '0',
     seq: 51055117 } }

Returns the order book for a given market, as well as a sequence number used by websockets for synchronization of book updates and an indicator specifying whether the market is frozen. You may set currencyPair to "all" to get the order books of all markets.

Request Parameter Description
currencyPair A pair like ETH_BTC or all
depth (optional) Default depth is 50. Max depth is 100.
Field Description
asks An array of price aggregated offers in the book ordered from low to high price.
bids An array of price aggregated bids in the book ordered from high to low price.
isFrozen Indicates if trading the market is currently disabled or not.
seq An always-incrementing sequence number for this market.

returnTradeHistory (public)

curl "https://trade.tyche.exchange/api/v1/public/returnTradeHistory?currencyPair=ETH_BTC"
curl "https://trade.tyche.exchange/api/v1/public/returnTradeHistory?currencyPair=ETH_BTC&start=1548480203&end=1553577808"

Example output:

[ { globalTradeID: 394604821,
    tradeID: 45205037,
    date: '2018-10-22 15:03:57',
    type: 'sell',
    rate: '0.03143485',
    amount: '0.00009034',
    total: '0.00000283' },
  { globalTradeID: 394604809,
    tradeID: 45205036,
    date: '2018-10-22 15:03:47',
    type: 'buy',
    rate: '0.03143485',
    amount: '0.00770177',
    total: '0.00024210' },
...
  { globalTradeID: 394603147,
    tradeID: 45204939,
    date: '2018-10-22 14:31:59',
    type: 'sell',
    rate: '0.03139500',
    amount: '0.00041216',
    total: '0.00001293' },
  { globalTradeID: 394603133,
    tradeID: 45204938,
    date: '2018-10-22 14:31:41',
    type: 'sell',
    rate: '0.03140030',
    amount: '2.42099000',
    total: '0.07601981' } ]

Returns the past 200 trades for a given market, or up to 5000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters. Fields include:

Field Description
globalTradeID The globally unique ID associated with this trade.
tradeID The ID unique only to this currency pair associated with this trade.
date The UTC date and time of the trade execution.
type Designates this trade as a buy or a sell from the side of the taker.
rate The price in base currency for this asset.
amount The number of units transacted in this trade.
total The total price in base units for this trade.

Trading

Base URL: https://trade.tyche.exchange/api/v1/trading

Order Placement

POST https://trade.tyche.exchange/api/v1/trading/placeOrder

Places a new order.

POST https://trade.tyche.exchange/api/v1/trading/placeOrder
{
  "instrument": "ETH-BTC",
  "side": "buy",
  "volume": 0.0001,
  "price": 0.02
}

The above request returns JSON structured like this:

{
   "status":true,
   "result":{
      "id":46,
      "side":"buy",
      "type":"limit",
      "status":"submitting",
      "timestamp":"2019-03-26 06:43:31",
      "lastUpdate":"2019-03-26 06:43:31",
      "volume":"0.0001",
      "price":"0.02",
      "remainingVolume":"57.67499800"
   },
   "msg":"Post Trade Successfully!"
}

Parameters

The parameters should be passed in the body of POST request as fields of a JSON object.

Parameter Type Description
instrument string Trade instrument for which the order should be placed, e.g. "ETH-BTC"
side string Order side, can have either of the two values:
"buy" - buying order;
"sell" - selling order
type string Optional. Order type. Accepted values:
"limit" - limit order;
The value must comply with the list of order types supported by the instrument (see the value of parameter supportedOrderTypes of the Instrument).
If the parameter is not specified, the default value "limit" is used.
More about order types in the corresponding section of documentation
volume decimal The amount of base currency to be bought or sold.
The value must be greater than or equal to the minVolume of the Instrument
price decimal Order price.
The value must be greater than or equal to the minPrice of the Instrument.

Response

Returns an object Order with the following structure:

Field Type Description
id int Unique order identifier
timestamp datetime Date and time of creation
side string Direction of trade, can have either of the two values:
"buy" - buying order;
"sell" - selling order
type string Order type, can have one of the following values:
"limit" - limit order;
status string Order status, can have one of the following values:
"submitting" - in the process of submission;
volume decimal Initial volume of the order
price decimal Initial price of the order. In case of market order, this field contains the value null
remainingVolume decimal Remaining volume of the order (volume that hasn’t been filled)
lastUpdate datetime Last time the order had undergone changes (remaining volume decreased, status changed, etc.). If this information is not available, the field contains the value null.

The data returned is in JSON format.

Comments

Order submission is not instantaneous, it’s a process that takes some time (usually less than one second). Consequently, if one sends a request to place an order which implies immediate execution, the response may still contain the status "submitting". In this situation the orderStatus method may be of use to track the status of order execution later.

Authentication

Authentication Keys and Access Rights

Some parts of the API require authentication. In order to access them, you need to obtain an authentication key. You can generate one on the API keys tab of the account management page.

Each authentication key contains a pair of credentials: public key (API key), that acts both as trader’s identifier and access token, and private key (Secret), that is used to sign API calls. It is important to keep the private key (Secret) confidential: it should not be disclosed to any third party, including the Tyche Exchange customer support. On the contrary, public key (API key) is not confidential and may be shared with Tyche Exchange support, if necessary.

It is possible to generate multiple authentication keys, each having custom access rights associated with it. The following access permissions can be granted to an authentication key:

* R1 - get information about orders, trades, balances;
* R2 - place, modify and cancel orders;
* R3 - get payment information, such as cryptocurrency deposit address, money transfer history or money transfer status, and preview cryptocurrency withdrawals;
* R4 - withdraw cryptocurrency (fiat withdrawals are conducted manually at the moment and not available via the API).

You can temporary disable an authentication key or delete it completely at any time. It is recommended that you delete old authentication keys that are no longer in use.

Authentication Process

Tyche Exchange Trade API 1.0 uses a custom HTTP scheme based on HMAC-SHA512 for authentication. A request to an authenticated endpoint should contain the following headers:

Header Description
X-TYCHE-API-KEY Your public key (API key)
X-TYCHE-API-NONCE Arbitrary integer value that increases with each request (Nonce)
X-TYCHE-API-SIGN HMAC-generated request signature (Signature)

X-TYCHE-API-NONCE Header

Nonce is a value that varies with each request. It serves the purpose of preventing replay attacks (i.e., when one of the previously sent valid requests is intercepted and fraudulently repeated by an attacker).

X-TYCHE-API-SIGN Header

Request signature is a string generated by HMAC-SHA512 algorithm, it ensures that the request was sent by you and wasn’t modified by a 3rd party on the way.

In order to sign the request, one should perform HMAC-SHA512 with the following parameters:

Parameter Value
Key Base64-decoded Secret
Message The result of concatenation Path + Nonce + Body,
where
Path is a URL-path of the request with parameters, e.g. /v1/account/balance?currency=LTC,
Body is a request body string that contains a JSON object with request parameters (in case of POST request) or omitted (in case of GET request) )

The result of HMAC-SHA512 execution is then Base64-encoded and passed in the request as a value of X-TYCHE-API-SIGN header.

Examples

The following code samples demonstrate the process of sending GET and POST requests to authenticated endpoints:

C# (POST)

string baseUrl = "https://trade.tyche.exchange/api";
string apiKey = "-- Your API key --";
string secret = "-- Your secret --";


string path = "/v1/trading/placeOrder";
string body = @"{
                    ""instrument"": ""ETH-BTC"",
                    ""side"": ""sell"",
                    ""volume"": 1,
                    ""price"": 12345.67
                }";
string nonce = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();


byte[] key = Convert.FromBase64String(secret);
byte[] message = Encoding.UTF8.GetBytes(path + nonce + body);
HMACSHA512 hmac = new HMACSHA512(key);
string signature = Convert.ToBase64String(hmac.ComputeHash(message));


WebRequest request = WebRequest.Create(baseUrl + path);
request.Method = "POST";
request.Headers.Add("X-TYCHE-API-KEY", apiKey);
request.Headers.Add("X-TYCHE-API-NONCE", nonce);
request.Headers.Add("X-TYCHE-API-SIGN", signature);

byte[] requestBody = Encoding.UTF8.GetBytes(body);
request.ContentLength = requestBody.Length;
using (Stream stream = request.GetRequestStream())
    stream.Write(requestBody, 0, requestBody.Length);


HttpWebResponse response;
try
{
    response = (HttpWebResponse) request.GetResponse();
}
catch (WebException exception)
{
    response = (HttpWebResponse) exception.Response;
}

HttpStatusCode responseStatusCode = response.StatusCode;

string responseBody;
using (Stream stream = response.GetResponseStream())
    using (StreamReader streamReader = new StreamReader(stream))
        responseBody = streamReader.ReadToEnd();

NodeJS (POST)

const crypto = require("crypto");
const request = require("request");

var baseUrl = "https://trade.tyche.exchange/api";
var apiKey = "-- Your API key --";
var secret = "-- Your secret --";

var path = "/v1/trading/placeOrder";
var body = JSON.stringify({
    instrument: "ETH-BTC",
    side: "sell",
    volume: 1,
    price: 12345.67
});
var nonce = Date.now();

var key = Buffer(secret, "base64");
var message = path + nonce + body;
var hmac = crypto.createHmac("sha512", key);
var signature = hmac.update(message).digest('base64');

request({
        url: baseUrl + path,
        method: "POST",
        headers: {
            "X-TYCHE-API-KEY": apiKey,
            "X-TYCHE-API-NONCE": nonce,
            "X-TYCHE-API-SIGN": signature
        },
        body: body
    },
    function (error, response, body) {
        console.log("error:", error);
        console.log("statusCode:", response && response.statusCode);
        console.log("body:", body);
    }
);

PHP (POST)

$baseUrl = 'https://trade.tyche.exchange/api';
$apiKey = '-- Your API key --';
$secret = '-- Your secret --';

$path = '/v1/trading/placeOrder';
$body = '{
    "instrument": "ETH-BTC",
    "side": "sell",
    "volume": 1,
    "price": 12345.67
}';
$nonce = round(microtime(true) * 1000);

$key = base64_decode($secret);
$message = $path . $nonce . $body;
$signature = base64_encode(hash_hmac('sha512', $message, $key, true));

$curl = curl_init($baseUrl . $path);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Content-Length:' . strlen($body),
    'X-TYCHE-API-KEY:' . $apiKey,
    'X-TYCHE-API-NONCE:' . $nonce,
    'X-TYCHE-API-SIGN:' . $signature
]);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$responseBody = curl_exec($curl);
$responseStatusCode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl)

Python (POST)

import datetime
import base64
import hmac
import json
from hashlib import sha512
from urllib.request import urlopen, Request
from urllib.error import HTTPError

baseUrl = "https://trade.tyche.exchange/api"
apiKey = "-- Your API key --"
secret = "-- Your secret --"

path = "/v1/trading/placeOrder"
body = json.dumps({
        "instrument": "ETH-BTC",
        "side": "sell",
        "volume": 1,
        "price": 12345.67
    }, separators=(',', ':'))
nonce = round(datetime.datetime.now().timestamp() * 1000)

key = base64.b64decode(secret)
message = str.encode(path + str(nonce) + body, "utf-8")
hmac = hmac.new(key, message, sha512)
signature = base64.b64encode(hmac.digest()).decode()

request = Request(baseUrl + path)
request.method = "POST"
request.data = str.encode(body, "utf-8")
request.add_header("Content-Length", len(body))
request.add_header("X-TYCHE-API-KEY", apiKey)
request.add_header("X-TYCHE-API-NONCE", nonce)
request.add_header("X-TYCHE-API-SIGN", signature)

try:
    response = urlopen(request)
except HTTPError as e:
    response = e

status = response.getcode()
body = bytes.decode(response.read())

print("Status code: " + str(status))
print(body)