NAV Navbar
javascript python go

API version: 1.0.0
Cover

API Overview

The WhaleTrace API provides you real-time streams and methods for whales moves tracking on various blockchains. Our API serves latests as well as historic blockchain transactions.

We are using Google Protocol buffers with GRPC, but we support REST API as well.

This documentation should contain all informations and descriptions of used models/messages with basic usage (for GRPC mainly) in supported languages. Every GRPC method or request is also described with sample codes and examples. Every REST API request is described also with expected result. For extensive examples, visit our public repository.

GRPC

If you are not planing to develop your own API calls, feel free to use our fully compliant client libraries below.

Client libraries

Examples

Go examples

Python examples

Nodejs examples

Whaletrace protobuf API introduction

As mentioned above, we provide API calls via protocol buffers in two forms - stream and RPC call

# RPC call
rpc SayHello(HelloRequest) returns (HelloResponse){
}
# Streaming
rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse){
}

GRPC Prerequirements

# --------------------------------
# Instructions for Python
# --------------------------------
# Make sure you have Python 3.4 or higher

# Ensure you have `pip` version 9.0.1 or higher: 
python -m pip install --upgrade pip

# Install gRPC, gRPC tools 
python -m pip install grpcio grpcio-tools

# transpile proto file to `*.py` files with
python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. ./types.proto

# This will generate transpiled files into current directory `types_pb2.py` and 'types_pb2_grpc'
# --------------------------------
# Instructions for GoLang
# --------------------------------
GIT_TAG="v1.2.0" # change as needed
go get -d -u github.com/golang/protobuf/protoc-gen-go
git -C "$(go env GOPATH)"/src/github.com/golang/protobuf checkout $GIT_TAG
go install github.com/golang/protobuf/protoc-gen-go
# --------------------------------
# Instructions for NodeJS
# --------------------------------
# Follow https://www.npmjs.com/package/google-protobuf

Protocol Buffers (a.k.a., protobuf) are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data. You can find protobuf's documentation on the Google Developers site.

This doc contains protobuf installation instructions. To install protobuf, you need to install the protocol compiler (used to compile .proto files) and the protobuf runtime for your chosen programming language.

For more info, follow instructions on Google's protocol buffer website

gRPC Connection & Authentication

// Load the protobuffer definitions
const proto = grpc.loadPackageDefinition(
  protoLoader.loadSync("types.proto", {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
  })
);

// Initialize the TransactionServer service. You have to provide valid host address
const client = new proto.types.TransactionServer(
  SERVER,
   grpc.credentials.createInsecure())
);
# Invoke connection to the server
channel = grpc.insecure_channel(SERVER)
# Initialize the TransactionServer Stub(client) service.
stub = types_pb2_grpc.TransactionServerStub(channel)
// install protoc [https://github.com/golang/protobuf]
// and protoc-gen-go [https://github.com/golang/protobuf/tree/master/protoc-gen-go]
// transpile proto file to `*.go` file with 
// `protoc -I .. -I $GOPATH/src --go_out=plugins=grpc:./ ../types.proto`
// This will generate transpiled file into current directory. 
// To adhere golang conventions, move it to dir named ie. types.

//DEFINE ABOVE MAIN:
type tokenAuth struct {
    token string
}

func (t tokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {
    return map[string]string{
        "Authorization": "Bearer " + t.token,
    }, nil
}

func (tokenAuth) RequireTransportSecurity() bool {
    return false
}

//IN MAIN:
// Dial the server
conn, err := grpc.Dial(Server, grpc.WithInsecure(), grpc.WithPerRPCCredentials(tokenAuth{TOKEN}), grpc.WithTimeout(5*time.Second), grpc.WithBlock())

//create client
client := types.NewTransactionServerClient(conn)

Each client is granted its private API token, which has to used with every method or subscription that is executed on the server.

After the successful connection you can use subscribtions as stated in sections below. Do not forget to attach your token for every gRPC call

#add your token into the header
metadata = [('authorization', 'Bearer {}'.format(TOKEN))]

# create timeframe  for request
now = time.time()
seconds = int(now)
to_time = timestamp_pb2.Timestamp(seconds=seconds)
from_time = timestamp_pb2.Timestamp(seconds=to_time.seconds - int(3600)) # last 1 hour

# in our case we have to use kwarg because `from` is
# is recognized as python keyword so there would syntax be error
# if you want get value you have to use getattr()
historic_request_kwargs = { 'from': from_time, 'to': to_time, 
                            'type': ASSET, 'count': COUNT}
#create request
req = types_pb2.CryptoTransactionRequest(**historic_request_kwargs)

# Call request on server
trx_stream = stub.HistoricTransactions(request=req, metadata=metadata)

#Read all data that are received
for transaction in trx_stream:
    print(transaction)
#add your token into the header
var metadata = new grpc.Metadata();
metadata.add('authorization', `Bearer ${TOKEN}`);

const now = Date.now() / 1000 | 0; // unix timestamp
// Subscribe to required stream and listen to incoming data
let channel = client.TopTransactions({
    from: {seconds: now - 7200},
    to: {seconds: now},
    type: ASSET,
    count: COUNT,
}, metadata);

channel.on("data", function (message) {
    console.log(message);
});
// create time frame
    hourAgo, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Hour))
    now, _ := ptypes.TimestampProto(time.Now())

    //create crypto request
    cryptoRequest := &types.CryptoTransactionRequest{
        Type:  ASSET,
        From:  hourAgo,
        To:    now,
        Count: AMOUNT,
    }

  //call TopTransactions metohd on server
  //note that token has been already provided while dialing the server
    sub, err := client.HistoricTransactions(context.Background(), cryptoRequest)
    if err != nil {
        panic(err)
    }

    for {
        transaction, err := sub.Recv()
        if err == io.EOF {
            break
        }
        if err != nil {
            panic(err)
        }

        fmt.Println(transaction)
    }

