Skip to content

Repository files navigation

⚡ AlphaKernel

A high-performance, low-latency algorithmic trading engine written entirely in C

ArchitectureComponentsBuildUsageTesting

LanguageDependenciesTestsLines of CodePlatform


Overview

AlphaKernel is a complete algorithmic trading system built from scratch in pure C (C99) with zero external dependencies. It implements the core infrastructure found in real-world electronic trading systems: a limit order book, price-time priority matching engine, pre-trade risk management, execution simulation, backtesting framework, and portfolio optimization.

This project demonstrates deep understanding of:

  • Systems programming — Manual memory management, custom allocators, cache-friendly data layouts
  • Market microstructure — Order books, matching algorithms, market impact modeling
  • Quantitative finance — Technical indicators, risk metrics (Sharpe, Sortino, VaR), portfolio theory
  • Software engineering — Modular architecture, comprehensive testing, clean API design

Architecture

┌──────────────────────────────────────────────────────────────┐
│ MAIN APPLICATION │
│ (CLI Menu + Full Demo Mode) │
├───────────┬───────────┬───────────┬──────────┬───────────────┤
│ BACKTEST │ STRATEGY │ RISK │PORTFOLIO │ LOGGING │
│ ENGINE │ ENGINE │ MANAGER │ MANAGER │ SYSTEM │
├───────────┴───────────┴───────────┴──────────┴───────────────┤
│ EXECUTION ENGINE (Simulator) │
│ Market Impact • Slippage • Transaction Costs │
├──────────────────────────────────────────────────────────────┤
│ ORDER MANAGEMENT SYSTEM (OMS) │
│ Market • Limit • Stop • Stop-Limit • IOC • FOK │
├──────────────────────────────────────────────────────────────┤
│ MATCHING ENGINE ◄──► LIMIT ORDER BOOK (LOB) │
│ Price-Time Priority Level-3 Full Depth │
├──────────────────────────────────────────────────────────────┤
│ MARKET DATA FEED HANDLER │
│ CSV Ingestion • Synthetic Data Generator │
├──────────────────────────────────────────────────────────────┤
│ CORE: Data Structures │ Memory Pool │ Statistics │ Timing │
│ Hash Table • Heap • BST • Segment Tree • Ring Buffer │
└──────────────────────────────────────────────────────────────┘

Data flow: Market Data → Strategy Signals → Risk Checks → Order Submission → Matching Engine → Execution → Position & P&L Update


Core Components

🔴 Limit Order Book (LOB)

The central data structure of any electronic exchange.

  • Level-3 depth — full order-level visibility (not just aggregated price levels)
  • Bid side sorted descending, ask side sorted ascending in cache-friendly arrays
  • O(log n) price level lookup via binary search insertion
  • O(1) best bid/ask access (always at index 0)
  • FIFO order queues at each price level using intrusive doubly-linked lists
  • Real-time spread, midpoint, and depth snapshot generation
OrderBook*book=order_book_create("AAPL");
order_book_add(book, buy_order);
doublespread=order_book_spread(book); // O(1)doublemid=order_book_midpoint(book); // O(1)order_book_print(book, 10); // Top 10 levels

🔴 Matching Engine

The heart of the trading system — implements Price-Time Priority (FIFO), the algorithm used by NYSE, NASDAQ, and CME.

  • Incoming BUY orders match against resting asks (lowest price first)
  • Incoming SELL orders match against resting bids (highest price first)
  • At the same price, oldest order fills first (time priority)
  • Supports partial fills with detailed execution reports
  • Order types: Market, Limit, Stop, Stop-Limit
  • Time-in-Force: GTC, DAY, IOC (Immediate or Cancel), FOK (Fill or Kill)
  • Nanosecond-precision latency tracking per submission
MatchingEngine*engine=matching_engine_create();
matching_engine_add_symbol(engine, "AAPL");
Order*order=order_create("AAPL", ORDER_LIMIT, ORDER_BUY, TIF_GTC, 175.50, 0, 100);
TradeExecutionfills[256];
intnum_fills;
matching_engine_submit(engine, order, fills, &num_fills);

