Building artificial intelligence from raw math. A self-teaching trading AI written in pure C without external machine learning libraries.
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:
- Learns patterns: A neural network trained on market data that generates realistic synthetic stock returns for stress-testing portfolios.
- Makes trades: An AI trading agent that learns when to buy, sell, or hold, outperforming a passive buy-and-hold strategy.
- 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.
Try it live in your browser: qforge-neural.vercel.app (every demo below runs directly as WebAssembly with zero installation).
More demos: XOR learning and matrix math benchmarks
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)| 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 |
The project has two layers: a core engine (the neural network library) and applications that use it.
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.
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
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
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 avoidlog(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);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
- GCC or Clang (C99)
- macOS or Linux
- No other dependencies
MIT