Protocol buffers make it easy to implement your custom libraries. You can think of protobuf file as a file with definitions for our api. Each supported language has tools to use this definitions, ie. node.js can directly load *.proto file and use its api. With python, we recommend class generation from this file with the help of grpc tool. In this documentation we are providing basic examples which you can use with just a little effort.

Requests examples

Examples bellow demonstrates sample usage of our grpc API endpoint. Note, that the SERVER_ENDPOINT, often used in these examples is grpc.whaletrace.com:30000.

Requesting historic transactions

// Example: https://github.com/whaletrace/api/blob/master/nodejs/HistoricTransactions/client.js
var metadata = new grpc.Metadata();
metadata.add('authorization', `Bearer ${TOKEN}`);

const now = Date.now() / 1000 | 0; // unix timestamp
let channel = client.HistoricTransactions({
    from: {seconds: now - 7200},
    to: {seconds: now},
    type: ASSET,
    count: COUNT,
}, metadata);

channel.on("data", function (message) {
    console.log(message);
});
# Example: https://github.com/whaletrace/api/blob/master/python/HistoricTransactions/client.js
historic_request_kwargs = { 'from': from_time, 'to': to_time, 
'type': ASSET, 'count': COUNT}
req = types_pb2.CryptoTransactionRequest(**historic_request_kwargs)

trx_stream = stub.HistoricTransactions(request=req, metadata=metadata)
for transaction in trx_stream:
  print(transaction)
// Example https://github.com/whaletrace/api/blob/master/go/HistoricTransactions/client.js
hourAgo, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Hour))
now, _ := ptypes.TimestampProto(time.Now())

//create crypto request
cryptoRequest := &types.CryptoTransactionRequest{
  Type:  ASSET,
  From:  hourAgo,
  To:    now,
  Count: AMOUNT,
}

sub, err := client.HistoricTransactions(context.Background(), cryptoRequest)
if err != nil {
  panic(err)
}

for {
  transaction, err := sub.Recv()
  if err == io.EOF {
    break
  }
  if err != nil {
    panic(err)
  }

  fmt.Println(transaction)
}

Historic transaction

Returns historic transactions within given range, specified by from and to timestamps, of given asset type, in order of their adding to our database.

Top transactions

Returns up to count top transactions within given range, specified by from and to timestamps, of given asset type in order of their value in USD.

Subscribing to transaction stream

var metadata = new grpc.Metadata();

metadata.add('authorization', `Bearer ${TOKEN}`);

let channel = client.SubscribeTransactions({
    type: ASSET,
}, metadata);

channel.on("data", function (message) {
    console.log(message);
});
#add your token into the header
metadata = [('authorization', 'Bearer {}'.format(TOKEN))]

#create request
req = types_pb2.CryptoSubscribeRequest(type=ASSET)

trx_stream = stub.SubscribeTransactions(request=req, metadata=metadata)
for transaction in trx_stream:
    print(transaction)
//create crypto request
cryptoRequest := &types.CryptoSubscribeRequest{
  Type:  ASSET,
}
//subscribe to Transactions on server
sub, err := client.SubscribeTransactions(context.Background(), cryptoRequest)
if err != nil {
  panic(err)
}
//infinite stream
for {
  transaction, err := sub.Recv()
  if err == io.EOF {
    panic("connection closed!")
  }
  if err != nil {
    panic(err)
  }
  fmt.Println(transaction)
}

