Navbar
python node.js php javascript c#
  • Introduction
  • Public API
  • Private API
  • Introduction

    Every call to the API has a standard Response body. The json format of the response body is as following:

    {
     "success": "true or false",
     "data" : {
       "The Data as described in each method."
     }
    }
    

    The Chainrift API is designed to allow users access to all the features of the exchange. We provide our users the ability to utilize our API in order to create highly customised and advanced trading strategies.

    Our API contains both Public and Private endpoints.

    To help you get started with our API, we've provided short code examples in a variety of different programming languages.

    Public API

    A short code example of our Public API:

    from datetime import datetime
    import requests
    
    def call_api(method, body = []):
      global APIUrl
      headers = {
        "Content-Type": "application/x-www-form-urlencoded"
      }
    
      res = requests.post(APIUrl + method, headers=headers, data=body, timeout=60)
      print(method, res.text, "\n")
    
    APIUrl = "https://api.chainrift.com/v1"
    
    # Example public API calls
    call_api("Public/GetPairs");
    call_api("Public/GetPairStats", { "symbol": "ETH/BTC" });
    call_api("Public/Market");
    call_api("Public/GetOrderBook", { "symbol": "ETH/BTC" });
    call_api("Public/GetTradeHistory", { "symbol": "ETH/BTC" });
    
    const request = require('request');
    const querystring = require('querystring');
    
    const APIUrl = "https://api.chainrift.com/v1";
    
    function callAPI(method, body = {}) {
        options.uri = APIUrl + method;
        options.body = querystring.stringify(body);
    
        request(options, function (error, response, body) {
            if (response.statusCode == 200) {
                console.log(method, error, body);
            } else {
                console.log(method, "failed with status code", response.statusCode, response.headers["www-authenticate"]);
            }
            console.log("");
        });
    }
    
    let options = {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        body: ""
    };
    
    // Example public API calls
    callAPI("Public/GetPairs");
    callAPI("Public/GetPairStats", { symbol: "ETH/BTC" });
    callAPI("Public/Market");
    callAPI("Public/GetOrderBook", { symbol: "ETH/BTC" });
    callAPI("Public/GetTradeHistory", { symbol: "ETH/BTC" });
    
    <?php
    $APIUrl = "https://api.chainrift.com/v1";
    $fopen = fopen($fname, "r");
    $content = fread($fopen, 9999999);
    fclose($fopen);
    
    function callAPI ($method, $body = []) {
      global $APIUrl;
      $url = $APIUrl . $method;
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
      $headers = [
        "Content-Type: application/x-www-form-urlencoded",
      ];
    
      if (count($body) > 0) {
        $body_data = http_build_query($body);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body_data);
        $content_length = strlen($body_data);
      } else {
        $content_length = 0;
      }
      $headers[] = "Content-Length: " . strval($content_length);
    
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      $response = curl_exec($ch);
      curl_close($ch);
    
      echo "Response for {$method}: {$response}\n\n";
    }
    
    // Example public API calls
    callAPI("Public/GetPairs");
    callAPI("Public/GetPairStats", [ "symbol" => "ETH/BTC" ]);
    callAPI("Public/Market");
    callAPI("Public/GetOrderBook", [ "symbol" => "ETH/BTC" ]);
    callAPI("Public/GetTradeHistory", [ "symbol" => "ETH/BTC" ]);
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    
    namespace API_CS_Example
    {
        class Program
        {
            const string APIUrl = "https://api.chainrift.com/v1";
            static void CallAPI(string method, Dictionary<string, object> body = null)
            {
                try
                {
                    var req = WebRequest.Create(APIUrl + method);
                    req.Method = "POST";
                    req.ContentType = "application/json";
                    req.Headers = new WebHeaderCollection()
                    {
                        "Content-Type: application/x-www-form-urlencoded"
                    };
    
                    var reqStream = req.GetRequestStream();
                    var response = req.GetResponse();
                    var resStream = new StreamReader(response.GetResponseStream());
                    var data = resStream.ReadToEnd();
                    Console.WriteLine(method + ": " + data + "\n");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exception while calling {method} {ex.Message}");
                }
            }
    
            static void Main(string[] args)
            {
                // Example public API calls
                CallAPI("Public/GetPairs");
                CallAPI("Public/GetPairStats", new Dictionary<string, object>(){ { "symbol", "ETH/BTC" } });
                CallAPI("Public/Market");
                CallAPI("Public/GetOrderBook", new Dictionary<string, object>() { { "symbol", "ETH/BTC" } });
                CallAPI("Public/GetTradeHistory", new Dictionary<string, object>() { { "symbol", "ETH/BTC" } });
            }
    
        }
    }
    
    
    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    </head>
    <body>
    <script>
          var APIUrl = "https://api.chainrift.com/v1";
    
          // AJAX Helpers
          function callMethod(method, reqData) {
              $.ajax({
                  // Only async to executed methods sequentially while testing
                  async: false,
                  method: "POST",
                  url: APIUrl + method,
                  data: reqData,
                  success: function (data) {
                      console.log(method, data);
                  },
                  complete: function (data) {
                      if (data.status != 200) {
                          console.log(`Request response code is ${data.status}`, data);
                      }
                  }
              });
          }
    
          // Examples calls to public methods
          callMethod("Public/GetPairs");
          callMethod("Public/GetPairStats", { symbol: "ETH/BTC" });
          callMethod("Public/Market");
          callMethod("Public/GetOrderBook", { symbol: "ETH/BTC" });
          callMethod("Public/GetTradeHistory", { symbol: "ETH/BTC" });
    
      </script>
    </body>
    </html>
    
    

    Our extensive public API is accessible to everyone and doesn't require any authentication. Please take a look at the example short code on the right to quickly get started.

    GetPairs

    Response:

    {
      "success": true,
      "data": [
        {
            "symbol": "BCH/BTC",
            "buymakerfee": 0.001,
            "sellmakerfee": 0.001,
            "buytakerfee": 0.002,
            "selltakerfee": 0.002,
            "mintradevalue": 0.00001
        },
        {
            "symbol": "BTC/USD",
            "buymakerfee": 0.001,
            "sellmakerfee": 0.001,
            "buytakerfee": 0.002,
            "selltakerfee": 0.002,
            "mintradevalue": 0.00001
        },
        {
            "symbol": "DASH/BTC",
            "buymakerfee": 0.001,
            "sellmakerfee": 0.001,
            "buytakerfee": 0.002,
            "selltakerfee": 0.002,
            "mintradevalue": 0.00001
        },
        {
            "symbol": "DCR/BTC",
            "buymakerfee": 0.001,
            "sellmakerfee": 0.001,
            "buytakerfee": 0.002,
            "selltakerfee": 0.002,
            "mintradevalue": 0.00001
        },
        ...
      ],
      "method": "Public/GetPairs"
    }
    
    

    Returns a list of active coin pairs.

    HTTP Request

    GET https://api.chainrift.com/v1/Public/GetPairs

    Returns

    Key Type Description
    symbol string The symbol for the coin pair (ex. BTC/USD).
    buymakerfee decimal The maker buying fee.
    buytakerfee decimal The taker buying fee.
    sellmakerfee decimal The maker selling fee.
    selltakerfee decimal The taker selling fee.
    mintradevalue decimal The minimum trade amount.

    GetPairStats

    Response:

    {
      "success": true,
      "data": [
        {
          "symbol": "BTC/USD",
          "lastprice": 7967.43759665,
          "high": 8615.65061449,
          "low": 7350.5912898,
          "volume": 454.90918703,
          "buytotal": 307986.66972244,
          "selltotal": 6364.26247791
        }
      ],
      "method": "Public/GetPairStats"
    }
    

    Returns information about the coin pairs.

    HTTP Request

    GET http://api.chainrift.com/v1/Public/GetPairStats?

    Parameter Required Type Description
    symbol No string This indicates coin pair (ex. BTC/USD).

    Returns

    Key Type Description
    symbol string The symbol for the coin pair (ex. BTC/USD)
    lastPrice decimal The market's last price.
    high decimal The 24 hour high market price.
    low decimal The 24 hour low market price.
    volume decimal The market's 24 hour volume.
    buytotal decimal The total of the the buy order book.
    selltotal decimal The total of the the sell order book.

    Market

    Response:

    {
      "success": true,
      "data": [
        {
          "symbol": "BTC/USD",
          "last": 7967.43759665,
          "change": 0.0636,
          "volume": 454.90918703,
          "high": 8615.65061449,
          "low": 7350.5912898,
          "bid": 7873.47249356,
          "ask": 7967.43759665,
          "timestamp": "2018-05-09T14:34:10.991",
          "openbuyorders": 2550,
          "opensellorders": 375114,
          "prevday": 7429.72650473,
          "created": "2018-03-05T12:47:08.000"
        }
      ],
      "method": "Public/Market"
    }
    

    Returns a list of ticker items for an active market or for all active markets.

    HTTP Request

    GET https://api.chainrift.com/v1/Public/Market?

    Parameter Required Type Description
    symbol No string This indicates the coin pair (ex. BTC/USD).

    Returns

    Key Type Description
    symbol string This string represents the market's symbol (ex. BTC/USD).
    last decimal The market's last price.
    change decimal The market's 24h change.
    volume decimal The market's 24 hour volume. (1st Coin in the pair)
    high decimal The 24 hour high market price.
    low decimal The 24 hour low market price.
    bid decimal The market's largest buyer price.
    ask decimal The market's lowest seller price.
    timestamp string The date the market data was updated.
    openbuyorders int The number of open buy orders
    opensellorders int The number of open sell orders.
    prevday decimal The previous day's buying price.
    created string The date the market was added.
    Errors
    You must provide a valid pair.

    GetOrderBook

    Response:

    {
      "success":true,
      "pair": "BCH/BTC",
      "data":[
        {
          "quantity":0.10585438,
          "price":0.20345334,
          "type":"Buy"
        },
        ...
      ],
      "method": "Public/GetOrderBook"
    }
    

    Returns a list of order items for a specified active coin pair. We allow a stop parameter to indicate how many entries in orderbook we shall return (for each order type buy/sell). The hardcoded limit is 250 entries - at the moment we will not return more than 250 rows for both buy/sell orders.

    HTTP Request

    GET https://api.chainrift.com/v1/Public/GetOrderBook?symbol=<symbol>

    Parameter Required Type Description
    symbol yes string The symbol for the coin pair (ex. BTC/USD).
    stop no integer The number of order book entries to return. (250 max)

    Returns

    Array of:

    Key Type Description
    quantity decimal The quantity of the order book.
    price decimal The last price.
    type string The transaction type “Buy” or “Sell”.
    Errors
    You must provide a valid symbol

    GetTradeHistory

    Response:

    {
      "success":true,
      "data":[
        {
          "date" : "2017-08-01T00:00:00.000",
          "type" : "Buy",
          "rate" : 0.003453342,
          "amount" : 5.09843672
        },
        ...
      ],
      "method":"Public/GetTradeHistory"
    }
    

    Returns the list of trades ordered by creation date.

    HTTP Request

    GET https://api.chainrift.com/v1/Public/GetTradeHistory?symbol=<symbol>&start=<start>&stop=<stop>

    Parameter Required Type Description
    symbol no string The symbol for the coin pair (ex. BTC/USD).
    start no string This indicates the row number to start from.
    stop no string This indicates the row number to stop.

    Returns

    Array of:

    Key Type Description
    date string The date the trade was created.
    type string The transaction type “Buy” or “Sell”
    rate decimal The trade price.
    amount decimal The trade amount.
    Errors
    You must provide a valid symbol

    Private API

    A short code example on our Private API:

      const crypto = require('crypto');
      const request = require('request');
      const querystring = require('querystring');
    
      let private_key = `<INSERT_YOUR_PRIVATE_KEY_HERE>`
    
      const APIUrl = "https://api.chainrift.com/v1";
      const apiKey = '<INSERT_YOUR_API_KEY_HERE>'
    
      function callAPI(method, body = {}) {
          options.uri = APIUrl + method;
          let nonce = new Date().getTime();
          let authPayload = method + nonce
          const signer = crypto.createSign('sha256');
          signer.update(authPayload);
          signer.end();
          let signature = signer.sign(private_key).toString('hex');
          options.headers["APIKey"] = apiKey;
          options.headers["APINonce"] = nonce;
          options.headers["APISignature"] = signature;
          options.headers["APIAuthPayload"] = authPayload;
    
    
          options.body = querystring.stringify(body);
    
          request(options, function (error, response, body) {
              if (response.statusCode == 200) {
                  console.log(method, error, body);
              } else {
                  console.log(method, "failed with status code", response.statusCode, response.headers["www-authenticate"]);
              }
              console.log("");
          });
      }
    
      let options = {
          headers: {
              "Content-Type": "application/x-www-form-urlencoded"
          },
          method: "POST",
          body: ""
      };
    
      # Example private API calls
      callAPI("Private/GetBalances");
      callAPI("Private/GetDepositAddresses");
      callAPI("Private/GenerateDepositAddress");
      callAPI("Private/GetWithdrawAddresses");
      callAPI("Private/AddWithdrawalAddress", { coin: "BTC", address: "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" });
      callAPI("Private/GetDeposits");
      callAPI("Private/GetWithdrawals");
      callAPI("Private/GetOpenOrders");
      callAPI("Private/GetTradeHistory");
      callAPI("Private/PlaceOrder", { price: 1, quantity: 1, type: "buy", symbol: "ETH/BTC" });
      callAPI("Private/CancelOrder", { orderId: "efaebd52-d627-4bb4-a932-55c2577be756" });
      callAPI("Private/CancelAllOrders");
      callAPI("Private/CreateWithdrawal", { coin: "BTC", quantity: 0.1, address: "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" });
    
    
      from datetime import datetime
      import requests
      import rsa
    
      def call_api(method, body = []):
        global APIUrl
        headers = {
          "Content-Type": "application/x-www-form-urlencoded"
        }
        nonce = int(datetime.now().timestamp() * 1000)
        auth_payload = method + str(nonce)
        signature = rsa.sign(auth_payload.encode(), key, "SHA-256").hex()
        headers["APIKey"] = "<INSERT_YOUR_API_KEY_HERE>"
        headers["APINonce"] = str(nonce)
        headers["APISignature"] = signature
        headers["APIAuthPayload"] = auth_payload
    
        res = requests.post(APIUrl + method, headers=headers, data=body, timeout=60)
        print(method, res.text, "\n")
    
      APIUrl = "https://api.chainrift.com/v1"
      pkcs1 = "<INSERT_YOUR_PRIVATE_KEY_HERE>"
      key = rsa.PrivateKey.load_pkcs1(pkcs1)
    
      // Example private API calls
      call_api("Private/GetBalances");
      call_api("Private/GetDepositAddresses");
      call_api("Private/GenerateDepositAddress");
      call_api("Private/GetWithdrawAddresses");
      call_api("Private/AddWithdrawalAddress", { "coin": "BTC", "address": "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" });
      call_api("Private/GetDeposits");
      call_api("Private/GetWithdrawals");
      call_api("Private/GetOpenOrders");
      call_api("Private/GetTradeHistory");
      call_api("Private/PlaceOrder", { "price": 1, "quantity": 1, "type": "buy", "symbol": "ETH/BTC" });
      call_api("Private/CancelOrder", { "orderId": "efaebd52-d627-4bb4-a932-55c2577be756" });
      call_api("Private/CancelAllOrders");
      call_api("Private/CreateWithdrawal", { "coin": "BTC", "quantity": 0.1, "address": "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" });
    
    <?php
    $APIUrl = "https://api.chainrift.com/v1";
    $fname = "9c642eae-d876-443c-af60-076b517b9509_pkcs1.pem";
    $fopen = fopen($fname, "r");
    $content = fread($fopen, 9999999);
    fclose($fopen);
    
    $cert = openssl_pkey_get_private($content);
    
    function callAPI ($method, $body = []) {
      global $APIUrl, $cert;
      $url = $APIUrl . $method;
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
      $headers = [
        "Content-Type: application/x-www-form-urlencoded",
      ];
    
      if (count($body) > 0) {
        $body_data = http_build_query($body);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body_data);
        $content_length = strlen($body_data);
      } else {
        $content_length = 0;
      }
      $headers[] = "Content-Length: " . strval($content_length);
    
      if (strpos("Private", $method) >= 0) {
        $nonce = time(true);
        $authPayload = $method . strval($nonce);
        $sign = openssl_sign($authPayload, $signature, $cert, OPENSSL_ALGO_SHA256);
        $hexsignature = bin2hex($signature);
        $headers[] = "APIKey: 9c642eae-d876-443c-af60-076b517b9509";
        $headers[] = "APINonce: {$nonce}";
        $headers[] = "APISignature: {$hexsignature}";
        $headers[] = "APIAuthPayload: {$authPayload}";
      }
    
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      $response = curl_exec($ch);
      curl_close($ch);
    
      echo "Response for {$method}: {$response}\n\n";
    }
    
    // Example private API calls
    callAPI("Private/GetBalances");
    callAPI("Private/GetDepositAddresses");
    callAPI("Private/GenerateDepositAddress");
    callAPI("Private/GetWithdrawAddresses");
    callAPI("Private/AddWithdrawalAddress", [ "coin" => "BTC", "address" => "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" ]);
    callAPI("Private/GetDeposits");
    callAPI("Private/GetWithdrawals");
    callAPI("Private/GetOpenOrders");
    callAPI("Private/GetTradeHistory");
    callAPI("Private/PlaceOrder", [ "price" => 1, "quantity" => 1, "type" => "buy", "symbol" => "ETH/BTC" ]);
    callAPI("Private/CancelOrder", [ "orderId" => "efaebd52-d627-4bb4-a932-55c2577be756" ]);
    callAPI("Private/CancelAllOrders");
    callAPI("Private/CreateWithdrawal", [ "coin" => "BTC", "quantity" => 0.1, "address" => "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" ]);
    
    using Org.BouncyCastle.Crypto;
    using Org.BouncyCastle.Crypto.Parameters;
    using Org.BouncyCastle.OpenSsl;
    using Org.BouncyCastle.Security;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Security.Cryptography;
    using System.Text;
    
    namespace API_CS_Example
    {
        class Program
        {
            const string APIUrl = "https://api.chainrift.com/v1";
            static void CallAPI(string method, Dictionary<string, object> body = null)
            {
                try
                {
                    var req = WebRequest.Create(APIUrl + method);
                    req.Method = "POST";
                    req.ContentType = "application/json";
                    req.Headers = new WebHeaderCollection()
                    {
                        "Content-Type: application/x-www-form-urlencoded"
                    };
    
                    if (method.Contains("Private"))
                    {
                        var pemstring = @"<INSERT_YOUR_PRIVATE_KEY_HERE";
                        var privateKey = GetRSAProviderFromPem(pemstring);
                        var nonce = 10;
                        var authPayload = method + nonce.ToString();
                        var hexsignature = BitConverter.ToString(privateKey.SignData(Encoding.ASCII.GetBytes(authPayload), "SHA256")).Replace("-", "");
                        req.Headers.Add($"APIKey: <INSERT_YOUR_API_KEY_HERE>");
                        req.Headers.Add($"APINonce: {nonce}");
                        req.Headers.Add($"APISignature: {hexsignature}");
                        req.Headers.Add($"APIAuthPayload: {authPayload}");
                    }
    
                    var reqStream = req.GetRequestStream();
                    var response = req.GetResponse();
                    var resStream = new StreamReader(response.GetResponseStream());
                    var data = resStream.ReadToEnd();
                    Console.WriteLine(method + ": " + data + "\n");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exception while calling {method} {ex.Message}");
                }
            }
    
            static void Main(string[] args)
            {
                // Example public API calls
                CallAPI("Private/GetBalances");
                CallAPI("Private/GetDepositAddresses");
                CallAPI("Private/GenerateDepositAddress");
                CallAPI("Private/GetWithdrawAddresses");
                CallAPI("Private/AddWithdrawalAddress", new Dictionary<string, object>() { { "coin", "BTC" }, { "address", "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" } });
                CallAPI("Private/GetDeposits");
                CallAPI("Private/GetWithdrawals");
                CallAPI("Private/GetOpenOrders");
                CallAPI("Private/GetTradeHistory");
                CallAPI("Private/PlaceOrder", new Dictionary<string, object>() { { "price", 1 }, { "quantity", 1 }, { "type", "buy" }, { "symbol", "ETH/BTC" } });
                CallAPI("Private/CancelOrder", new Dictionary<string, object>() { { "orderId", "efaebd52-d627-4bb4-a932-55c2577be756" } });
                CallAPI("Private/CancelAllOrders");
                CallAPI("Private/CreateWithdrawal", new Dictionary<string, object>() { { "coin", "BTC" }, { "quantity", 0.1 }, { "address", "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" } });
            }
    
            public static RSACryptoServiceProvider GetRSAProviderFromPem(String pemstr, string type = "Private")
            {
                CspParameters cspParameters = new CspParameters();
                RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParameters);
    
                Func<RSACryptoServiceProvider, RsaKeyParameters, RSACryptoServiceProvider> MakePublicRCSP = (RSACryptoServiceProvider rcsp, RsaKeyParameters rkp) =>
                {
                    RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rkp);
                    rcsp.ImportParameters(rsaParameters);
                    return rsaKey;
                };
    
                Func<RSACryptoServiceProvider, RsaPrivateCrtKeyParameters, RSACryptoServiceProvider> MakePrivateRCSP = (RSACryptoServiceProvider rcsp, RsaPrivateCrtKeyParameters rkp) =>
                {
                    RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rkp);
                    rcsp.ImportParameters(rsaParameters);
                    return rsaKey;
                };
    
                PemReader reader = new PemReader(new StringReader(pemstr));
                object kp = reader.ReadObject();
    
                // If object has Private/Public property, we have a Private PEM
                if (type == "Private")
                    return (kp.GetType().GetProperty(type) != null) ? MakePrivateRCSP(rsaKey, (RsaPrivateCrtKeyParameters)(((AsymmetricCipherKeyPair)kp).Private)) : MakePublicRCSP(rsaKey, (RsaKeyParameters)kp);
                return MakePublicRCSP(rsaKey, (RsaKeyParameters)((AsymmetricCipherKeyPair)kp).Public);
            }
        }
    }
    
    
    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    </head>
    <body>
    <textarea id="txtClear" cols="80" rows="3">Private/GetBalances</textarea>
    <br/>
    <textarea id="apiKey" cols="80" rows="3">INSERT_API_KEY_HERE</textarea>
    <br/>
    <textarea id="prikey" cols="80" rows="10">INSERT_PRIVATE_KEY_HERE
    </textarea>
    <br/>
    <script>
        var crypto = window.crypto || window.msCrypto;
        var nonce;
        var APIUrl = "https://api.chainrift.com/v1";
        var signAlgorithm = {
            name: "RSASSA-PKCS1-v1_5",
            hash: {
                name: "SHA-256"
            },
        };
    
        // Helper methods
        function arrayBufferToBase64String(arrayBuffer) {
            var byteArray = new Uint8Array(arrayBuffer)
            var byteString = '';
            for (var i=0; i<byteArray.byteLength; i++) {
                byteString += String.fromCharCode(byteArray[i]);
            }
            return btoa(byteString);
        }
    
        function base64StringToArrayBuffer(b64str) {
            var byteStr = atob(b64str);
            var bytes = new Uint8Array(byteStr.length);
            for (var i = 0; i < byteStr.length; i++) {
                bytes[i] = byteStr.charCodeAt(i);
            }
            return bytes.buffer;
        }
    
        function textToArrayBuffer(str) {
            var buf = unescape(encodeURIComponent(str));
            var bufView = new Uint8Array(buf.length);
            for (var i=0; i < buf.length; i++) {
                bufView[i] = buf.charCodeAt(i);
            }
            return bufView;
        }
    
        function convertPemToBinary(pem) {
            var lines = pem.split('\n');
            var encoded = '';
            for(var i = 0;i < lines.length;i++){
                if (lines[i].trim().length > 0 &&
                    lines[i].indexOf('-BEGIN PRIVATE KEY-') < 0 &&
                    lines[i].indexOf('-END PRIVATE KEY-') < 0) {
                    encoded += lines[i].trim();
                }
            }
            return base64StringToArrayBuffer(encoded);
        }
    
        function importPrivateKey(pemKey) {
            return new Promise(function(resolve) {
            var importer = crypto.subtle.importKey("pkcs8", convertPemToBinary(pemKey), signAlgorithm, false, ["sign"]);
                importer.then(function(key) { 
                    resolve(key);
                })
                .catch (function (ex) {
                    console.log("An error occurred while importing private key:", ex);
                });
            });
        }
    
        function setHeaders(jqXHR, nonce, ajaxSignature, ajaxPayload) {
            jqXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            jqXHR.setRequestHeader("APINonce", nonce);
            jqXHR.setRequestHeader("APIKey", $("#apiKey").val());
            jqXHR.setRequestHeader("APISignature", ajaxSignature);
            jqXHR.setRequestHeader("APIAuthPayload", ajaxPayload);
        }
    
        // AJAX Helpers
        function callAPI(method, reqData, nonce, signature, payload) {
            $.ajax({
                // Only async to executed methods sequentially while testing
                async: false,
                method: "POST",
                url: APIUrl + method,
                data: reqData,
                beforeSend: function (jqXHR, settings) {
                    if (method.indexOf("Private") >= 0) {
                        setHeaders(jqXHR, nonce, signature, payload);
                    }
                },
                success: function (data) {
                    console.log(method, data);
                },
                complete: function (data) {
                    if (data.status != 200) {
                        console.log(`Request response code is ${data.status}`, data);
                    }
                }
            });
        }
    
        function callMethod(method, reqData = {}) {
            if (method.indexOf("Private") >= 0) {
                let nonce = new Date().getTime();
                let ajaxPayload = method + nonce;
                crypto.subtle.sign(signAlgorithm, pkey, textToArrayBuffer(ajaxPayload)).then(function (cipheredData) {
                    ajaxSignature = Array.from(new Uint8Array(cipheredData), function (byte) { return ('0' + (byte & 0xFF).toString(16)).slice(-2); }).join("");
                    callAPI(method, reqData, nonce, ajaxSignature, ajaxPayload);
                });
            } else {
                callAPI(method, reqData);
            }
        }
    
        // Examples calls to private methods
        var pkey;
        if (crypto.subtle) {
            importPrivateKey($('#prikey').val()).then(function (key) {
                pkey = key;
                callMethod("Private/GetBalances");
                callMethod("Private/GetDepositAddresses");
                callMethod("Private/GenerateDepositAddress");
                callMethod("Private/GetWithdrawAddresses");
                callMethod("Private/AddWithdrawalAddress", { coin: "BTC", address: "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" });
                callMethod("Private/GetDeposits");
                callMethod("Private/GetWithdrawals");
                callMethod("Private/GetOpenOrders");
                callMethod("Private/GetTradeHistory");
                callMethod("Private/PlaceOrder", { price: 1, quantity: 1, type: "buy", symbol: "ETH/BTC" });
                callMethod("Private/CancelOrder", { orderId: "efaebd52-d627-4bb4-a932-55c2577be756" });
                callMethod("Private/CancelAllOrders");
                callMethod("Private/CreateWithdrawal", { coin: "BTC", quantity: 0.1, address: "mhyMHUfApEUugEWGV8Bk7JGKaFwiZaP1tT" });
          });
        }
    </script>
    </html>
    
    

    We've made security our number one priority and require authentication on all of our private API methods. In order to use our private API, you will need to provide the following:

    1. The APIKey (generated from our website).
      • To generate an API Key please login to your account.
      • On the user menu, select "API Keys" and press "Generate API key".
      • Once an API key is generated, you will recieve a guid (API Key) and two private keys:
        • Pkcs1
        • Pkcs8
      • These private keys will be used to sign the APIAuthPayload below. The usage of these private keys depends on which library you decide to use. Please see the shortcode example on the right.
    2. Each time a unique APINonce string.
    3. An APIAuthPayload string composed of the url route (without host) + nonce.
    4. An APISignature, the signed APIAuthPayload in hex format used to verify the request authenticity. It is important to note that this string needs to be SHA-256 signed using the private key (generated during the API creation) and hex encoded. Please see the shortcode example on the right.

    You need to call each method using https://

    On the API keys screen you can also set specific IP addresses where the API will be accessible from. You can also assign specific rights for API calls to deposits, withdrawals and trading.

    GetBalances

    Response:

    {
       "success":true,
       "data":[
          {
             "coin":"ETH",
             "quantity":199.9990
          },
       ],
       "method":"Private/GetBalances"
    }
    

    Returns coin names and balances for the current user.

    HTTP Request

    POST https://api.chainrift.com/v1/Private/GetBalances

    Returns

    Key Type Description
    coin string The coin name.
    quantity decimal The user's balance for the coin specified.

    GetDepositAddresses

    Response:

    {
        "success": true,
        "data": [
            {
                "coin": "BCH",
                "addresses": [
                    {
                        "address": "mvgnWjX78aAuT65YPAzJJnvw7vTFkRh9jF",
                        "id": ""
                    }
                ]
            },
            {
                "coin": "XRP",
                "addresses": [
                    {
                        "address": "rMvT6j5m5Q9jpzx9AWPHAapQmpmxiSKBy8",
                        "id": "123"
                    },
                    {
                        "address": "rpkd8PLVYBdr45XWNnphZtneppKtNoZP5R",
                        "id": "3478338959"
                    },
                    {
                        "address": "rMYRD3d6K6PHj1Lgj4xfjASN7ZkzGoBpUr",
                        "id": "3478338959"
                    }
                ]
            }
        ],
        "method":"Private/GetDepositAddresses"
    }
    

    Returns a list of deposit addresses for each coin for the current user.

    HTTP Request

    POST https://api.chainrift.com/v1/Private/GetDepositAddresses

    Returns

    Key Type Description
    coin string The coin name.
    addresses string array This string array contains the coin's addresses and identifiers (if available). If this is a Monero(XMR) based address, then this represents the address' payment ID (if available). If this is a Ripple(XRP) based address, then this represents the address' destination tag (if available).

    GenerateDepositAddress

    Response:

    {
       "success":true,
       "data":"n4VQ5YdHf7hLQ2gWQYYrcxoE5B7nWuDFNF",
       "method":"Private/GenerateDepositAddress"
    }
    

    Generates a deposit address, up to a maximum of 10 visible, for the current user. You can generate up to 3 addresses per day.

    HTTP Request

    POST https://api.chainrift.com/v1/Private/GenerateDepositAddress

    Parameter Required Type Description
    coin yes string Coin Name

    Returns

    Key Type Description
    data string The deposit address created.
    Errors
    You have already assigned the maximum number of addresses for the selected coin type.
    The coin type you provided is not supported.
    You need to provide a coin type for address generation.
    You have reached the maximum daily limit of 1 deposit addresses for coin.
    You can not generate a new deposit address until you use the last generated deposit address.
    The coin you provided is not supported.
    Sorry, we can not generate an address at the moment.

    GetWithdrawAddresses

    Response:

    {
        "success": true,
        "data": [
            {
                "coin": "BCH",
                "addresses": [
                    {
                        "address": "mvgnWjX78aAuT65YPAzJJnvw7vTFkRh9jF",
                        "id": ""
                    }
                ]
            },
            {
                "coin": "XRP",
                "addresses": [
                    {
                        "address": "rMvT6j5m5Q9jpzx9AWPHAapQmpmxiSKBy8",
                        "id": "123"
                    },
                    {
                        "address": "rpkd8PLVYBdr45XWNnphZtneppKtNoZP5R",
                        "id": "3478338959"
                    },
                    {
                        "address": "rMYRD3d6K6PHj1Lgj4xfjASN7ZkzGoBpUr",
                        "id": "3478338959"
                    }
                ]
            }
        ],
        "method":"Private/GetWithdrawAddresses"
    }
    

    Returns active coins and withdrawal addresses for each coin for the current user.

    HTTP Request

    POST https://api.chainrift.com/v1/Private/GetWithdrawAddresses

    Returns

    Array of:

    Key Type Description
    coin string The coin name.
    addresses string array This string array contains the coin's addresses and identifiers (if available). If this is a Monero(XMR) based address, then this represents the address' payment ID (if available). If this is a Ripple(XRP) based address, then this represents the address' destination tag (if available).

    AddWithdrawalAddress

    Response:

    {
      "success":true,
      "data":"n4VQ5YdHf7hLQ2gWQYYrcxoE5B7nWuDFNF",
      "method":"Private/AddWithdrawalAddress"
    }
    

    Adds a valid withdrawal address for the current user.

    HTTP Request

    POST https://api.chainrift.com/v1/Private/AddWithdrawalAddress

    Parameter Required Type Description
    coin yes string The coin name.
    address yes string The withdrawal address to be added.
    id no string This an optional parameter available for Monero(XMR) and Ripple(XRP) based coins. If this is a Monero(XMR) based address, then this represents the payment identifier. If this is a Ripple(XRP) based address, then this represents the destination tag.
    Errors
    The address already exists and is assigned.
    The address is not valid.
    You need to provide coin type and address.
    The coin you provided is not supported.

    GetDeposits

    Response:

    {
       "success":true,
       "data":[
          {
             "coin":"BTC",
             "address":"muAY1orcwyx2xu28HZChqQSguqsR58HDQh",
             "id":"",
             "quantity":1.1000,
             "confirmations":6,
             "txid":"7fbf0168f5f961a471b9e8854851ee4a7542333db0b90df4909149d7d5ea8615",
             "timestamp":"2017-10-06T18:24:49.807075",
             "status":"Complete"
          }
       ],
       "method":"Private/GetDeposits"
    }
    

    Returns deposits from a start date to an end with a default pagination of 10 records for the current user.

    HTTP Request

    GET https://api.chainrift.com/v1/Private/GetDeposits

    Parameter Required Type Description
    start no string This indicates start date with the following format: "YYYY-MM-DD HH:mm:ss".
    end no string This indicates end date with the following format: "YYYY-MM-DD HH:mm:ss".
    coin no string The coin name.
    pageindex no integer This indicates the page number.
    pagesize no integer This indicates the number of records to display.

    Returns

    Array of:

    Key Type Description
    coin string The coin name.
    address string The deposit address.
    quantity decimal The deposit quantity.
    confirmations int The number of confirmations required.
    txid string This is the transaction identifier. A hyphenated value, represents a deposit from another account on our exchange.
    timestamp string The date the deposit was created.
    status string The transaction status of the deposit.
    Errors
    You need to provide start and end parameters as "YYYY-MM-DD HH:mm:ss" timestamp.
    The coin you provided is not supported.

    GetWithdrawals

    Response:

    {
       "success":true,
       "data":[
          {
             "coin":"BTC",
             "address":"muAY1orcwyx2xu28HZChqQSguqsR58HDQh",
             "id":"",
             "quantity":1.1000,
             "confirmations":6,
             "txid":"7fbf0168f5f961a471b9e8854851ee4a7542333db0b90df4909149d7d5ea8615",
             "timestamp":"2017-10-06T18:24:49.807075",
             "status":"Complete"
          }
       ],
       "method":"Private/GetWithdrawals"
    }
    
    

    Returns Withdrawals from a start date to an end with a default pagination of 10 records for the current user.

    HTTP Request

    GET https://api.chainrift.com/v1/Private/GetWithdrawals

    Parameter Required Type Description
    start yes string Start date with the following format: "YYYY-MM-DD HH:mm:ss".
    end yes string End date with the following format: "YYYY-MM-DD HH:mm:ss".
    coin no string Coin Name
    pageindex yes integer Page number
    pagesize yes integer Number of records to display

    Returns

    Array of:

    Key Type Description
    coin string The coin name.
    address string The withdrawal Address.
    id string id
    quantity decimal The withdrawal quantity.
    confirmations int The number of confirmations required.
    txid string This is the transaction ID. A hyphenated value, represents a withdrawal from another account on our exchange.
    timestamp string The date the widthrawal was created.
    status string The transaction Status of the withdrawal.
    Errors
    You need to provide start and end parameters as "YYYY-MM-DD HH:mm:ss" timestamp.
    The coin you provided is not supported.

    GetOpenOrders

    Response:

    {
       "success":true,
       "data":[
          {
             "orderid":"fe6ecaae-3c7c-4258-83ce-7519d091780c",
             "quantity":5.0,
             "price":0.00002400,
             "type":"Buy",
             "symbol":"ETH/BTC",
             "leaveqty":"4.3"
          }
       ],
       "method":"Private/GetOpenOrders"
    }
    

    Returns open orders for the current user.

    GET https://api.chainrift.com/v1/Private/GetOpenOrders

    Parameter Required Type Description
    symbol no string The symbol for the coin pair (ex. BTC/USD)
    orderids no array The order IDs of the specific open orders you wish to fetch.

    Returns

    Array of:

    Key Type Description
    orderid string The order identifier.
    quantity decimal The order quantity.
    price decimal The order price.
    type string The transaction type “Buy” or “Sell”.
    symbol string The symbol for the coin pair (ex. BTC/USD).
    leaveqty decimal The un-filled order quantity.

    GetOrders

    Response:

    {
       "success":true,
       "data":[
          {
             "orderid":"fe6ecaae-3c7c-4258-83ce-7519d091780c",
             "quantity":5.0,
             "price":0.00002400,
             "type":"Buy",
             "symbol":"ETH/BTC",
             "leaveqty": 0  
          }
          {
             "orderid":"fe9fraae-3c7c-4658-97ce-7529d091780c",
             "quantity":10.34567324,
             "price":0.01400,
             "type":"Buy",
             "symbol":"LTC/BTC",
             "leaveqty": 5.34567324  
          }
       ],
       "method":"Private/GetOrders"
    }
    

    Returns open orders and completed orders for the current user.

    GET https://api.chainrift.com/v1/Private/GetOrders

    Parameter Required Type Description
    symbol no string The symbol for the coin pair (ex. BTC/USD)
    orderids no array The order IDs of the specific open orders you wish to fetch.

    Returns

    Array of:

    Key Type Description
    orderid string The order identifier.
    quantity decimal The order quantity.
    price decimal The order price.
    type string The transaction type “Buy” or “Sell”.
    symbol string The symbol for the coin pair (ex. BTC/USD).
    leaveqty decimal The un-filled order quantity.

    GetTradeHistory

    Response:

    {
       "success":true,
       "data":[
          {
             "date":"2017-09-22T05:04:49.703423",
             "type":"Buy",
             "rate":1.0,
             "amount":1.0,
             "symbol":"ETH/BTC",
             "orderid":"af4a8ba1-9600-4a70-a92b-9cfcbdd44074"
          }
       ],
       "method":"Private/GetTradeHistory"
    }
    

    Returns a user's trade history.

    GET https://api.chainrift.com/v1/Private/GetTradeHistory

    Parameter Required Type Description
    start no string Start date with the following format: "YYYY-MM-DD HH:mm:ss"
    end no string End date with the following format: "YYYY-MM-DD HH:mm:ss"
    coin no string Coin Name
    pageindex no integer Page number
    pagesize no integer Number of records to display

    Returns

    Array of:

    Key Type Description
    date string The date the trade was created.
    type string The transaction type “Buy” or “Sell”.
    rate decimal The trade price.
    amount decimal The trade amount.
    symbol string The market symbol.
    orderid string The trade's order identifier.
    Errors
    The coin you provided is not supported.

    PlaceOrder

    Response:

    {
      "success":true,
      "data":"57a580b7-5292-4996-a4b6-ad8d68e90f40",
      "method":"Private/PlaceOrder"
    }
    
    

    Places an order for the current user.

    POST https://api.chainrift.com/v1/Private/PlaceOrder

    Parameter Required Type Description
    price yes decimal The price for the order being placed.
    quantity yes decimal This indicates the order quantity.
    type yes string The transaction type “Buy” or “Sell”.
    symbol yes string The market symbol (ex. BTC/USD) in which to place the order.

    Returns

    A String of new the new order's ID.

    PlaceOrders

    Response:

    {
      "orderids" : [
        {
          "tempid":1,
          "id": "df6d8ba1-9600-4a70-a92b-9cfcbdd44074"
        },
        {
          "tempid":2,
          "id": "af4a8ba1-9600-4a70-a92b-9cfcbdd44074"
        }
      ], 
      "errors" : [
        { 
          "tempid":3,
          "error":"You do not have enough balance to complete this operation"
        }
      ]
    }
    

    Places multiple orders for the current user.

    POST https://api.chainrift.com/v1/Private/PlaceOrders

    This method accepts a JSON array named orders with the following object:

    Parameter Required Type Description
    tempid yes string An order identifier set by the user. This could be any string.
    price yes decimal The price for the order being placed.
    quantity yes decimal This indicates the order quantity.
    type yes string The transaction type “Buy” or “Sell”.
    symbol yes string The market symbol (ex. BTC/USD) in which to place the order.

    Returns

    An object with an array of order with the tempid, and id; and any errors associated with the orders placed.

    CancelOrder

    Response:

    {
      "success":true,
      "data":"57a580b7-5292-4996-a4b6-ad8d68e90f40",
      "method":"Private/CancelOrder"
    }
    
    

    Cancels an order for the current user.

    POST https://api.chainrift.com/v1/Private/CancelOrder

    Parameter Required Type Description
    orderid Yes String The order identifier.

    Returns

    Order ID cancelled.

    Errors
    No orders with matching ID found on your account.
    You must provide order Id.

    CancelAllOrders

    Response:

    {
      "success":true,
      "data":"23 Orders removed",
      "method":"Private/CancelAllOrders"
    }
    
    

    If sent without parameters it will cancel ALL users orders for ALL coin pairs. An optional "symbol" parameter (e.g. XMR/BTC, ETH/BTC) can be passed to cancel all orders for the selected coin pair.

    POST https://api.chainrift.com/v1/Private/CancelAllOrders

    Parameter Required Type Description
    symbol No String The symbol for the coin pair (ex. BTC/USD) you wish to cancel orders for.
    orderids No Array The order IDs of the specific orders you wish to cancel.

    Returns

    Number of Orders cancelled.

    Errors
    No orders with matching Id found on your account.
    You must provide order Id.

    CreateWithdrawal

    Response:

    {
      "success":true,
      "data": "57a580b7-5292-4996-a4b6-ad8d68e90f40",
      "method":"Private/CreateWithdrawal"
    }
    

    Creates a withdrawal from a withdrawal address for the current user.

    POST https://api.chainrift.com/v1/Private/CreateWithdrawal

    Parameter Required Type Description
    coin yes string The coin name.
    quantity yes decimal The quantity to withdraw.
    address yes decimal The withdrawal address unless the coin is EUR,USD etc
    id no string This an optional parameter available for Monero(XMR) and Ripple(XRP) based coins. If this is a Monero(XMR) based address, then this represents the payment ID. If this is a Ripple(XRP) based address, then this represents the destination tag.

    Returns

    Ledger ID

    Errors
    Please Provide Coin for Withdrawal.
    Please Provide Withdrawal Quantity.
    Please Provide Withdrawal Address.
    The coin you provided is not supported.
    Please verify your previous transaction before requesting a new withdrawal.
    There is already a withdrawal pending email confirmation
    The entered amount is below the minimum withdrawal amount.
    have insufficient balance to proceed with this withdrawal.
    The Withdrawal Address does not exist.