Skip to content
Builder106Public

About

Building artificial intelligence from raw math. A self-teaching trading AI written in pure C without external machine learning libraries.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

130 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

qforge: Building artificial intelligence from raw math in C

CI C99 License: MIT Tests WebAssembly Demo

Building artificial intelligence from raw math. A self-teaching trading AI written in pure C without external machine learning libraries.

The qforge project page: the name, a short description of a neural network framework in C99 with two finance applications, buttons to run it in the browser or view it on GitHub, and a row of figures for unit tests passing, MFLOP/s on one core, lines of C and dependencies.

πŸ’‘ What is QForge?

QForge is a learning engine written in C. It includes a simulated market and trains an agent to trade through trial and error.

The project builds its own neural network and trading components without TensorFlow, PyTorch, or external dependencies:

  1. Learns patterns: A neural network trained on market data that generates realistic synthetic stock returns for stress-testing portfolios.
  2. Makes trades: An AI trading agent that learns when to buy, sell, or hold, outperforming a passive buy-and-hold strategy.
  3. Runs fast: Custom matrix math optimized to process 2,400 million operations per second on a single CPU core.

Everything (the math engine, the learning algorithms, and the trading logic) is written by hand in ~2,000 lines of C.


Demo

Try it live in your browser: qforge-neural.vercel.app (every demo below runs directly as WebAssembly with zero installation).

$ make dqn: Reinforcement-learning trading agent

DQN trader demo: 300-episode training run beating buy-and-hold

$ make market_gen: Synthetic market data generator

Market generator demo: trains on GARCH-simulated returns and reproduces stylized facts

More demos: XOR learning and matrix math benchmarks

$ make examples: XOR classification (foundational test of neural networks)

XOR training demo: 2β†’4β†’1 MLP converges in under a second

$ make bench: Matrix computation throughput

Benchmark demo: matmul up to 512Γ—512 and full forward+backward+SGD timings


Quick Start

git clone https://github.com/Builder106/qforge.git
cd qforge
make test         # 56 unit tests β€” all should pass
make dqn          # Train the AI trading agent (~30 sec)
make market_gen   # Generate synthetic market data (~20 sec)

All Commands

Command What it does
make test Run 56 unit tests (engine + scenario tests)
make integration Black-box tests of the compiled example binaries
make dqn Train the AI trading agent
make market_gen Generate synthetic market data
make examples Train on the XOR problem (hello world of AI)
make bench Measure computation speed (MFLOP/s)
make lob_bench Benchmark L3 limit order book throughput and latency
make pcap_bench Benchmark PCAP binary parsing and exchange feed replay
make test_cpp Run modern C++17 unit tests for L3 limit order book
make gradcheck Verify math correctness via finite differences
make wasm Build every example as a WebAssembly module
make e2e Run the Playwright + Gherkin E2E suite
make memcheck Check for memory leaks

How It Works

The project has two layers: a core engine (the neural network library) and applications that use it.

Core Engine

The engine builds from matrix operations to a learning system. Every module includes Tensor. Above it, each module builds on the one before: Activation, then Layer, Network, and Optimizer. Loss depends on Tensor alone. The example programs include Network, Optimizer, and Loss directly.

Tensor handles matmul, transpose, Hadamard products, and broadcasting. Activation covers ReLU, sigmoid, tanh, softmax, and their derivatives; Loss covers MSE and epsilon-clamped cross-entropy. Dense layers use forward and backward passes with Xavier or He initialization. The network trains and predicts with SGD plus momentum or Adam, then powers the XOR, DQN trading, market-generation, and benchmark applications.

The six modules total ~2,000 lines and can be tested independently. The 56-test unit suite follows the same bottom-up structure.

Application 1: Synthetic Market Data Generator

Hedge funds use AI to generate fake but realistic market data for stress-testing their portfolios against scenarios that haven't happened yet. This application:

  • Trains on a GARCH(1,1) process calibrated to S&P 500 daily returns
  • The neural network learns to predict the next day's return from the previous 5 days
  • Generated data preserves the stylized facts of real financial data:
    • Fat tails β€” extreme moves happen more often than a normal distribution predicts
    • Volatility clustering β€” big moves tend to follow big moves
    • Negative skewness β€” crashes are sharper than rallies

Application 2: DQN Trading Agent

A reinforcement learning agent that learns to trade by trial and error β€” no human rules, just rewards:

  • Uses Deep Q-Learning β€” the same technique DeepMind used to beat Atari games
  • Experience Replay Buffer β€” remembers past trades and learns from a random mix of them
  • Epsilon-Greedy Exploration β€” starts by making random trades, gradually shifts to using what it's learned
  • Target Network β€” a frozen copy of the AI, updated periodically, that provides stable learning targets
  • Tested against a buy-and-hold baseline β€” the simplest possible strategy

Technical Details

The backend Risk Limit Engine provides account-scoped pre-trade quantity, notional and position limits, collateral reservations, real-time initial/maintenance margin, and a kill switch. Gateways use risk_reserve before routing and report fills, confirmed cancellations and price marks through the C99/C++17 API in include/risk_engine.h.