Transaction subscription

With gRPC, you can also subscribe to obtain the newest transactions - only a few seconds after they are confirmed on the blockchain.

Models

Transactions are data models transactions that occured on various blockchains, such as BTC, ETH or TRX, including contract execution of various tokes, such as USDT, or HT. You can request old transactions using RPC call or subscribe to incoming new transactions.

Token

Extends basic transaction data with information about token transaction

Field Type Label Description
name string Name of the token (example: HuobiToken)
chain string Blockchain, on which the token has been tracker (example:ETH for ethereum blockchain)
symbol string Symbol used for the token on the blockchain (example: HT)
action string Action that has taken place, since with contracts we can track multiple actions (transfer

Entity

Represents additional information about an entity thet receved/sent transaction

Field Type Label Description
address string Address of the entity in the form of an hash
name string Name of the entity or Wallet in case of unknown entity
type string Type of the entity (example: wallet,exchange,gambling)
url string (optional) url of the entity webpage

Transaction

Represents information about a transaction that occured

Field Type Label Description
hash string ID(in a form of hash) of the trancasction, that can be used to look up the transaction
from Entity Sender information (empty in cas of issue token action)
to Entity Receiver information (empty in cas of redeem token action)
time google.protobuf.Timestamp Time of the acceptance of the transaction into the blockchain
asset string Asset of the transaction (example:BTC,ETH,USDT)
size double Size(value) of the transaction in its native asset
USD_size double Size(value) of the transaction is USD
token Token Additional info about the transaction in case it was contract execution

Server Model

TransactionServer

Server that provides main informations about transactions

Method Name Request Type Response Type Description
TopTransactions CryptoTransactionRequest Transaction stream Obtain top transaction from given time-frame of given asset as an rpc stream
HistoricTransactions CryptoTransactionRequest Transaction stream Obtain historic transactions from given time-frame of given asset as an array
SubscribeTransactions CryptoSubscribeRequest Transaction stream subscribe to the newest transactions of given asset

CryptoSubscribeRequest

Represents data of request for crypto transactions of some type(Asset) with no additional filters

Field Type Label Description
type string Asset name (example:BTC,ETH,USDT)
sizeLimit int64 lower USD size limit of the returned transactions (min and default according membership)

CryptoTransactionRequest

Represents data of request for crypto transactions of some type(Asset) with additional filters

Field Type Label Description
type string Asset name (example:BTC,ETH,USDT)
from google.protobuf.Timestamp Start of the time-frame in which the interested transactions occured
to google.protobuf.Timestamp End of the time-frame in which the interested transactions occured
count int64 Number of transaction that should be returned (max 100, default 50 )
sizeLimit int64 lower USD size limit of the returned transactions (min and default according membership)

gRPC Error codes

gRPC uses a set of well defined status codes as part of the RPC API. In case of an error, our API returns one of these well defined gRPC error codes:

Code Number Description
CANCELLED 1 The operation was cancelled, typically by the caller.
INVALID_ARGUMENT 3 One of the provided arguments for the calls was invalid
PERMISSION_DENIED 7 You dont have enough permissions for this call. This can happen if you call rpc call that is not allowed to you.
UNAUTHENTICATED 16 The request does not have valid authentication credentials for the operation. This is mostly doue to ommited/invalid API key.
ABORTED 10 The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
INTERNAL 13 Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
UNAVAILABLE 14 The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.

Whaletrace REST API introduction

As mentioned above, we provide also REST API

REST Connection & Authentication

Each client is granted its private API token, which has to used with every call.

Rate Limits

API rate limiting depends on your plan.

Endpoints

TopTransactions


HTTP request example:

GET http://api.whaletrace.com/v1/TopTransactions?apiKey={YOUR_API_KEY}&type=BTC&from=2020-01-24T16:41:21Z&to=2020-01-25T00:41:21Z&count=2

Returns up to count top transactions within given range, specified by from and to timestamps, of given asset type in order of their value in USD.

HTTP response example
{
   "data":[
      {
         "hash":"12e471b81d5098833c0aa8ce2913b4e9947a12c39a9da309c1ebb963a643f32d",
         "from":{
            "address":"1CKobgeJYo9YqfmPguSEbRZ5TFyxNVV2UR and others",
            "name":"Wallet",
            "type":"wallet"
         },
         "to":{
            "address":"1NcJeP1XFFfurdgSJejdabZzH6bJQ6uKCk",
            "name":"Wallet",
            "type":"wallet"
         },
         "time":"2020-01-24T23:21:55Z",
         "asset":"BTC",
         "size":4825.66713426,
         "USD_size":41041719.89682519
      },
      {
         "hash":"fecb0051e9e69c7e8202fae3866a5193579696c1093049e7e336e5a15d0a9248",
         "from":{
            "address":"bc1qw0c0mrjjw73azm65utnhwvcpsdnpg0cdljg0eg",
            "name":"Wallet",
            "type":"wallet"
         },
         "to":{
            "address":"bc1quq29mutxkgxmjfdr7ayj3zd9ad0ld5mrhh89l2",
            "name":"OKEx",
            "type":"exchange",
            "url":"okex.com"
         },
         "time":"2020-01-24T19:44:03Z",
         "asset":"BTC",
         "size":2763.80593244,
         "USD_size":23417202.542436957
      }
   ],
   "count":2
}

URL Parameters

Parameter Type Description
apiKey string (required) your API key
from string (required) specify time range from which should be transactions considered for selection, in RFC 3339 format, with eventually ommited minutes and seconds
to string (required) specify time range to which should be transactions considered for selection, in RFC 3339 fromat, with eventually ommited minutes and seconds
type string (required) Asset shortcut (BTC, ETH, USDT...)
count int (optional) number of top transactions to be returned (default: 50, max: 100)
sizeLimit int (optional) USD Treshold that every returned transaction must met (default,max: specified by your plan)

HistoricTransactions


HTTP request example:

GET http://api.whaletrace.com/v1/HistoricTransactions?apiKey={YOUR_API_KEY}&type=BTC&from=2020-01-26T16:41:21Z&to=2020-01-27T16:41:21Z&count=2

Returns historic transactions within given range, specified by from and to timestamps, of given asset type, with amount that is above given sizeLimit, in order of their adding to our database.

HTTP response example
{
   "data":[
      {
         "hash":"0244bc0708353dd662f0acd660d67a7c7b3fed1f2a361552480da9f93cc8a0f4",
         "from":{
            "address":"1NDyJtNTjmwk5xPNhjgAMu4HDHigtobu1s and others",
            "name":"Binance",
            "type":"exchange",
            "url":"www.binance.com"
         },
         "to":{
            "address":"1j3e3PwjJxUh6BnxfL7TfKazHYC9B1mUH and others",
            "name":"OKEx",
            "type":"exchange",
            "url":"okex.com"
         },
         "time":"2020-01-26T17:00:14Z",
         "asset":"BTC",
         "size":199.77251136,
         "USD_size":1687456.4284816703
      },
      {
         "hash":"6de75dcf2d5dc66f6d20facde7741c8850a53cdb2cf77e0c23c79c479aa2bbce",
         "from":{
            "address":"3PBC1cpPiYSYoAzxbedYCz7fmdWf1vatiL and others",
            "name":"OKEx",
            "type":"exchange",
            "url":"okex.com"
         },
         "to":{
            "address":"bc1qze0n7lum2vp0wreu6pmg7pv2hy3kvlzywkcdxvpyuaahg8flqfpq8xlfq2",
            "name":"Wallet",
            "type":"wallet"
         },
         "time":"2020-01-26T17:00:14Z",
         "asset":"BTC",
         "size":59.74959892,
         "USD_size":504698.28962135874
      }
   ],
   "count":2,
   "cursor":"BTC$1580054400$2111"
}

URL Parameters

Parameter Type Description
apiKey string (required) your API key
from string (required) specify time range from which should be transactions considered for selection, in RFC 3339 format, with eventually ommited minutes and seconds
to string (required) specify time range to which should be transactions considered for selection, in RFC 3339 fromat, with eventually ommited minutes and seconds
type string (required) Asset shortcut (BTC, ETH, USDT...)
count int (optional) number of transactions to be returned (default: 50, max: 100)
sizeLimit int (optional) USD Treshold that every returned transaction must met (default,max: specified by your plan)
cursor string (optional) Pagination key from the previous response. Recommended when retrieving transactions in intervals.

If you would like to obtain all historic transaction without using cursor, please use provided GRPC API.

REST Error codes

Our Rest API uses a set of well defined error status codes. In case of an error, our API returns one of these REST error codes:

Number Description
200 Ok -- The request was successful.
400 Bad Request -- Your request was not valid.
401 Unauthorized -- No valid API key was provided
403 Forbidden -- Access to this resource is restricted for the given caller.
404 Not Found -- The requested resource does not exist.
405 Method Not Allowed -- An invalid method was used to access a resource.
429 Too Many Requests -- You have exceeded the allowed number of calls per minute. Lower call frequency or upgrade your plan for a higher rate limit.
500 Internal Server Error -- There was a problem with the API host server.
503 Service Unavailable -- API is temporarily offline for maintenance.