triangular_arbitrage_bot/src/book.c

67 lines
2.0 KiB
C

/*
* book.c - Global order book storage
*
* Maintains a flat array of order books indexed by symbol index.
* The ws_client parse_book_update directly writes to client->books[],
* bypassing this module. This file provides a legacy API for
* manual updates from string arrays.
*/
#include "book.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
static order_book_t g_books[MAX_SYMBOLS];
static uint32_t g_book_count = 0;
/* Zero out the global book array and reset count. */
void book_init(void) {
memset(g_books, 0, sizeof(g_books));
g_book_count = 0;
}
/* Return book for a symbol index, or NULL if out of range. */
order_book_t *book_get(uint16_t symbol_idx) {
if (symbol_idx >= g_book_count) return NULL;
return &g_books[symbol_idx];
}
/* Return the number of books currently stored. */
uint32_t book_count(void) {
return g_book_count;
}
/*
* Update book from string-encoded price/size arrays.
* bids/asks are flattened [price0, size0, price1, size1, ...] string arrays.
*/
order_book_t *book_update(uint16_t symbol_idx, int64_t ts_ms, int64_t sequence,
const char **bids, uint32_t bid_count,
const char **asks, uint32_t ask_count) {
if (symbol_idx >= MAX_SYMBOLS) return NULL;
order_book_t *book = &g_books[symbol_idx];
book->symbol_idx = symbol_idx;
book->ts_ms = ts_ms;
book->sequence = sequence;
book->bid_count = bid_count > MAX_BOOK_LEVELS ? MAX_BOOK_LEVELS : bid_count;
for (uint32_t i = 0; i < book->bid_count; i++) {
book->bids[i][0] = atof(bids[i * 2]);
book->bids[i][1] = atof(bids[i * 2 + 1]);
}
book->ask_count = ask_count > MAX_BOOK_LEVELS ? MAX_BOOK_LEVELS : ask_count;
for (uint32_t i = 0; i < book->ask_count; i++) {
book->asks[i][0] = atof(asks[i * 2]);
book->asks[i][1] = atof(asks[i * 2 + 1]);
}
if (symbol_idx >= g_book_count) {
g_book_count = symbol_idx + 1;
}
return book;
}