Architecture diagram
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        C-Neural-Engine                               β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Tensor  β”‚ Activate β”‚   Loss   β”‚  Layer   β”‚ Network  β”‚  Optimizer   β”‚
β”‚          β”‚          β”‚          β”‚          β”‚          β”‚              β”‚
β”‚ β€’ create β”‚ β€’ relu   β”‚ β€’ mse    β”‚ β€’ dense  β”‚ β€’ create β”‚ β€’ sgd        β”‚
β”‚ β€’ matmul β”‚ β€’ sigmoidβ”‚ β€’ cross- β”‚ β€’ fwd    β”‚ β€’ fwd    β”‚ β€’ momentum   β”‚
β”‚ β€’ transp β”‚ β€’ tanh   β”‚   entropyβ”‚ β€’ bwd    β”‚ β€’ bwd    β”‚ β€’ step       β”‚
β”‚ β€’ add    β”‚ β€’ softmaxβ”‚ β€’ derivs β”‚ β€’ xavier β”‚ β€’ predictβ”‚              β”‚
β”‚ β€’ hadam. β”‚ β€’ derivs β”‚          β”‚ β€’ he     β”‚          β”‚              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Performance benchmarks
  Operation         β”‚ Avg Time   β”‚ Throughput
  ──────────────────┼────────────┼──────────────────
  matmul    32Γ—32   β”‚   0.029 ms β”‚  2,256 MFLOP/s
  matmul    64Γ—64   β”‚   0.217 ms β”‚  2,417 MFLOP/s
  matmul   256Γ—256  β”‚  22.70  ms β”‚  1,478 MFLOP/s
  matmul   512Γ—512  β”‚ 158.67  ms β”‚  1,692 MFLOP/s
  ──────────────────┼────────────┼──────────────────
  train  16β†’32β†’1    β”‚   0.011 ms β”‚  (full fwd+bwd+sgd)
  train  64β†’128β†’10  β”‚   0.105 ms β”‚
  train  256β†’512β†’32 β”‚   3.015 ms β”‚
Gradient verification

Backpropagation correctness validated against central finite differences: dL/dw β‰ˆ [L(w+Ξ΅) - L(w-Ξ΅)] / 2Ξ΅

  Test 1: [2β†’3(Οƒ)β†’1(Οƒ)]           β€” all passed (max rel error: 1.17e-08)
  Test 2: [4β†’8(relu)β†’4(relu)β†’2(Οƒ)] β€” all passed (max rel error: 2.33e-07)
  Test 3: [3β†’5(none)β†’2(none)]      β€” all passed (max rel error: 3.50e-10)
  Test 4: [2β†’4(tanh)β†’1(Οƒ)]         β€” all passed (max rel error: 2.56e-10)

  βœ“ All gradient checks passed. Backpropagation is numerically correct.
Numerical stability
  • Softmax: Subtracts row-max before exp() to prevent overflow
  • Sigmoid: Branches on sign to avoid large negative exponents
  • Cross-Entropy: Clamps predictions to [Ξ΅, 1-Ξ΅] to avoid log(0)
  • Weight Init: Xavier (sigmoid/tanh) and He (ReLU), auto-selected
Memory management

All tensor operations return new heap-allocated tensors. Callers are responsible for freeing via tensor_free(). Layer and network destructors cascade through all owned tensors. Verified leak-free with AddressSanitizer.

API usage
# include "network.h"

# include "optimizer.h"

# include "loss.h"

// Create a 3-layer neural network
Network *net = network_create();
network_add_layer(net, 2, 8, ACT_RELU);      // Hidden 1
network_add_layer(net, 8, 4, ACT_RELU);      // Hidden 2
network_add_layer(net, 4, 1, ACT_SIGMOID);   // Output

// Optimizer: Stochastic Gradient Descent with momentum
Optimizer *opt = optimizer_create_sgd(0.01, 0.9, net);

// Training loop
for (int epoch = 0; epoch < 10000; epoch++) {
    Tensor *output = network_forward(net, input);
    Tensor *grad = loss_mse_deriv(output, target);
    network_backward(net, grad);
    optimizer_step(opt, net);
    // ... free tensors
}

// Cleanup
optimizer_free(opt);
network_free(net);

Project Structure

C_engine/
β”œβ”€β”€ include/                    # Core engine headers
β”‚   β”œβ”€β”€ tensor.h                  matrix math
β”‚   β”œβ”€β”€ activation.h              ReLU, Sigmoid, Tanh, Softmax
β”‚   β”œβ”€β”€ loss.h                    MSE, Cross-Entropy
β”‚   β”œβ”€β”€ layer.h                   dense layer (forward + backward)
β”‚   β”œβ”€β”€ network.h                 sequential model
β”‚   └── optimizer.h               SGD + momentum
β”œβ”€β”€ src/                        # Engine implementation
β”œβ”€β”€ tests/                      # 56 unit tests (TDD) + integration script
β”‚   └── test_harness.h            custom zero-dep test framework
β”œβ”€β”€ examples/                   # Applications
β”‚   β”œβ”€β”€ market_generator.c        synthetic market data
β”‚   β”œβ”€β”€ dqn_trader.c              reinforcement learning trader
β”‚   β”œβ”€β”€ xor.c                     classic AI proof-of-concept
β”‚   β”œβ”€β”€ benchmark.c               performance measurement
β”‚   └── gradient_check.c          mathematical correctness
└── docs/
    └── PRD.md

Requirements

  • GCC or Clang (C99)
  • macOS or Linux
  • No other dependencies

License

MIT

About

Building artificial intelligence from raw math. A self-teaching trading AI written in pure C without external machine learning libraries.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages