#include <pthread.h>
void pin_thread_to_core(int core_id) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
}
echo 1 > /sys/devices/system/cpu/intel_pstate/no_turbo
#include <numa.h>
numa_set_preferred(0);
#include <immintrin.h>
inline double fast_ewma(double price, double predicted, double alpha) {
__m128d v_price = _mm_set_sd(price);
__m128d v_pred = _mm_set_sd(predicted);
__m128d v_alpha = _mm_set_sd(alpha);
__m128d v_one_minus_alpha = _mm_set_sd(1.0 - alpha);
__m128d part1 = _mm_mul_sd(v_price, v_alpha);
__m128d part2 = _mm_mul_sd(v_pred, v_one_minus_alpha);
__m128d sum = _mm_add_sd(part1, part2);
return _mm_cvtsd_f64(sum);
}
struct Kalman {
double x = 0.0; // preço estimado
double v = 0.0; // velocidade
double P = 1.0; // incerteza
const double R = 0.01; // ruído do mercado
const double Q = 0.0001; // ruído do modelo
inline double update(double price) noexcept {
// Predição
double x_pred = x + v;
double P_pred = P + Q;
// Correção
double K = P_pred / (P_pred + R);
x = x_pred + K * (price - x_pred);
v = v + K * (price - x_pred) * 0.01;
P = (1 - K) * P_pred;
return x;
}
};
struct HoltWinters {
double L = 0.0;
double T = 0.0;
double alpha = 0.8;
double beta = 0.2;
inline double update(double price) noexcept {
double L_prev = L;
L = alpha * price + (1 - alpha) * (L + T);
T = beta * (L - L_prev) + (1 - beta) * T;
return L + T;
}
};
inline double ar1(double price, double phi = 0.9) {
return phi * price;
}
from numba import njit
@njit(fastmath=True)
def ewma(price, predicted, alpha):
return alpha * price + (1 - alpha) * predicted
import dpdk
port = dpdk.Port(0)
port.start()
def send_order(symbol, side, destination):
pkt = dpdk.Packet()
pkt.write(f"{symbol}|{side}|{destination}")
port.send(pkt)
from pyverbs.device import Context
from pyverbs.qp import QP
ctx = Context(name='mlx5_0')
qp = QP(ctx)
import hashlib
from numba import njit
@njit(fastmath=True)
def ewma(price, predicted, alpha):
return alpha * price + (1 - alpha) * predicted
def jitter_ns(ts1, ts2):
return abs(ts2 - ts1)
def sha256_hex(value):
return hashlib.sha256(str(value).encode()).hexdigest()
def key_from_hash(h):
return int(h[:8], 16) % 3 # 0,1,2 → EWMA, Kalman, Holt-Winters
def predictive_router(tick_prev, tick_now, predicted):
j = jitter_ns(tick_prev.timestamp, tick_now.timestamp)
h = sha256_hex(j)
k = key_from_hash(h)
if k == 0:
predicted = ewma(tick_now.price, predicted, 0.8)
elif k == 1:
predicted = kalman.update(tick_now.price)
else:
predicted = hw.update(tick_now.price)
if predicted > tick_now.price:
send_order(tick_now.symbol, "BUY", "EXCHANGE_A")
else:
send_order(tick_now.symbol, "BUY", "EXCHANGE_B")
return predicted













No comments:
Post a Comment