@timmeck/trading-brain 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/README.md +306 -0
  2. package/dist/api/server.d.ts +21 -0
  3. package/dist/api/server.js +157 -0
  4. package/dist/api/server.js.map +1 -0
  5. package/dist/cli/colors.d.ts +46 -0
  6. package/dist/cli/colors.js +70 -0
  7. package/dist/cli/colors.js.map +1 -0
  8. package/dist/cli/commands/config.d.ts +2 -0
  9. package/dist/cli/commands/config.js +70 -0
  10. package/dist/cli/commands/config.js.map +1 -0
  11. package/dist/cli/commands/doctor.d.ts +2 -0
  12. package/dist/cli/commands/doctor.js +61 -0
  13. package/dist/cli/commands/doctor.js.map +1 -0
  14. package/dist/cli/commands/export.d.ts +2 -0
  15. package/dist/cli/commands/export.js +23 -0
  16. package/dist/cli/commands/export.js.map +1 -0
  17. package/dist/cli/commands/import.d.ts +2 -0
  18. package/dist/cli/commands/import.js +42 -0
  19. package/dist/cli/commands/import.js.map +1 -0
  20. package/dist/cli/commands/insights.d.ts +2 -0
  21. package/dist/cli/commands/insights.js +29 -0
  22. package/dist/cli/commands/insights.js.map +1 -0
  23. package/dist/cli/commands/network.d.ts +2 -0
  24. package/dist/cli/commands/network.js +43 -0
  25. package/dist/cli/commands/network.js.map +1 -0
  26. package/dist/cli/commands/query.d.ts +2 -0
  27. package/dist/cli/commands/query.js +27 -0
  28. package/dist/cli/commands/query.js.map +1 -0
  29. package/dist/cli/commands/rules.d.ts +2 -0
  30. package/dist/cli/commands/rules.js +26 -0
  31. package/dist/cli/commands/rules.js.map +1 -0
  32. package/dist/cli/commands/start.d.ts +2 -0
  33. package/dist/cli/commands/start.js +86 -0
  34. package/dist/cli/commands/start.js.map +1 -0
  35. package/dist/cli/commands/status.d.ts +2 -0
  36. package/dist/cli/commands/status.js +58 -0
  37. package/dist/cli/commands/status.js.map +1 -0
  38. package/dist/cli/commands/stop.d.ts +2 -0
  39. package/dist/cli/commands/stop.js +34 -0
  40. package/dist/cli/commands/stop.js.map +1 -0
  41. package/dist/cli/ipc-helper.d.ts +2 -0
  42. package/dist/cli/ipc-helper.js +26 -0
  43. package/dist/cli/ipc-helper.js.map +1 -0
  44. package/dist/config.d.ts +2 -0
  45. package/dist/config.js +107 -0
  46. package/dist/config.js.map +1 -0
  47. package/dist/db/connection.d.ts +2 -0
  48. package/dist/db/connection.js +19 -0
  49. package/dist/db/connection.js.map +1 -0
  50. package/dist/db/migrations/001_core.d.ts +2 -0
  51. package/dist/db/migrations/001_core.js +42 -0
  52. package/dist/db/migrations/001_core.js.map +1 -0
  53. package/dist/db/migrations/002_synapses.d.ts +2 -0
  54. package/dist/db/migrations/002_synapses.js +43 -0
  55. package/dist/db/migrations/002_synapses.js.map +1 -0
  56. package/dist/db/migrations/003_learning.d.ts +2 -0
  57. package/dist/db/migrations/003_learning.js +48 -0
  58. package/dist/db/migrations/003_learning.js.map +1 -0
  59. package/dist/db/migrations/004_research.d.ts +2 -0
  60. package/dist/db/migrations/004_research.js +29 -0
  61. package/dist/db/migrations/004_research.js.map +1 -0
  62. package/dist/db/migrations/index.d.ts +2 -0
  63. package/dist/db/migrations/index.js +45 -0
  64. package/dist/db/migrations/index.js.map +1 -0
  65. package/dist/db/repositories/calibration.repository.d.ts +25 -0
  66. package/dist/db/repositories/calibration.repository.js +66 -0
  67. package/dist/db/repositories/calibration.repository.js.map +1 -0
  68. package/dist/db/repositories/chain.repository.d.ts +28 -0
  69. package/dist/db/repositories/chain.repository.js +52 -0
  70. package/dist/db/repositories/chain.repository.js.map +1 -0
  71. package/dist/db/repositories/graph.repository.d.ts +33 -0
  72. package/dist/db/repositories/graph.repository.js +73 -0
  73. package/dist/db/repositories/graph.repository.js.map +1 -0
  74. package/dist/db/repositories/insight.repository.d.ts +30 -0
  75. package/dist/db/repositories/insight.repository.js +60 -0
  76. package/dist/db/repositories/insight.repository.js.map +1 -0
  77. package/dist/db/repositories/rule.repository.d.ts +35 -0
  78. package/dist/db/repositories/rule.repository.js +48 -0
  79. package/dist/db/repositories/rule.repository.js.map +1 -0
  80. package/dist/db/repositories/signal.repository.d.ts +17 -0
  81. package/dist/db/repositories/signal.repository.js +35 -0
  82. package/dist/db/repositories/signal.repository.js.map +1 -0
  83. package/dist/db/repositories/synapse.repository.d.ts +25 -0
  84. package/dist/db/repositories/synapse.repository.js +50 -0
  85. package/dist/db/repositories/synapse.repository.js.map +1 -0
  86. package/dist/db/repositories/trade.repository.d.ts +36 -0
  87. package/dist/db/repositories/trade.repository.js +64 -0
  88. package/dist/db/repositories/trade.repository.js.map +1 -0
  89. package/dist/graph/weighted-graph.d.ts +58 -0
  90. package/dist/graph/weighted-graph.js +149 -0
  91. package/dist/graph/weighted-graph.js.map +1 -0
  92. package/dist/index.d.ts +2 -0
  93. package/dist/index.js +49 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/ipc/client.d.ts +16 -0
  96. package/dist/ipc/client.js +95 -0
  97. package/dist/ipc/client.js.map +1 -0
  98. package/dist/ipc/protocol.d.ts +8 -0
  99. package/dist/ipc/protocol.js +29 -0
  100. package/dist/ipc/protocol.js.map +1 -0
  101. package/dist/ipc/router.d.ts +32 -0
  102. package/dist/ipc/router.js +70 -0
  103. package/dist/ipc/router.js.map +1 -0
  104. package/dist/ipc/server.d.ts +18 -0
  105. package/dist/ipc/server.js +142 -0
  106. package/dist/ipc/server.js.map +1 -0
  107. package/dist/learning/calibrator.d.ts +6 -0
  108. package/dist/learning/calibrator.js +57 -0
  109. package/dist/learning/calibrator.js.map +1 -0
  110. package/dist/learning/chain-detector.d.ts +17 -0
  111. package/dist/learning/chain-detector.js +29 -0
  112. package/dist/learning/chain-detector.js.map +1 -0
  113. package/dist/learning/learning-engine.d.ts +31 -0
  114. package/dist/learning/learning-engine.js +85 -0
  115. package/dist/learning/learning-engine.js.map +1 -0
  116. package/dist/learning/pattern-extractor.d.ts +14 -0
  117. package/dist/learning/pattern-extractor.js +40 -0
  118. package/dist/learning/pattern-extractor.js.map +1 -0
  119. package/dist/mcp/http-server.d.ts +14 -0
  120. package/dist/mcp/http-server.js +117 -0
  121. package/dist/mcp/http-server.js.map +1 -0
  122. package/dist/mcp/server.d.ts +1 -0
  123. package/dist/mcp/server.js +67 -0
  124. package/dist/mcp/server.js.map +1 -0
  125. package/dist/mcp/tools.d.ts +7 -0
  126. package/dist/mcp/tools.js +158 -0
  127. package/dist/mcp/tools.js.map +1 -0
  128. package/dist/research/research-engine.d.ts +21 -0
  129. package/dist/research/research-engine.js +204 -0
  130. package/dist/research/research-engine.js.map +1 -0
  131. package/dist/services/analytics.service.d.ts +16 -0
  132. package/dist/services/analytics.service.js +64 -0
  133. package/dist/services/analytics.service.js.map +1 -0
  134. package/dist/services/insight.service.d.ts +11 -0
  135. package/dist/services/insight.service.js +25 -0
  136. package/dist/services/insight.service.js.map +1 -0
  137. package/dist/services/signal.service.d.ts +22 -0
  138. package/dist/services/signal.service.js +96 -0
  139. package/dist/services/signal.service.js.map +1 -0
  140. package/dist/services/strategy.service.d.ts +29 -0
  141. package/dist/services/strategy.service.js +115 -0
  142. package/dist/services/strategy.service.js.map +1 -0
  143. package/dist/services/synapse.service.d.ts +20 -0
  144. package/dist/services/synapse.service.js +48 -0
  145. package/dist/services/synapse.service.js.map +1 -0
  146. package/dist/services/trade.service.d.ts +37 -0
  147. package/dist/services/trade.service.js +114 -0
  148. package/dist/services/trade.service.js.map +1 -0
  149. package/dist/signals/fingerprint.d.ts +29 -0
  150. package/dist/signals/fingerprint.js +98 -0
  151. package/dist/signals/fingerprint.js.map +1 -0
  152. package/dist/signals/wilson-score.d.ts +10 -0
  153. package/dist/signals/wilson-score.js +19 -0
  154. package/dist/signals/wilson-score.js.map +1 -0
  155. package/dist/synapses/decay.d.ts +6 -0
  156. package/dist/synapses/decay.js +17 -0
  157. package/dist/synapses/decay.js.map +1 -0
  158. package/dist/synapses/hebbian.d.ts +11 -0
  159. package/dist/synapses/hebbian.js +21 -0
  160. package/dist/synapses/hebbian.js.map +1 -0
  161. package/dist/synapses/synapse-manager.d.ts +22 -0
  162. package/dist/synapses/synapse-manager.js +99 -0
  163. package/dist/synapses/synapse-manager.js.map +1 -0
  164. package/dist/trading-core.d.ts +17 -0
  165. package/dist/trading-core.js +235 -0
  166. package/dist/trading-core.js.map +1 -0
  167. package/dist/types/config.types.d.ts +52 -0
  168. package/dist/types/config.types.js +2 -0
  169. package/dist/types/config.types.js.map +1 -0
  170. package/dist/types/ipc.types.d.ts +11 -0
  171. package/dist/types/ipc.types.js +2 -0
  172. package/dist/types/ipc.types.js.map +1 -0
  173. package/dist/utils/events.d.ts +48 -0
  174. package/dist/utils/events.js +23 -0
  175. package/dist/utils/events.js.map +1 -0
  176. package/dist/utils/hash.d.ts +1 -0
  177. package/dist/utils/hash.js +5 -0
  178. package/dist/utils/hash.js.map +1 -0
  179. package/dist/utils/logger.d.ts +8 -0
  180. package/dist/utils/logger.js +39 -0
  181. package/dist/utils/logger.js.map +1 -0
  182. package/dist/utils/paths.d.ts +3 -0
  183. package/dist/utils/paths.js +18 -0
  184. package/dist/utils/paths.js.map +1 -0
  185. package/package.json +47 -0
  186. package/src/api/server.ts +160 -0
  187. package/src/cli/colors.ts +80 -0
  188. package/src/cli/commands/config.ts +76 -0
  189. package/src/cli/commands/doctor.ts +62 -0
  190. package/src/cli/commands/export.ts +24 -0
  191. package/src/cli/commands/import.ts +44 -0
  192. package/src/cli/commands/insights.ts +30 -0
  193. package/src/cli/commands/network.ts +43 -0
  194. package/src/cli/commands/query.ts +28 -0
  195. package/src/cli/commands/rules.ts +27 -0
  196. package/src/cli/commands/start.ts +93 -0
  197. package/src/cli/commands/status.ts +64 -0
  198. package/src/cli/commands/stop.ts +33 -0
  199. package/src/cli/ipc-helper.ts +22 -0
  200. package/src/config.ts +103 -0
  201. package/src/db/connection.ts +22 -0
  202. package/src/db/migrations/001_core.ts +43 -0
  203. package/src/db/migrations/002_synapses.ts +44 -0
  204. package/src/db/migrations/003_learning.ts +49 -0
  205. package/src/db/migrations/004_research.ts +30 -0
  206. package/src/db/migrations/index.ts +60 -0
  207. package/src/db/repositories/calibration.repository.ts +86 -0
  208. package/src/db/repositories/chain.repository.ts +70 -0
  209. package/src/db/repositories/graph.repository.ts +103 -0
  210. package/src/db/repositories/insight.repository.ts +80 -0
  211. package/src/db/repositories/rule.repository.ts +67 -0
  212. package/src/db/repositories/signal.repository.ts +48 -0
  213. package/src/db/repositories/synapse.repository.ts +71 -0
  214. package/src/db/repositories/trade.repository.ts +97 -0
  215. package/src/graph/weighted-graph.ts +194 -0
  216. package/src/index.ts +55 -0
  217. package/src/ipc/client.ts +112 -0
  218. package/src/ipc/protocol.ts +35 -0
  219. package/src/ipc/router.ts +113 -0
  220. package/src/ipc/server.ts +150 -0
  221. package/src/learning/calibrator.ts +57 -0
  222. package/src/learning/chain-detector.ts +43 -0
  223. package/src/learning/learning-engine.ts +94 -0
  224. package/src/learning/pattern-extractor.ts +53 -0
  225. package/src/mcp/http-server.ts +118 -0
  226. package/src/mcp/server.ts +72 -0
  227. package/src/mcp/tools.ts +256 -0
  228. package/src/research/research-engine.ts +223 -0
  229. package/src/services/analytics.service.ts +68 -0
  230. package/src/services/insight.service.ts +29 -0
  231. package/src/services/signal.service.ts +109 -0
  232. package/src/services/strategy.service.ts +130 -0
  233. package/src/services/synapse.service.ts +58 -0
  234. package/src/services/trade.service.ts +139 -0
  235. package/src/signals/fingerprint.ts +93 -0
  236. package/src/signals/wilson-score.ts +17 -0
  237. package/src/synapses/decay.ts +19 -0
  238. package/src/synapses/hebbian.ts +23 -0
  239. package/src/synapses/synapse-manager.ts +112 -0
  240. package/src/trading-core.ts +285 -0
  241. package/src/types/config.types.ts +60 -0
  242. package/src/types/ipc.types.ts +8 -0
  243. package/src/utils/events.ts +42 -0
  244. package/src/utils/hash.ts +5 -0
  245. package/src/utils/logger.ts +48 -0
  246. package/src/utils/paths.ts +19 -0
  247. package/tsconfig.json +18 -0
