New York kdb Training 2019
Spaces still available. Register now to learn Kdb+.

Kdb C API Query Subscribe Example

Examples of connecting, querying and subscribing using the C API for linux are available to download and are detailed below:

Download Example C Code

Example of Kdb C API Query

Useful Code KX Information

We will use the two methods shown below to connect and query kdb:
The Interfacing Kdb with C page on the code KX website details the full API specificiation.

Method Calls

Signature Notes
int c = khpu("localhost", 1234,"myusername:mypassword"); Connect to a kdb server on the localhost port 1234.
result=k(handle,"([]a:til 10;b:reverse til 10;c:10?`4)",(K)0) Send a synchronous message in string format to a server and return the result.

Querying 2.6/2.8 kdb from C in Linux

Code KX has a simple example of querying that relies on a q server to be running on port 12001.
To compile and run the example for kdb < version 3, do the following in linux:

-lpthread - links in the posix threads library that is needed
-m64 - generates code for a 64 bit environment, setting int to 32 bits and long and pointer types to 64 bits
The svn uses -r as you need the old revisions of the library/header, these can also be downloaded qc-eg.zip and here

Querying 3.0 kdb from C in Linux

The main difference with kdb version 3.0+ is that we must make sure to specify the environment variable KXVER.
Kdb must be running on the local machine port 12001.

C Connect / Query Code

The major steps involved in kx's example csv.c to connect and query a kdb server are:

  1. Connect to kdb server. khpu(host, port, "user:pass")
  2. Send query synchronously. result=k(handle,"select...",(K)0)
  3. Close handle. kclose(handle)
  4. Check the result type then loop through rows/columns. using K.

Subscribing to Kdb tickerplant

See the subscriber.c in the C example code. This demonstrates connecting to a tickerplant and subscribing to the trade table. The steps are:

  1. Connect
  2. Subscribe to all syms on the trade table
  3. loop forever, calling k() to receive incoming data.

Subscriber C Code

tbl is the latest table of trade data, this is a K object with ->t or type 98. We used ->k to access the underlying dictionary which contains the column names and data.

The dictionary tbl is an array with two items:
[0] is symbol list of column names
[1] is columns of data

Executing from Shell

When you execute the above code at the linux terminal it will output the number of rows it is receiving and the column names

Feedhandler and Further Coding

The code shown above is for demonstration purposes only and is missing error handling, failover and graceful handling of many other scenarios. Writing production ready C subscribers and feedhandlers is tricky. If you would like further help with subscribing to kdb+tick tickerplants or creating feedhandlers we are available for kdb+ consulting.