Understanding kdb+ Keyed Tables Syntax: Trade Ticker Plant Example
In kdb+, a ticker plant is a system used for real-time data collection, storage, and distribution. A keyed table is a fundamental data structure used in kdb+ for efficient data management. In this article, we will explain the syntax of kdb+ keyed tables using a trade ticker plant example.
Keyed Tables
A keyed table is a table with a column or a set of columns defined as its key. A keyed table allows for efficient data lookup and retrieval based on its key. The key columns have a unique value for each row and are sorted in ascending order. A keyed table is created using the enlist function, which ensures that the key columns are enlisted.
trade:([]
time: timespan$();
sym: symbol$();
price: float$();
size: long$()
)The above code block creates an unkeyed table named trade with four columns, time, sym, price, and size.
Keying the Table
To key a table, we need to define one or more columns as the key. In our example, we will key the table using the sym column, which represents the trade symbol.
trade: enlist[`sym]!trade
The above code block keys the trade table using the sym column. The exclamation mark (!) is used to define the sym column as the key. Now, the trade table is a keyed table and can be queried efficiently using the sym column as the key.
Adding Data to the Table
To add data to the keyed table, we can use the upsert function. The upsert function inserts new data into the table or updates existing data if the key exists. In the following example, we add a new trade row to the trade table.
newTrade: (`time xkey `timespan$(`second$10:00:00.000); `sym; `AAPL; 150.25; 150)
upsert newTrade into trade
The above code block creates a new trade row named newTrade and inserts it into the trade table. The xkey function is used to ensure that the time column is sorted in ascending order before adding the new trade.
Querying the Keyed Table
To query the keyed table, we can use the get function or use the key directly. In the following example, we retrieve all trades for the AAPL symbol.
get trade`AAPL
The above code block retrieves all trades for the AAPL symbol from the trade table.
Publishing to a kdb+ Ticker Plant
A kdb+ ticker plant is a system used for real-time data collection, storage, and distribution. To publish data to a kdb+ ticker plant, we need to use the pub function. In the following example, we publish the trade table to a kdb+ ticker plant named sym.q.
\p sym.q:5000
pub trade
The above code block publishes the trade table to the sym.q ticker plant on port 5000. The \p command is used to set the ticker plant endpoint.
kdb+ API Guide: Publishing to a kdb+ Ticker Plant
- Book: q for Mortals
- Article: kdb+ API Guide: Publishing to a kdb+ Ticker Plant
- Online Resource: kx.com