@@ -0,0 +1,194 @@
1
+ export const NODE_TYPES = {
2
+ SIGNAL: 'signal',
3
+ REGIME: 'regime',
4
+ OUTCOME: 'outcome',
5
+ PAIR: 'pair',
6
+ BOT_TYPE: 'bot_type',
7
+ TIME: 'time',
8
+ COMBO: 'combo',
9
+ } as const;
10
+
11
+ export type NodeType = typeof NODE_TYPES[keyof typeof NODE_TYPES];
12
+
13
+ export interface GraphNode {
14
+ id: string;
15
+ type: string;
16
+ label: string;
17
+ activation: number;
18
+ totalActivations: number;
19
+ }
20
+
21
+ export interface GraphEdge {
22
+ source: string;
23
+ target: string;
24
+ weight: number;
25
+ activations: number;
26
+ lastActivated: number;
27
+ }
28
+
29
+ export interface ActivatedNode {
30
+ id: string;
31
+ type: string;
32
+ label: string;
33
+ activation: number;
34
+ }
35
+
36
+ export class WeightedGraph {
37
+ nodes: Record<string, GraphNode> = {};
38
+ edges: Record<string, GraphEdge> = {};
39
+
40
+ addNode(id: string, type: string, label: string): GraphNode {
41
+ if (!this.nodes[id]) {
42
+ this.nodes[id] = { id, type, label, activation: 0, totalActivations: 0 };
43
+ }
44
+ return this.nodes[id]!;
45
+ }
46
+
47
+ addEdge(sourceId: string, targetId: string, weight: number = 0.5): GraphEdge {
48
+ const edgeId = `${sourceId}->${targetId}`;
49
+ const reverseId = `${targetId}->${sourceId}`;
50
+ if (!this.edges[edgeId]) {
51
+ this.edges[edgeId] = { source: sourceId, target: targetId, weight, activations: 0, lastActivated: 0 };
52
+ }
53
+ if (!this.edges[reverseId]) {
54
+ this.edges[reverseId] = { source: targetId, target: sourceId, weight, activations: 0, lastActivated: 0 };
55
+ }
56
+ return this.edges[edgeId]!;
57
+ }
58
+
59
+ strengthenEdge(sourceId: string, targetId: string, amount: number = 0.1): void {
60
+ const edgeId = `${sourceId}->${targetId}`;
61
+ const reverseId = `${targetId}->${sourceId}`;
62
+ for (const id of [edgeId, reverseId]) {
63
+ const edge = this.edges[id];
64
+ if (edge) {
65
+ edge.weight = Math.min(1.0, edge.weight + (1.0 - edge.weight) * amount);
66
+ edge.activations++;
67
+ edge.lastActivated = Date.now();
68
+ }
69
+ }
70
+ }
71
+
72
+ weakenEdge(sourceId: string, targetId: string, factor: number = 0.8): void {
73
+ const edgeId = `${sourceId}->${targetId}`;
74
+ const reverseId = `${targetId}->${sourceId}`;
75
+ for (const id of [edgeId, reverseId]) {
76
+ const edge = this.edges[id];
77
+ if (edge) {
78
+ edge.weight *= factor;
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Spreading Activation — BFS energy propagation through the graph.
85
+ * Returns activated nodes sorted by activation level descending.
86
+ */
87
+ spreadingActivation(
88
+ startNodeId: string,
89
+ initialEnergy: number = 1.0,
90
+ decayFactor: number = 0.6,
91
+ threshold: number = 0.05,
92
+ maxDepth: number = 4,
93
+ ): ActivatedNode[] {
94
+ // Reset activations
95
+ for (const node of Object.values(this.nodes)) {
96
+ node.activation = 0;
97
+ }
98
+
99
+ if (!this.nodes[startNodeId]) return [];
100
+
101
+ const queue: Array<{ nodeId: string; energy: number; depth: number }> = [
102
+ { nodeId: startNodeId, energy: initialEnergy, depth: 0 },
103
+ ];
104
+ const visited = new Set<string>();
105
+
106
+ while (queue.length > 0) {
107
+ const { nodeId, energy, depth } = queue.shift()!;
108
+
109
+ if (visited.has(nodeId) || energy < threshold || depth > maxDepth) continue;
110
+ visited.add(nodeId);
111
+
112
+ const node = this.nodes[nodeId];
113
+ if (!node) continue;
114
+
115
+ node.activation += energy;
116
+ node.totalActivations++;
117
+
118
+ // Find outgoing edges
119
+ for (const edge of Object.values(this.edges)) {
120
+ if (edge.source === nodeId && !visited.has(edge.target)) {
121
+ const propagatedEnergy = energy * edge.weight * decayFactor;
122
+ if (propagatedEnergy >= threshold) {
123
+ queue.push({ nodeId: edge.target, energy: propagatedEnergy, depth: depth + 1 });
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ return Object.values(this.nodes)
130
+ .filter(n => n.activation > 0)
131
+ .sort((a, b) => b.activation - a.activation)
132
+ .map(n => ({ id: n.id, type: n.type, label: n.label, activation: n.activation }));
133
+ }
134
+
135
+ getEdgesFor(nodeId: string): GraphEdge[] {
136
+ return Object.values(this.edges).filter(e => e.source === nodeId || e.target === nodeId);
137
+ }
138
+
139
+ /** Apply temporal decay to all edges */
140
+ decayEdges(halfLifeMs: number): void {
141
+ const now = Date.now();
142
+ for (const edge of Object.values(this.edges)) {
143
+ if (edge.lastActivated > 0) {
144
+ const age = now - edge.lastActivated;
145
+ if (age > halfLifeMs) {
146
+ const periods = age / halfLifeMs;
147
+ edge.weight = Math.max(0.01, edge.weight * Math.pow(0.5, periods));
148
+ }
149
+ }
150
+ }
151
+ }
152
+
153
+ /** Find shortest path between two nodes using BFS */
154
+ findPath(fromId: string, toId: string, maxDepth: number = 6): string[] | null {
155
+ if (!this.nodes[fromId] || !this.nodes[toId]) return null;
156
+ if (fromId === toId) return [fromId];
157
+
158
+ const queue: Array<{ nodeId: string; path: string[] }> = [{ nodeId: fromId, path: [fromId] }];
159
+ const visited = new Set<string>();
160
+
161
+ while (queue.length > 0) {
162
+ const { nodeId, path } = queue.shift()!;
163
+ if (visited.has(nodeId) || path.length > maxDepth) continue;
164
+ visited.add(nodeId);
165
+
166
+ for (const edge of Object.values(this.edges)) {
167
+ if (edge.source === nodeId && !visited.has(edge.target)) {
168
+ const newPath = [...path, edge.target];
169
+ if (edge.target === toId) return newPath;
170
+ queue.push({ nodeId: edge.target, path: newPath });
171
+ }
172
+ }
173
+ }
174
+
175
+ return null;
176
+ }
177
+
178
+ serialize(): { nodes: GraphNode[]; edges: GraphEdge[] } {
179
+ return {
180
+ nodes: Object.values(this.nodes),
181
+ edges: Object.values(this.edges),
182
+ };
183
+ }
184
+
185
+ deserialize(data: { nodes: GraphNode[]; edges: GraphEdge[] }): void {
186
+ this.nodes = {};
187
+ this.edges = {};
188
+ if (data.nodes) data.nodes.forEach(n => { this.nodes[n.id] = n; });
189
+ if (data.edges) data.edges.forEach(e => { this.edges[`${e.source}->${e.target}`] = e; });
190
+ }
191
+
192
+ getNodeCount(): number { return Object.keys(this.nodes).length; }
193
+ getEdgeCount(): number { return Object.keys(this.edges).length; }
194
+ }
package/src/index.ts ADDED
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from 'commander';
4
+ import { startCommand } from './cli/commands/start.js';
5
+ import { stopCommand } from './cli/commands/stop.js';
6
+ import { statusCommand } from './cli/commands/status.js';
7
+ import { queryCommand } from './cli/commands/query.js';
8
+ import { insightsCommand } from './cli/commands/insights.js';
9
+ import { rulesCommand } from './cli/commands/rules.js';
10
+ import { networkCommand } from './cli/commands/network.js';
11
+ import { exportCommand } from './cli/commands/export.js';
12
+ import { importCommand } from './cli/commands/import.js';
13
+ import { configCommand } from './cli/commands/config.js';
14
+ import { doctorCommand } from './cli/commands/doctor.js';
15
+
16
+ const program = new Command();
17
+
18
+ program
19
+ .name('trading')
20
+ .description('Trading Brain — Adaptive Trading Intelligence & Signal Learning System')
21
+ .version('1.0.0');
22
+
23
+ program.addCommand(startCommand());
24
+ program.addCommand(stopCommand());
25
+ program.addCommand(statusCommand());
26
+ program.addCommand(queryCommand());
27
+ program.addCommand(insightsCommand());
28
+ program.addCommand(rulesCommand());
29
+ program.addCommand(networkCommand());
30
+ program.addCommand(exportCommand());
31
+ program.addCommand(importCommand());
32
+ program.addCommand(configCommand());
33
+ program.addCommand(doctorCommand());
34
+
35
+ // Hidden command: run MCP server (called by Claude Code)
36
+ program
37
+ .command('mcp-server')
38
+ .description('Start MCP server (stdio transport, used by Claude Code)')
39
+ .action(async () => {
40
+ const { startMcpServer } = await import('./mcp/server.js');
41
+ await startMcpServer();
42
+ });
43
+
44
+ // Hidden command: run daemon in foreground (called by start command)
45
+ program
46
+ .command('daemon')
47
+ .description('Run daemon in foreground')
48
+ .option('-c, --config <path>', 'Config file path')
49
+ .action(async (opts) => {
50
+ const { TradingCore } = await import('./trading-core.js');
51
+ const core = new TradingCore();
52
+ core.start(opts.config);
53
+ });
54
+
55
+ program.parse();
@@ -0,0 +1,112 @@
1
+ import net from 'node:net';
2
+ import { randomUUID } from 'node:crypto';
3
+ import type { IpcMessage } from '../types/ipc.types.js';
4
+ import { encodeMessage, MessageDecoder } from './protocol.js';
5
+ import { getPipeName } from '../utils/paths.js';
6
+
7
+ interface PendingRequest {
8
+ resolve: (result: unknown) => void;
9
+ reject: (err: Error) => void;
10
+ timer: ReturnType<typeof setTimeout>;
11
+ }
12
+
13
+ export class IpcClient {
14
+ private socket: net.Socket | null = null;
15
+ private decoder = new MessageDecoder();
16
+ private pending = new Map<string, PendingRequest>();
17
+ private onNotification?: (msg: IpcMessage) => void;
18
+
19
+ constructor(
20
+ private pipeName: string = getPipeName(),
21
+ private timeout: number = 5000,
22
+ ) {}
23
+
24
+ connect(): Promise<void> {
25
+ return new Promise((resolve, reject) => {
26
+ this.socket = net.createConnection(this.pipeName, () => {
27
+ resolve();
28
+ });
29
+
30
+ this.socket.on('data', (chunk) => {
31
+ const messages = this.decoder.feed(chunk);
32
+ for (const msg of messages) {
33
+ this.handleMessage(msg);
34
+ }
35
+ });
36
+
37
+ this.socket.on('error', (err) => {
38
+ reject(err);
39
+ for (const [id, req] of this.pending) {
40
+ clearTimeout(req.timer);
41
+ req.reject(new Error(`Connection error: ${err.message}`));
42
+ this.pending.delete(id);
43
+ }
44
+ });
45
+
46
+ this.socket.on('close', () => {
47
+ for (const [id, req] of this.pending) {
48
+ clearTimeout(req.timer);
49
+ req.reject(new Error('Connection closed'));
50
+ this.pending.delete(id);
51
+ }
52
+ this.socket = null;
53
+ });
54
+ });
55
+ }
56
+
57
+ request(method: string, params?: unknown): Promise<unknown> {
58
+ return new Promise((resolve, reject) => {
59
+ if (!this.socket || this.socket.destroyed) {
60
+ return reject(new Error('Not connected'));
61
+ }
62
+
63
+ const id = randomUUID();
64
+ const timer = setTimeout(() => {
65
+ this.pending.delete(id);
66
+ reject(new Error(`Request timeout: ${method} (${this.timeout}ms)`));
67
+ }, this.timeout);
68
+
69
+ this.pending.set(id, { resolve, reject, timer });
70
+
71
+ const msg: IpcMessage = { id, type: 'request', method, params };
72
+ this.socket.write(encodeMessage(msg));
73
+ });
74
+ }
75
+
76
+ setNotificationHandler(handler: (msg: IpcMessage) => void): void {
77
+ this.onNotification = handler;
78
+ }
79
+
80
+ disconnect(): void {
81
+ for (const [id, req] of this.pending) {
82
+ clearTimeout(req.timer);
83
+ req.reject(new Error('Client disconnecting'));
84
+ this.pending.delete(id);
85
+ }
86
+ this.socket?.destroy();
87
+ this.socket = null;
88
+ this.decoder.reset();
89
+ }
90
+
91
+ get connected(): boolean {
92
+ return this.socket !== null && !this.socket.destroyed;
93
+ }
94
+
95
+ private handleMessage(msg: IpcMessage): void {
96
+ if (msg.type === 'response') {
97
+ const req = this.pending.get(msg.id);
98
+ if (!req) return;
99
+
100
+ clearTimeout(req.timer);
101
+ this.pending.delete(msg.id);
102
+
103
+ if (msg.error) {
104
+ req.reject(new Error(msg.error.message));
105
+ } else {
106
+ req.resolve(msg.result);
107
+ }
108
+ } else if (msg.type === 'notification') {
109
+ this.onNotification?.(msg);
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,35 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import type { IpcMessage } from '../types/ipc.types.js';
3
+
4
+ export function encodeMessage(msg: IpcMessage): Buffer {
5
+ const json = JSON.stringify(msg);
6
+ const payload = Buffer.from(json, 'utf8');
7
+ const frame = Buffer.alloc(4 + payload.length);
8
+ frame.writeUInt32BE(payload.length, 0);
9
+ payload.copy(frame, 4);
10
+ return frame;
11
+ }
12
+
13
+ export class MessageDecoder {
14
+ private buffer = Buffer.alloc(0);
15
+
16
+ feed(chunk: Buffer): IpcMessage[] {
17
+ this.buffer = Buffer.concat([this.buffer, chunk]);
18
+ const messages: IpcMessage[] = [];
19
+
20
+ while (this.buffer.length >= 4) {
21
+ const length = this.buffer.readUInt32BE(0);
22
+ if (this.buffer.length < 4 + length) break;
23
+
24
+ const json = this.buffer.subarray(4, 4 + length).toString('utf8');
25
+ this.buffer = this.buffer.subarray(4 + length);
26
+ messages.push(JSON.parse(json) as IpcMessage);
27
+ }
28
+
29
+ return messages;
30
+ }
31
+
32
+ reset(): void {
33
+ this.buffer = Buffer.alloc(0);
34
+ }
35
+ }
@@ -0,0 +1,113 @@
1
+ import { getLogger } from '../utils/logger.js';
2
+ import type { TradeService } from '../services/trade.service.js';
3
+ import type { SignalService } from '../services/signal.service.js';
4
+ import type { StrategyService } from '../services/strategy.service.js';
5
+ import type { SynapseService } from '../services/synapse.service.js';
6
+ import type { AnalyticsService } from '../services/analytics.service.js';
7
+ import type { InsightService } from '../services/insight.service.js';
8
+ import type { LearningEngine } from '../learning/learning-engine.js';
9
+ import type { ResearchEngine } from '../research/research-engine.js';
10
+ import type { RuleRepository } from '../db/repositories/rule.repository.js';
11
+ import type { ChainRepository } from '../db/repositories/chain.repository.js';
12
+ import type { CalibrationRepository } from '../db/repositories/calibration.repository.js';
13
+
14
+ const logger = getLogger();
15
+
16
+ export interface Services {
17
+ trade: TradeService;
18
+ signal: SignalService;
19
+ strategy: StrategyService;
20
+ synapse: SynapseService;
21
+ analytics: AnalyticsService;
22
+ insight: InsightService;
23
+ ruleRepo: RuleRepository;
24
+ chainRepo: ChainRepository;
25
+ calRepo: CalibrationRepository;
26
+ learning?: LearningEngine;
27
+ research?: ResearchEngine;
28
+ }
29
+
30
+ type MethodHandler = (params: unknown) => unknown;
31
+
32
+ export class IpcRouter {
33
+ private methods: Map<string, MethodHandler>;
34
+
35
+ constructor(private services: Services) {
36
+ this.methods = this.buildMethodMap();
37
+ }
38
+
39
+ handle(method: string, params: unknown): unknown {
40
+ const handler = this.methods.get(method);
41
+ if (!handler) {
42
+ throw new Error(`Unknown method: ${method}`);
43
+ }
44
+
45
+ logger.debug(`IPC: ${method}`, { params });
46
+ const result = handler(params);
47
+ logger.debug(`IPC: ${method} → done`);
48
+ return result;
49
+ }
50
+
51
+ listMethods(): string[] {
52
+ return Array.from(this.methods.keys()).sort();
53
+ }
54
+
55
+ private buildMethodMap(): Map<string, MethodHandler> {
56
+ const s = this.services;
57
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
58
+ const p = (params: unknown) => params as any;
59
+
60
+ return new Map<string, MethodHandler>([
61
+ // ─── Trade ──────────────────────────────────────────
62
+ ['trade.recordOutcome', (params) => s.trade.recordOutcome(p(params))],
63
+ ['trade.query', (params) => s.trade.query(p(params).search ?? '', p(params).limit)],
64
+ ['trade.recent', (params) => s.trade.getRecent(p(params).limit)],
65
+ ['trade.byPair', (params) => s.trade.getByPair(p(params).pair)],
66
+ ['trade.count', () => s.trade.count()],
67
+
68
+ // ─── Signal ─────────────────────────────────────────
69
+ ['signal.weights', (params) => s.signal.getSignalWeights(p(params).signals, p(params).regime)],
70
+ ['signal.confidence', (params) => s.signal.getConfidence(p(params).signals, p(params).regime)],
71
+
72
+ // ─── Strategy ───────────────────────────────────────
73
+ ['strategy.dcaMultiplier', (params) => s.strategy.getDCAMultiplier(p(params).regime, p(params).rsi, p(params).volatility)],
74
+ ['strategy.gridParams', (params) => s.strategy.getGridParams(p(params).regime, p(params).volatility, p(params).pair)],
75
+
76
+ // ─── Synapse ────────────────────────────────────────
77
+ ['synapse.explore', (params) => s.synapse.explore(p(params).query)],
78
+ ['synapse.findPath', (params) => s.synapse.findPath(p(params).from, p(params).to)],
79
+ ['synapse.stats', () => s.synapse.getStats()],
80
+
81
+ // ─── Rules ──────────────────────────────────────────
82
+ ['rule.list', () => s.ruleRepo.getAll()],
83
+ ['rule.count', () => s.ruleRepo.count()],
84
+
85
+ // ─── Chains ─────────────────────────────────────────
86
+ ['chain.list', (params) => s.chainRepo.getRecent(p(params).limit ?? 20)],
87
+ ['chain.byPair', (params) => s.chainRepo.getByPair(p(params).pair)],
88
+
89
+ // ─── Insights ───────────────────────────────────────
90
+ ['insight.list', (params) => s.insight.getRecent(p(params).limit ?? 20)],
91
+ ['insight.byType', (params) => s.insight.getByType(p(params).type)],
92
+ ['insight.count', () => s.insight.count()],
93
+
94
+ // ─── Calibration ────────────────────────────────────
95
+ ['calibration.get', () => s.learning?.getCalibration() ?? s.calRepo.get()],
96
+
97
+ // ─── Analytics ──────────────────────────────────────
98
+ ['analytics.summary', () => s.analytics.getSummary()],
99
+
100
+ // ─── Learning ───────────────────────────────────────
101
+ ['learning.run', () => s.learning?.runManual()],
102
+
103
+ // ─── Research ───────────────────────────────────────
104
+ ['research.run', () => s.research?.runManual()],
105
+
106
+ // ─── Reset ──────────────────────────────────────────
107
+ ['reset', () => {
108
+ // This will be wired in TradingCore
109
+ return { success: true, message: 'Reset not available via IPC — use CLI' };
110
+ }],
111
+ ]);
112
+ }
113
+ }
@@ -0,0 +1,150 @@
1
+ import net from 'node:net';
2
+ import fs from 'node:fs';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { getLogger } from '../utils/logger.js';
5
+ import type { IpcMessage } from '../types/ipc.types.js';
6
+ import { encodeMessage, MessageDecoder } from './protocol.js';
7
+ import type { IpcRouter } from './router.js';
8
+
9
+ export class IpcServer {
10
+ private server: net.Server | null = null;
11
+ private clients = new Map<string, net.Socket>();
12
+ private logger = getLogger();
13
+
14
+ constructor(
15
+ private router: IpcRouter,
16
+ private pipeName: string,
17
+ ) {}
18
+
19
+ start(): void {
20
+ this.createServer();
21
+ this.listen();
22
+ }
23
+
24
+ private createServer(): void {
25
+ this.server = net.createServer((socket) => {
26
+ const clientId = randomUUID();
27
+ this.clients.set(clientId, socket);
28
+ const decoder = new MessageDecoder();
29
+
30
+ this.logger.info(`IPC client connected: ${clientId}`);
31
+
32
+ socket.on('data', (chunk) => {
33
+ const messages = decoder.feed(chunk);
34
+ for (const msg of messages) {
35
+ this.handleMessage(clientId, msg, socket);
36
+ }
37
+ });
38
+
39
+ socket.on('close', () => {
40
+ this.logger.info(`IPC client disconnected: ${clientId}`);
41
+ this.clients.delete(clientId);
42
+ });
43
+
44
+ socket.on('error', (err) => {
45
+ this.logger.error(`IPC client ${clientId} error:`, err);
46
+ this.clients.delete(clientId);
47
+ });
48
+ });
49
+ }
50
+
51
+ private listen(retried = false): void {
52
+ if (!this.server) return;
53
+
54
+ this.server.on('error', (err: NodeJS.ErrnoException) => {
55
+ if (err.code === 'EADDRINUSE' && !retried) {
56
+ this.logger.warn(`IPC pipe in use, attempting to recover stale pipe: ${this.pipeName}`);
57
+ this.recoverStalePipe();
58
+ } else {
59
+ this.logger.error('IPC server error:', err);
60
+ }
61
+ });
62
+
63
+ this.server.listen(this.pipeName, () => {
64
+ this.logger.info(`IPC server listening on ${this.pipeName}`);
65
+ });
66
+ }
67
+
68
+ private recoverStalePipe(): void {
69
+ const probe = net.createConnection(this.pipeName);
70
+
71
+ probe.on('connect', () => {
72
+ probe.destroy();
73
+ this.logger.error('IPC pipe is held by another running daemon. Stop it first with: trading stop');
74
+ });
75
+
76
+ probe.on('error', () => {
77
+ probe.destroy();
78
+ this.logger.info('Stale IPC pipe detected, reclaiming...');
79
+
80
+ if (process.platform !== 'win32') {
81
+ try { fs.unlinkSync(this.pipeName); } catch { /* ignore */ }
82
+ }
83
+
84
+ this.createServer();
85
+ this.server!.on('error', (err) => {
86
+ this.logger.error('IPC server error after recovery:', err);
87
+ });
88
+ this.server!.listen(this.pipeName, () => {
89
+ this.logger.info(`IPC server recovered and listening on ${this.pipeName}`);
90
+ });
91
+ });
92
+
93
+ probe.setTimeout(2000, () => {
94
+ probe.destroy();
95
+ this.logger.warn('IPC pipe probe timed out, treating as stale');
96
+ if (process.platform !== 'win32') {
97
+ try { fs.unlinkSync(this.pipeName); } catch { /* ignore */ }
98
+ }
99
+ this.createServer();
100
+ this.server!.on('error', (err) => {
101
+ this.logger.error('IPC server error after timeout recovery:', err);
102
+ });
103
+ this.server!.listen(this.pipeName, () => {
104
+ this.logger.info(`IPC server recovered (timeout) and listening on ${this.pipeName}`);
105
+ });
106
+ });
107
+ }
108
+
109
+ private handleMessage(clientId: string, msg: IpcMessage, socket: net.Socket): void {
110
+ if (msg.type !== 'request' || !msg.method) return;
111
+
112
+ try {
113
+ const result = this.router.handle(msg.method, msg.params);
114
+ const response: IpcMessage = { id: msg.id, type: 'response', result };
115
+ socket.write(encodeMessage(response));
116
+ } catch (err) {
117
+ const response: IpcMessage = {
118
+ id: msg.id, type: 'response',
119
+ error: { code: -1, message: err instanceof Error ? err.message : String(err) },
120
+ };
121
+ socket.write(encodeMessage(response));
122
+ }
123
+ }
124
+
125
+ notify(clientId: string | null, notification: Omit<IpcMessage, 'id' | 'type'>): void {
126
+ const msg: IpcMessage = { id: randomUUID(), type: 'notification', ...notification };
127
+ const encoded = encodeMessage(msg);
128
+
129
+ if (clientId) {
130
+ const socket = this.clients.get(clientId);
131
+ if (socket && !socket.destroyed) socket.write(encoded);
132
+ } else {
133
+ for (const socket of this.clients.values()) {
134
+ if (!socket.destroyed) socket.write(encoded);
135
+ }
136
+ }
137
+ }
138
+
139
+ getClientCount(): number {
140
+ return this.clients.size;
141
+ }
142
+
143
+ stop(): void {
144
+ for (const socket of this.clients.values()) socket.destroy();
145
+ this.clients.clear();
146
+ this.server?.close();
147
+ this.server = null;
148
+ this.logger.info('IPC server stopped');
149
+ }
150
+ }