House of Win (rules)
TFJS LSTM + Ops
Order Exec (Node)
Aggregator Service
Overfit Detector
Backtest Harness
Grid Search
Position Sizing
Jest Tests
Monte Carlo
House of Win — Decision Algorithm (concise)
- Inputs: EMA(5,20) on 10m, RSI(14) 10m, Stochastic (14,3), Parabolic SAR, VWAP(30), Momentum (1m & 5m), CVD (trade flow), Bid/Ask imbalance, Volume spike (10m)
- Indicator thresholds (defaults): EMA bias if EMA5>EMA20 => +12 score; RSI 30-70 preferred; Stochastic K > D => +6; VWAP breakout => +6; Vol spike => +6; CVD positive => +4; Imbalance >+5% => +6
- Ensemble: LSTM / GRU / XGB placeholders — calibrated weights: wLSTM=0.4, wGRU=0.3, wXGB=0.3. Outputs produce predicted High/Low (pH/pL) used to compute upMove/downMove
- Score -> Decision: score ∈ [0,100]. BUY if score ≥ 70; SELL if score ≤ 35; otherwise HOLD
- Safe gates: block trades if Overfitting detector = CRITICAL OR Liquidity = CRITICAL OR BlackSwan = CRITICAL
- Position Sizing: percent-risk (default 1%). SL uses ATR(14) * 1.2 with minimum SL% safeguard. TP = SL * RR (default RR=2)
Tuning: reduce indicator bonuses or raise score thresholds to reduce trade frequency. Use EWMA to weight models by recent performance for ensemble.
TF.js LSTM model architecture & commands (snippets)
# Keras model (Python) - saved as 'model.h5' locally
from tensorflow import keras
from tensorflow.keras import layers
inputs = keras.Input(shape=(T, F)) # T = timesteps (e.g., 6 x 10-min = 60min -> 6 timesteps), F = features
x = layers.LSTM(128, return_sequences=True)(inputs)
x = layers.Dropout(0.2)(x)
x = layers.LSTM(64)(x)
x = layers.Dense(64, activation='relu')(x)
x = layers.Dropout(0.2)(x)
# Output two numbers: predicted pH, pL (price units or scaled)
outputs = layers.Dense(2, activation='linear')(x)
model = keras.Model(inputs, outputs)
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
# training hyperparams:
# epochs=50, batch_size=64, learning_rate=1e-3, early stopping (patience 5), validation_split=0.1
# Save:
model.save('lstm_model.h5')
# Convert to TFJS:
# 1) install: pip install tensorflowjs
# 2) convert:
tensorflowjs_converter --input_format=keras lstm_model.h5 web_model/
# This will create web_model/model.json + binary shards -> place at /model/model.json on your server (or serve locally)
# Client-side TFJS loader (JS snippet - included in dashboard)
async function loadTFModel(url='/model/model.json'){
try{
window.tfModel = await tf.loadLayersModel(url);
console.info('TFJS model loaded');
return window.tfModel;
}catch(e){
console.warn('TFJS model not found or failed to load, falling back to simulated ensemble', e);
window.tfModel = null;
return null;
}
}
# Preprocessing steps (client-side):
# - Collect last T timesteps of features: normalized (z-score or min-max) using same scaler used in training
# - Ensure shape [1, T, F], dtype=float32
# - Run predict: tfModel.predict(tf.tensor(inputArray)).array()
# - Output: [pH, pL] (apply inverse-scaling if necessary)
# Example TFJS predict wrapper (JS - included in file):
async function predictPHPL(inputArray){ // inputArray shape [T, F]
if(window.tfModel){
const t = tf.tensor([inputArray], undefined, 'float32'); // [1,T,F]
const out = await window.tfModel.predict(t).array();
t.dispose();
return out[0]; // [pH, pL]
} else {
// fallback synthetic ensemble
return simulateEnsemblePrediction(inputArray);
}
}
# Checklist to validate predictions:
# - Ensure features fed into client use same scaling as training (provide mean/std)
# - Run model on a handful of known samples and compare to Keras predict locally
# - Validate shapes: [1,T,F] and numeric dtype float32
# - Check model.loaded === true and no console errors
Secure Node.js Order Execution Microservice (snippets)
// server.js (Express) - minimal secure skeleton (do NOT store real keys in code).
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const app = express();
app.use(helmet()); app.use(bodyParser.json());
// rate limiter
const limiter = rateLimit({ windowMs: 1000*60, max: 120 });
app.use(limiter);
// middleware: verify JWT (example)
function auth(req,res,next){
const authHeader = req.headers.authorization;
if(!authHeader) return res.status(401).json({err:'no auth'});
const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if(err) return res.status(401).json({err:'invalid token'});
req.user = decoded; next();
});
}
// idempotency & HMAC verification example
function verifyHmac(req, res, next){
const idKey = req.headers['idempotency-key'] || '';
const hmac = req.headers['x-signature'] || '';
// signature computed client-side: HMAC_SHA256(secret, idKey + JSON.stringify(body))
const expected = crypto.createHmac('sha256', process.env.SHARED_SECRET).update(idKey + JSON.stringify(req.body)).digest('hex');
if(hmac !== expected) return res.status(401).json({err:'bad signature'});
next();
}
// endpoints
app.post('/order', auth, verifyHmac, async (req,res)=>{
// body: {symbol, side, type, quantity, price, dryRun}
// fetch API keys securely from vault (not env in production)
const dry = req.body.dryRun || false;
// implement placing order with Binance client here (libs: binance-api-node)
// log requests to audit trail (DB)
return res.json({ok:true, dry});
});
app.get('/status', auth, (req,res)=>res.json({ok:true, ts:Date.now()}));
app.post('/webhook', (req,res)=>{
// used by exchange or monitoring systems
// validate source by IP or HMAC
res.json({ok:true});
});
// start
app.listen(process.env.PORT||3000, ()=>console.log('order service alive'));
Vault: store your BINANCE_API_KEY and BINANCE_SECRET in AWS Secrets Manager or Hashicorp Vault. Use short-lived credentials and least privilege. Use environment variables only for references in CI/CD, never hard-coded keys.
# Dockerfile (example)
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
CMD ["node","server.js"]
Node.js Aggregator (1m -> finalized 10m) single-file script + Dockerfile
// aggregator.js - connects to Binance WS, persists finalized 10m candles into SQLite
const WebSocket = require('ws');
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('candles.db');
db.run(`CREATE TABLE IF NOT EXISTS candles(t INTEGER PRIMARY KEY, o REAL, h REAL, l REAL, c REAL, v REAL)`);
const symbol = 'btcusdt';
const ws = new WebSocket(`wss://stream.binance.com:9443/ws/${symbol}@kline_1m`);
let buffer = {}; // store kline by start ts
ws.on('message', (data) => {
const msg = JSON.parse(data);
if(msg.k){
const k = msg.k;
const start = k.t;
const candle = {t:start,o:+k.o,h:+k.h,l:+k.l,c:+k.c,v:+k.v, isFinal: k.x};
// store last candle for that minute, only persist when final
if(candle.isFinal){
// insert candle to sqlite
db.run(`INSERT OR REPLACE INTO candles(t,o,h,l,c,v) VALUES(?,?,?,?,?,?)`, [candle.t, candle.o, candle.h, candle.l, candle.c, candle.v]);
console.log('persisted', new Date(candle.t).toISOString());
}
}
});
// simple REST API via tiny http server (express recommended)
# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
CMD ["node","aggregator.js"]
Overfitting Detector (JS functions + example)
// compute rolling averages, gap, z-score, p-value (approx using normal)
function overfitStats(trainArr, testArr, window=10){
const rollMean = (arr) => {
const r = [];
for(let i=0;ia+b,0)/slice.length);
}
return r;
};
const rt = rollMean(trainArr), rs = rollMean(testArr);
const gapArr = rt.map((v,i)=> (v - (rs[i]||v)) );
const latestGap = gapArr[gapArr.length-1] || 0;
const meanGap = gapArr.reduce((a,b)=>a+b,0)/gapArr.length;
const stdGap = Math.sqrt(gapArr.reduce((a,b)=>a+Math.pow(b-meanGap,2),0)/(gapArr.length||1)) || 1;
const z = (latestGap - meanGap) / stdGap;
// approximate two-sided p-value
const p = Math.exp(-0.717*z*z - 0.416*z*z*z);
let level = 'SAFE';
if(latestGap > 15) level='CRITICAL'; else if(latestGap > 10) level='HIGH'; else if(latestGap > 5) level='MEDIUM';
return {latestGap: Number(latestGap.toFixed(2)), z: Number(z.toFixed(2)), p: Number(p.toFixed(4)), level, gapSeries: gapArr};
}
// Example call:
const train = [78,82,80,85,90,88,92,91,93,94,95];
const test = [70,72,74,75,76,73,74,72,71,70,69];
console.log(overfitStats(train,test,10));
Backtest Harness (browser-based, walk-forward)
// Basic idea (code included in dashboard JS):
// - fetch REST 1m klines
// - aggregate to 10m
// - simulate strategy with slippage & fees
// - rolling windows: trainWindowDays, testWindowDays
// - output metrics & CSV
// Example config:
const btConfig = {
symbol:'BTCUSDT', trainWindowDays:60, testWindowDays:10, feeTaker:0.0006, feeMaker:0.0002, slippagePct:0.001
};
// The dashboard contains a walk-forward backtest function 'runBacktest(config)' that returns metrics: netPL, sharpe, maxDD, winrate, avgTrade
Grid Search / Random Search (JS)
// gridSearch(paramsGrid, runBacktestFn, topN=5)
// paramsGrid example:
// { how:[60,70,80], conf:[70,75,80], volSpike:[1.5,1.8,2.0], emaPeriods:[[5,20],[8,34]] }
async function gridSearch(paramsGrid, runBacktestFn, opts={topN:5, randomTrials:0, earlyStopSharpe:5}){
const keys=Object.keys(paramsGrid);
const combos = [];
function expand(i, acc){
if(i===keys.length){ combos.push({...acc}); return; }
const k = keys[i];
for(const v of paramsGrid[k]){ acc[k]=v; expand(i+1,acc); }
}
expand(0,{});
// optionally random subset
let trials = combos;
if(opts.randomTrials && opts.randomTrials < combos.length){
trials = [];
for(let i=0;i (b.metrics.sharpe||0)-(a.metrics.sharpe||0));
if(results[0] && results[0].metrics.sharpe >= opts.earlyStopSharpe) break;
}
return results.slice(0,opts.topN);
}
// Usage: integrate with dashboard's backtest function
Position Sizing (JS function)
// computePositionSize({accountBalance, riskPct, entryPrice, stopLossDistance, leverage, minNotional})
function computePositionSize({accountBalance=10000, riskPct=1, entryPrice, stopLossDistance, leverage=1, minNotional=10}){
if(!entryPrice || !stopLossDistance) return null;
const riskAmount = accountBalance * (riskPct/100);
const notional = riskAmount / (stopLossDistance || 1e-8);
let baseSize = notional / entryPrice;
baseSize = baseSize * leverage;
// enforce min notional & basic exchange limits
const notionalValue = baseSize * entryPrice;
if(notionalValue < minNotional){
baseSize = minNotional / entryPrice;
}
return {baseSize: Number(baseSize.toFixed(8)), notional: Number((baseSize*entryPrice).toFixed(2)), riskAmount};
}
// Example:
console.log(computePositionSize({accountBalance:10000, riskPct:1, entryPrice:40000, stopLossDistance:200, leverage:1}));
// returns qty ~ 0.0125
Jest Unit Tests for Indicators (files & scripts)
// package.json scripts:
{
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^29.0.0"
}
}
// __tests__/indicators.test.js
const { ema, rsiSeries, stochastic, parabolicSAR, vwap } = require('../indicators');
test('EMA produces expected', ()=>{ expect(ema([1,2,3,4,5],3).slice(-1)[0]).toBeCloseTo(4.25,2); });
test('RSI basic', ()=>{ const r=rsiSeries([1,1.1,1.2,1.15,1.3],3); expect(Number(r.slice(-1)[0]).toFixed(0)).toBeDefined(); });
// more tests with synthetic data...
// Run: npm install && npm test
Monte Carlo Stress Test (JS)
// MonteCarlo: perturb returns by sampling residuals
function monteCarloSim(originalReturns, residuals, nSim=1000, days=252){
const results=[];
for(let s=0;sa-b);
const p5 = results[Math.floor(0.05*results.length)], p95=results[Math.floor(0.95*results.length)];
return {results, p5, p95, median: results[Math.floor(0.5*results.length)]};
}
Comments
Post a Comment