🔴 Risk Management Engine

Every order passes through 8 independent pre-trade risk checks before reaching the matching engine:

CheckDescription
Order SizeReject orders exceeding max quantity
Notional ValueReject orders exceeding max dollar value
Price CollarReject prices deviating >N% from reference
Position LimitPrevent excessive concentration per symbol
Portfolio ExposureCap total portfolio notional
Max DrawdownAuto-trigger kill switch on drawdown breach
Rate LimitingThrottle orders per second
Kill SwitchEmergency halt — reject ALL new orders
RiskCheckResultresult=risk_check_order(rm, order, reference_price);
if (result!=RISK_PASS) {
printf("REJECTED: %s\n", risk_result_str(result));
}

🟡 Memory Pool Allocator

Custom fixed-size block allocator that eliminates malloc/free overhead in the order processing hot path.

  • Pre-allocated contiguous memory arena
  • O(1) allocation — pop from intrusive free-list head
  • O(1) deallocation — push onto free-list head
  • Zero fragmentation (fixed-size blocks)
  • Pool statistics: utilization, peak usage, lifetime allocation count

This is the technique used in real low-latency trading systems to avoid kernel syscalls during order processing.

🟡 Backtesting Framework

Event-driven bar-by-bar backtesting engine with comprehensive performance analytics:

CategoryMetrics
ReturnsTotal return, annualized return, CAGR
Risk-AdjustedSharpe ratio, Sortino ratio, Calmar ratio
DrawdownMax drawdown (depth + duration), average drawdown
Trade StatsWin rate, profit factor, payoff ratio, expectancy
CostsTotal commission, slippage cost, time in market

Includes ASCII equity curve visualization and detailed trade journal.

🟡 Execution Simulator

Realistic trade execution modeling based on the Almgren-Chriss square-root market impact model:

  • Market impact:Impact (bps) = coeff × √(order_size / ADV)
  • Slippage: Proportional to order size vs average daily volume
  • Transaction costs: Commission per share + spread crossing cost
  • Fill probability: Stochastic fill modeling for limit orders

🟢 Technical Indicators

IndicatorAlgorithm
SMACircular queue-optimized O(1) update
EMAWilder exponential smoothing
RSIRelative Strength Index (14-period default)
Bollinger Bands2σ bands around 20-period SMA
MACD12/26/9 EMA crossover with histogram

🟢 Trading Strategies

  • MA Crossover — Short/long moving average crossover
  • RSI Momentum — Overbought/oversold signals
  • Bollinger Bands — Mean reversion at band extremes
  • MACD Histogram — Signal line crossover
  • Combined — Weighted ensemble of all strategies

🟢 Portfolio Optimization

  • Dynamic Programming — Knapsack-style weight allocation maximizing risk-adjusted returns
  • Greedy Algorithm — Sharpe ratio-ranked allocation
  • Covariance matrix computation for portfolio risk
  • Multi-stock comparison and ranking

Data Structures & Complexity

StructureUse CaseInsertLookupDelete
Dynamic ArrayPrice time-seriesO(1)*O(1)O(n)
Circular QueueMoving average windowsO(1)O(1)O(1)
Min/Max HeapPrice trackingO(log n)O(1)O(log n)
Hash TableSymbol → Stock lookupO(1)*O(1)*O(1)*
Binary Search TreeOrdered price dataO(log n)O(log n)O(log n)
Segment TreeRange min/max queriesO(log n)O(log n)
Sorted ArrayOrder book price levelsO(n)O(log n)O(n)
Intrusive Linked ListOrder FIFO queuesO(1)O(n)O(1)
Memory Pool (Free-List)Order allocationO(1)O(1)

* amortized


Build

Prerequisites

  • GCC — MinGW-w64 on Windows, gcc on Linux/macOS
  • No external libraries — uses only the C standard library + math.h

Windows

