forked from JakeNesler/OpenProphet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvectorDB.js
More file actions
288 lines (264 loc) · 8.65 KB
/
Copy pathvectorDB.js
File metadata and controls
288 lines (264 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// vectorDB.js - Vector similarity search for trading decisions
import Database from 'better-sqlite3';
import * as sqliteVec from 'sqlite-vec';
import { pipeline } from '@xenova/transformers';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Initialize embedding pipeline (local model, no API key needed)
let embedder = null;
async function getEmbedder() {
if (!embedder) {
console.log('🔄 Loading local embedding model (first run may take 30s)...');
embedder = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
console.log('✅ Embedding model loaded');
}
return embedder;
}
// Lazy-initialized SQLite database — deferred until first use so the MCP server
// doesn't crash on import when data/ directory doesn't exist yet.
const dbPath = process.env.DATABASE_PATH || path.join(__dirname, 'data', 'prophet_trader.db');
let _db = null;
function getDb() {
if (!_db) {
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
_db = new Database(dbPath);
sqliteVec.load(_db);
_db.exec(`
CREATE TABLE IF NOT EXISTS trade_embeddings (
id TEXT PRIMARY KEY,
decision_file TEXT NOT NULL,
symbol TEXT,
action TEXT,
strategy TEXT,
result_pct REAL,
result_dollars REAL,
date TEXT,
reasoning TEXT,
market_context TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE VIRTUAL TABLE IF NOT EXISTS trade_vectors USING vec0(
trade_id TEXT PRIMARY KEY,
embedding FLOAT[384]
);
`);
}
return _db;
}
/**
* Get local embedding for text (no API key required)
* @param {string} text - Text to embed
* @returns {Promise<number[]>} - 384-dimensional embedding vector
*/
export async function getEmbedding(text) {
try {
const model = await getEmbedder();
const output = await model(text, { pooling: 'mean', normalize: true });
return Array.from(output.data);
} catch (error) {
console.error('Embedding error:', error.message);
throw error;
}
}
/**
* Store trade decision with embedding for similarity search
* @param {Object} trade - Trade decision object
* @param {string} trade.id - Unique trade ID
* @param {string} trade.decision_file - Path to decision JSON file
* @param {string} trade.symbol - Stock symbol
* @param {string} trade.action - BUY, SELL, HOLD, etc.
* @param {string} trade.strategy - SCALP, SWING, etc.
* @param {number} trade.result_pct - Result percentage (e.g., 26.5 for +26.5%)
* @param {number} trade.result_dollars - Result in dollars (e.g., 1920 for +$1920)
* @param {string} trade.date - Date in YYYY-MM-DD format
* @param {string} trade.reasoning - Trade reasoning/thesis
* @param {string} trade.market_context - Market conditions, catalysts, etc.
* @returns {Promise<void>}
*/
export async function storeTrade(trade) {
try {
// Create embedding from reasoning + market context
const textToEmbed = `${trade.reasoning}\n\nMarket Context: ${trade.market_context}`;
const embedding = await getEmbedding(textToEmbed);
// Store trade metadata
const insertTrade = getDb().prepare(`
INSERT OR REPLACE INTO trade_embeddings (
id, decision_file, symbol, action, strategy,
result_pct, result_dollars, date, reasoning, market_context
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
insertTrade.run(
trade.id,
trade.decision_file,
trade.symbol,
trade.action,
trade.strategy,
trade.result_pct,
trade.result_dollars,
trade.date,
trade.reasoning,
trade.market_context
);
// Store embedding vector
const insertVector = getDb().prepare(`
INSERT OR REPLACE INTO trade_vectors (trade_id, embedding)
VALUES (?, vec_f32(?))
`);
insertVector.run(trade.id, new Float32Array(embedding));
console.log(`✅ Stored trade: ${trade.id} (${trade.symbol} ${trade.action})`);
} catch (error) {
console.error(`❌ Error storing trade ${trade.id}:`, error.message);
throw error;
}
}
/**
* Find trades similar to a query
* @param {string} queryText - Query describing the setup (e.g., "SPY gap up scalp")
* @param {number} limit - Number of similar trades to return
* @param {Object} filters - Optional filters (symbol, action, strategy)
* @returns {Promise<Array>} - Array of similar trades with metadata
*/
export async function findSimilarTrades(queryText, limit = 5, filters = {}) {
try {
// Get query embedding
const queryEmbedding = await getEmbedding(queryText);
// Build filter conditions
let whereClause = '';
const params = [];
if (filters.symbol) {
whereClause += ' AND te.symbol = ?';
params.push(filters.symbol);
}
if (filters.action) {
whereClause += ' AND te.action = ?';
params.push(filters.action);
}
if (filters.strategy) {
whereClause += ' AND te.strategy = ?';
params.push(filters.strategy);
}
// Search for similar trades
const query = getDb().prepare(`
SELECT
te.id,
te.symbol,
te.action,
te.strategy,
te.result_pct,
te.result_dollars,
te.date,
te.reasoning,
te.market_context,
tv.distance
FROM trade_vectors tv
JOIN trade_embeddings te ON tv.trade_id = te.id
WHERE tv.embedding MATCH vec_f32(?)
AND k = ?
${whereClause}
ORDER BY tv.distance
`);
const results = query.all(new Float32Array(queryEmbedding), limit, ...params);
return results.map(r => ({
id: r.id,
symbol: r.symbol,
action: r.action,
strategy: r.strategy,
result_pct: r.result_pct,
result_dollars: r.result_dollars,
date: r.date,
reasoning: r.reasoning,
market_context: r.market_context,
similarity: Math.max(0, 1 - (r.distance / 2)), // Cosine distance 0-2 → similarity 0-1
}));
} catch (error) {
console.error('Error finding similar trades:', error.message);
throw error;
}
}
/**
* Get trade statistics by filters
* @param {Object} filters - Filters (symbol, action, strategy, min_result, max_result)
* @returns {Object} - Statistics (count, win_rate, avg_result, best, worst)
*/
export function getTradeStats(filters = {}) {
try {
let whereClause = 'WHERE 1=1';
const params = [];
if (filters.symbol) {
whereClause += ' AND symbol = ?';
params.push(filters.symbol);
}
if (filters.action) {
whereClause += ' AND action = ?';
params.push(filters.action);
}
if (filters.strategy) {
whereClause += ' AND strategy = ?';
params.push(filters.strategy);
}
if (filters.min_result !== undefined) {
whereClause += ' AND result_pct >= ?';
params.push(filters.min_result);
}
if (filters.max_result !== undefined) {
whereClause += ' AND result_pct <= ?';
params.push(filters.max_result);
}
const query = getDb().prepare(`
SELECT
COUNT(*) as count,
SUM(CASE WHEN result_pct > 0 THEN 1 ELSE 0 END) as winners,
SUM(CASE WHEN result_pct < 0 THEN 1 ELSE 0 END) as losers,
AVG(result_pct) as avg_result_pct,
AVG(result_dollars) as avg_result_dollars,
MAX(result_pct) as best_pct,
MIN(result_pct) as worst_pct,
MAX(result_dollars) as best_dollars,
MIN(result_dollars) as worst_dollars
FROM trade_embeddings
${whereClause}
`);
const stats = query.get(...params);
return {
count: stats.count || 0,
winners: stats.winners || 0,
losers: stats.losers || 0,
win_rate: stats.count > 0 ? (stats.winners / stats.count) * 100 : 0,
avg_result_pct: stats.avg_result_pct || 0,
avg_result_dollars: stats.avg_result_dollars || 0,
best_result_pct: stats.best_pct || 0,
worst_result_pct: stats.worst_pct || 0,
best_result_dollars: stats.best_dollars || 0,
worst_result_dollars: stats.worst_dollars || 0,
};
} catch (error) {
console.error('Error getting trade stats:', error.message);
throw error;
}
}
/**
* Delete all embeddings (useful for re-indexing)
*/
export function clearAllEmbeddings() {
getDb().exec('DELETE FROM trade_embeddings');
getDb().exec('DELETE FROM trade_vectors');
console.log('✅ Cleared all embeddings');
}
/**
* Get total number of embedded trades
*/
export function getEmbeddingCount() {
const result = getDb().prepare('SELECT COUNT(*) as count FROM trade_embeddings').get();
return result.count;
}
export default {
getEmbedding,
storeTrade,
findSimilarTrades,
getTradeStats,
clearAllEmbeddings,
getEmbeddingCount,
};