# Option 1: Batch script
compile.bat
# Option 2: Manual
mkdir obj bin
gcc -Wall -Wextra -O2 -std=c99 -I. -Iinclude -c *.c src/**/*.c
gcc obj/*.o -o bin/trading_engine.exe

Linux / macOS

make
# or
make run # Build and run
make debug # Build with debug symbols

Run

# Windows
bin\trading_engine.exe
# Linux/macOS
./bin/trading_engine

Usage

AlphaKernel provides an interactive menu with 11 options:

 DATA & ANALYSIS
1. Generate Sample Market Data
2. Load Stock Data & Technical Indicators
3. Compare All Stocks
TRADING ENGINE
4. Order Book & Matching Engine Demo
5. Risk Management Demo
6. Memory Pool Performance Test
STRATEGIES & BACKTESTING
7. Execute Trading Strategies
8. Backtest with Full Analytics
PORTFOLIO
9. Optimize Portfolio (Dynamic Programming)
10. Optimize Portfolio (Greedy / Sharpe)
SYSTEM
11. Full System Demonstration

Option 11 runs an end-to-end demonstration of every component: data generation → indicator analysis → order book construction → matching engine execution → risk management → strategy backtesting → portfolio optimization.


Testing

61 unit tests covering all engine components:

# Windows
bin\test_runner.exe
# Linux/macOS
make test
 ── Memory Pool ── 7 tests ✓
── Order ── 9 tests ✓
── Order Book ── 8 tests ✓
── Matching Engine ── 8 tests ✓
── Risk Manager ── 6 tests ✓
── Statistics ── 4 tests ✓
── Timing ── 3 tests ✓
Results: 61 tests run, 61 passed, 0 failed

Project Structure

AlphaKernel/
├── include/ # Header files
│ ├── core/
│ │ └── memory_pool.h # O(1) pool allocator
│ ├── engine/
│ │ ├── order.h # Order types & lifecycle
│ │ ├── order_book.h # Level-3 limit order book
│ │ └── matching_engine.h # Price-time priority matcher
│ ├── risk/
│ │ └── risk_manager.h # 8 pre-trade risk checks
│ ├── execution/
│ │ └── execution_engine.h # Market impact simulator
│ ├── backtest/
│ │ └── backtest_engine.h # Full analytics framework
│ └── utils/
│ ├── logger.h # Structured logging
│ └── timing.h # Nanosecond-precision timing
├── src/ # New module implementations
│ ├── core/memory_pool.c
│ ├── engine/
│ │ ├── order.c
│ │ ├── order_book.c
│ │ └── matching_engine.c
│ ├── risk/risk_manager.c
│ ├── execution/execution_engine.c
│ ├── backtest/backtest_engine.c
│ ├── utils/
│ │ ├── logger.c
│ │ └── timing.c
│ └── main.c # Application entry point
├── tests/
│ └── test_runner.c # 61 unit tests
├── data_structures.c/h # Core data structures library
├── market_data.c/h # CSV feed handler + data generator
├── indicators.c/h # Technical indicators (SMA/EMA/RSI/BB/MACD)
├── strategies.c/h # Trading strategy engine
├── portfolio_optimizer.c/h # DP + Greedy portfolio optimization
├── Makefile # Unix build system
├── compile.bat # Windows build script
└── README.md

Technical Highlights

  • 10,500+ lines of pure C — no C++, no frameworks, no external dependencies
  • Zero-allocation order processing via memory pool in the matching engine hot path
  • Nanosecond-precision timing using QueryPerformanceCounter (Windows) / clock_gettime (POSIX)
  • Cache-friendly order book — sorted arrays over tree-based structures for better L1/L2 cache utilization
  • 8 independent risk checks with automatic kill switch on drawdown breach
  • Industry-standard matching — Price-Time Priority (FIFO), used by NYSE, NASDAQ, CME
  • Realistic execution modeling — Almgren-Chriss market impact, slippage, transaction costs
  • Comprehensive backtesting — Sharpe, Sortino, Calmar ratios, drawdown analysis, trade journal

License

MIT License — see LICENSE for details.

Author

Prem KudaleGitHub

About

A low-latency algorithmic trading engine in pure C — featuring a limit order book, price-time priority matching engine, pre-trade risk management, memory pool allocator, backtesting framework, and portfolio optimization. Zero external dependencies.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages