Repository navigation
Expand file tree
/
Copy pathmcp-server.js
More file actions
executable file
·2283 lines (2143 loc) · 79.6 KB
/
Copy pathmcp-server.js
File metadata and controls
executable file
·2283 lines (2143 loc) · 79.6 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { dataDir } from './mcp-env.js';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { generateNewsSummary } from './news-summary.js';
import axios from 'axios';
import fs from 'fs/promises';
import path from 'path';
import { storeTrade, findSimilarTrades, getTradeStats, getEmbeddingCount } from './vectorDB.js';
import { ORDER_TOOLS, checkPermissions } from './permissions.js';
// Configuration
const TRADING_BOT_URL = process.env.TRADING_BOT_URL || 'http://127.0.0.1:4534';
const TRADING_BOT_TOKEN = process.env.TRADING_BOT_TOKEN || '';
const OPENPROPHET_ACCOUNT_ID = process.env.OPENPROPHET_ACCOUNT_ID || 'default';
const OPENPROPHET_SANDBOX_ID = process.env.OPENPROPHET_SANDBOX_ID || `sbx_${OPENPROPHET_ACCOUNT_ID}`;
const SANDBOX_DATA_DIR = path.join(dataDir, 'sandboxes', OPENPROPHET_ACCOUNT_ID);
const SUMMARIES_DIR = path.join(SANDBOX_DATA_DIR, 'news_summaries');
const DECISIONS_DIR = path.join(SANDBOX_DATA_DIR, 'decisive_actions');
// Ensure directories exist
await fs.mkdir(SUMMARIES_DIR, { recursive: true });
await fs.mkdir(DECISIONS_DIR, { recursive: true });
// Helper to call trading bot API - resolves correct port per sandbox
async function getTradingBotUrl() {
try {
const resp = await agentAxios.get(`${AGENT_URL}/api/health`, { timeout: 3000 });
const sandboxes = resp.data.sandboxes || [];
const sandbox = sandboxes.find(s => s.sandboxId === OPENPROPHET_SANDBOX_ID);
if (sandbox && sandbox.port) {
return `http://127.0.0.1:${sandbox.port}`;
}
} catch {}
return TRADING_BOT_URL;
}
let _tradingBotUrl = TRADING_BOT_URL;
let _lastPortCheck = 0;
async function callTradingBot(endpoint, method = 'GET', data = null) {
try {
// Refresh port every 30 seconds
const now = Date.now();
if (now - _lastPortCheck > 30000) {
_tradingBotUrl = await getTradingBotUrl();
_lastPortCheck = now;
}
const config = {
method,
url: `${_tradingBotUrl}/api/v1${endpoint}`,
headers: { 'Content-Type': 'application/json' },
};
if (TRADING_BOT_TOKEN) {
config.headers.Authorization = `Bearer ${TRADING_BOT_TOKEN}`;
}
if (data) {
config.data = data;
}
const response = await axios(config);
return response.data;
} catch (error) {
throw new Error(`Trading bot error: ${error.message}`);
}
}
async function autoStoreSetup(args, action) {
if (typeof args.thesis !== 'string' || !args.thesis.trim()) return;
try {
const now = new Date();
const dateStr = now.toISOString().split('T')[0];
const id = `${dateStr}-${args.symbol}-${action}-${now.getTime()}`;
const trade = {
id,
decision_file: `manual_${id}.json`,
symbol: args.symbol,
action,
strategy: args.strategy || 'auto',
result_pct: null,
result_dollars: null,
date: dateStr,
reasoning: args.thesis,
market_context: args.market_context || '',
};
await storeTrade(trade);
} catch (error) {
console.error('Failed to auto-store trade setup:', error.message);
}
}
// Only OPENING trades should seed the entry-recall corpus; closing/exit orders would
// pollute find_similar_setups (used as pre-entry research). Options carry an explicit intent;
// default to opening when unknown.
function isOpeningIntent(positionIntent) {
if (typeof positionIntent !== 'string' || !positionIntent) return true;
return positionIntent.includes('open');
}
// Build an order tool response, nudging the agent if no thesis was captured to memory.
function orderResponse(data, args) {
let text = JSON.stringify(data, null, 2);
if (typeof args.thesis !== 'string' || !args.thesis.trim()) {
text += '\n\n⚠ No `thesis` provided — this trade was NOT captured to your trade-memory. Pass a `thesis` next time so find_similar_setups can recall it.';
}
return { content: [{ type: 'text', text }] };
}
// Create MCP server
const server = new Server(
{
name: 'openprophet',
version: '1.0.0',
},
{
capabilities: {
tools: {},
},
}
);
// List available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'get_account',
description: 'Get trading account information including cash, buying power, and portfolio value',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'get_positions',
description: 'Get all open positions in the trading account',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'get_orders',
description: 'Get all orders (open, filled, cancelled)',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'place_buy_order',
description: 'Place a buy order for a stock or option',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Stock symbol (e.g., AAPL, TSLA)',
},
quantity: {
type: 'number',
description: 'Number of shares to buy',
},
order_type: {
type: 'string',
description: 'Order type (market, limit)',
enum: ['market', 'limit'],
},
limit_price: {
type: 'number',
description: 'Limit price (required for limit orders)',
},
thesis: {
type: 'string',
description: 'Your one-paragraph rationale for this trade — captured to the trade-memory for future recall.',
},
strategy: {
type: 'string',
description: 'Trading strategy for this setup',
},
market_context: {
type: 'string',
description: 'Relevant market context for this setup',
},
},
required: ['symbol', 'quantity', 'order_type'],
},
},
{
name: 'place_sell_order',
description: 'Place a sell order for a stock or option',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Stock symbol (e.g., AAPL, TSLA)',
},
quantity: {
type: 'number',
description: 'Number of shares to sell',
},
order_type: {
type: 'string',
description: 'Order type (market, limit)',
enum: ['market', 'limit'],
},
limit_price: {
type: 'number',
description: 'Limit price (required for limit orders)',
},
thesis: {
type: 'string',
description: 'Your one-paragraph rationale for this trade — captured to the trade-memory for future recall.',
},
strategy: {
type: 'string',
description: 'Trading strategy for this setup',
},
market_context: {
type: 'string',
description: 'Relevant market context for this setup',
},
},
required: ['symbol', 'quantity', 'order_type'],
},
},
{
name: 'place_managed_position',
description: 'Open a managed position with automatic stop loss, take profit, and optional partial exits. Perfect for active swing trading.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Stock symbol (e.g., BE, NXT, GOOGL)',
},
side: {
type: 'string',
description: 'Position side',
enum: ['buy', 'sell'],
},
strategy: {
type: 'string',
description: 'Trading strategy type',
enum: ['SWING_TRADE', 'LONG_TERM', 'DAY_TRADE'],
},
allocation_dollars: {
type: 'number',
description: 'Dollar amount to allocate to this position',
},
entry_strategy: {
type: 'string',
description: 'Entry order type',
enum: ['market', 'limit'],
},
entry_price: {
type: 'number',
description: 'Entry price (required for limit orders)',
},
stop_loss_percent: {
type: 'number',
description: 'Stop loss as % from entry (e.g., 15 for -15%)',
},
stop_loss_price: {
type: 'number',
description: 'Absolute stop loss price',
},
take_profit_percent: {
type: 'number',
description: 'Take profit as % from entry (e.g., 25 for +25%)',
},
take_profit_price: {
type: 'number',
description: 'Absolute take profit price',
},
trailing_stop: {
type: 'boolean',
description: 'Enable trailing stop loss',
},
trailing_percent: {
type: 'number',
description: 'Trailing stop percentage',
},
partial_exit: {
type: 'object',
description: 'Partial profit taking configuration',
properties: {
enabled: {
type: 'boolean',
description: 'Enable partial exits',
},
percent: {
type: 'number',
description: 'Percentage of position to exit (e.g., 50 for 50%)',
},
target_percent: {
type: 'number',
description: 'Profit % to trigger partial exit (e.g., 20 for +20%)',
},
},
},
notes: {
type: 'string',
description: 'Notes about this position',
},
tags: {
type: 'array',
description: 'Tags for categorization',
items: {
type: 'string',
},
},
thesis: {
type: 'string',
description: 'Your one-paragraph rationale for this trade — captured to the trade-memory for future recall.',
},
market_context: {
type: 'string',
description: 'Relevant market context for this setup',
},
},
required: ['symbol', 'side', 'allocation_dollars'],
},
},
{
name: 'get_managed_positions',
description: 'List managed positions with optional status filter. By default, returns only ACTIVE positions for token efficiency. Use status="" or status="ALL" to get all positions.',
inputSchema: {
type: 'object',
properties: {
status: {
type: 'string',
description: 'Filter by status. Leave empty or use "ALL" for all positions. Use PENDING, ACTIVE, PARTIAL, CLOSED, or STOPPED_OUT for specific statuses. Defaults to ACTIVE only.',
enum: ['PENDING', 'ACTIVE', 'PARTIAL', 'CLOSED', 'STOPPED_OUT', 'ALL', ''],
},
},
},
},
{
name: 'get_managed_position',
description: 'Get details of a specific managed position by ID',
inputSchema: {
type: 'object',
properties: {
position_id: {
type: 'string',
description: 'Position ID',
},
},
required: ['position_id'],
},
},
{
name: 'close_managed_position',
description: 'Manually close a managed position (cancels all orders and exits at market)',
inputSchema: {
type: 'object',
properties: {
position_id: {
type: 'string',
description: 'Position ID to close',
},
},
required: ['position_id'],
},
},
{
name: 'cancel_order',
description: 'Cancel an open order by ID',
inputSchema: {
type: 'object',
properties: {
order_id: {
type: 'string',
description: 'Order ID to cancel',
},
},
required: ['order_id'],
},
},
{
name: 'get_quote',
description: 'Get real-time quote data (bid/ask prices) for a stock symbol',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Stock symbol (e.g., AAPL, GOOGL, TSLA)',
},
},
required: ['symbol'],
},
},
{
name: 'get_latest_bar',
description: 'Get the latest price bar (OHLCV data) for a stock symbol',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Stock symbol (e.g., AAPL, GOOGL, TSLA)',
},
},
required: ['symbol'],
},
},
{
name: 'get_historical_bars',
description: 'Get historical price bars for technical analysis. Returns OHLCV data for the specified date range and timeframe.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Stock symbol (e.g., AAPL, GOOGL, TSLA)',
},
start_date: {
type: 'string',
description: 'Start date in YYYY-MM-DD format (default: 30 days ago)',
},
end_date: {
type: 'string',
description: 'End date in YYYY-MM-DD format (default: today)',
},
timeframe: {
type: 'string',
description: 'Bar timeframe: 1Min, 5Min, 15Min, 1Hour, 1Day (default: 1Day)',
enum: ['1Min', '5Min', '15Min', '1Hour', '1Day'],
},
},
required: ['symbol'],
},
},
{
name: 'get_news',
description: 'Get latest news from Google News RSS feed',
inputSchema: {
type: 'object',
properties: {
limit: {
type: 'number',
description: 'Number of news items to return (default: 20)',
},
},
},
},
{
name: 'get_news_by_topic',
description: 'Get news for a specific topic (WORLD, NATION, BUSINESS, TECHNOLOGY, ENTERTAINMENT, SPORTS, SCIENCE, HEALTH)',
inputSchema: {
type: 'object',
properties: {
topic: {
type: 'string',
description: 'News topic',
enum: ['WORLD', 'NATION', 'BUSINESS', 'TECHNOLOGY', 'ENTERTAINMENT', 'SPORTS', 'SCIENCE', 'HEALTH'],
},
},
required: ['topic'],
},
},
{
name: 'search_news',
description: 'Search for news by keyword or stock symbol',
inputSchema: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'Search query (e.g., Tesla, NVDA, Federal Reserve)',
},
limit: {
type: 'number',
description: 'Number of results (default: 20)',
},
},
required: ['query'],
},
},
{
name: 'get_market_news',
description: 'Get market news, optionally filtered by stock symbols',
inputSchema: {
type: 'object',
properties: {
symbols: {
type: 'string',
description: 'Comma-separated stock symbols (e.g., TSLA,NVDA,AAPL)',
},
},
},
},
{
name: 'aggregate_and_summarize_news',
description: 'Aggregate news from multiple sources and create an AI-powered summary using Gemini. Saves summary to a file.',
inputSchema: {
type: 'object',
properties: {
topics: {
type: 'array',
items: { type: 'string' },
description: 'News topics to aggregate (BUSINESS, TECHNOLOGY, etc.)',
},
symbols: {
type: 'array',
items: { type: 'string' },
description: 'Stock symbols to search for (e.g., ["TSLA", "NVDA"])',
},
max_articles: {
type: 'number',
description: 'Maximum articles per source (default: 10)',
},
},
},
},
{
name: 'list_news_summaries',
description: 'List all saved news summaries',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'get_news_summary',
description: 'Get a specific news summary by filename',
inputSchema: {
type: 'object',
properties: {
filename: {
type: 'string',
description: 'Summary filename',
},
},
required: ['filename'],
},
},
{
name: 'get_marketwatch_topstories',
description: 'Get MarketWatch top stories',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'get_marketwatch_realtime',
description: 'Get MarketWatch real-time headlines',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'get_marketwatch_bulletins',
description: 'Get MarketWatch breaking news bulletins',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'get_marketwatch_marketpulse',
description: 'Get MarketWatch market pulse (brief up-to-the-minute market updates)',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'get_marketwatch_all',
description: 'Get all MarketWatch news feeds aggregated',
inputSchema: {
type: 'object',
properties: {},
},
},
// ── Economic Intelligence Feeds (free, no API key) ──────────────────
{
name: 'get_treasury_data',
description: 'Get US Treasury data: national debt levels and average interest rates on government securities. No API key required. Updated daily.',
inputSchema: { type: 'object', properties: {} },
},
{
name: 'get_global_events',
description: 'Get global news events from GDELT (Global Database of Events, Language, and Tone). Searches 100+ languages, updates every 15 minutes. No API key required.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'Search query (e.g., "tariff china", "federal reserve"). Leave empty for broad market coverage.' },
},
},
},
{
name: 'get_economic_indicators',
description: 'Get key economic indicators from BLS: CPI, Core CPI, Unemployment Rate, Nonfarm Payrolls, PPI. No API key required.',
inputSchema: { type: 'object', properties: {} },
},
{
name: 'get_market_snapshot',
description: 'Get broad market snapshot from Yahoo Finance: indexes (SPY, QQQ, DIA, IWM), bonds, commodities (Gold, Oil), crypto (BTC, ETH), VIX. Includes 5-day history. No API key required.',
inputSchema: { type: 'object', properties: {} },
},
{
name: 'get_defense_contracts',
description: 'Get recent US defense/military contracts from USAspending.gov. Useful for defense sector signals. No API key required.',
inputSchema: { type: 'object', properties: {} },
},
{
name: 'get_global_trade_flows',
description: 'Get global trade flow data from UN Comtrade for strategic commodities: crude, gas, gold, semiconductors. No API key required. Data lags 1-2 months.',
inputSchema: { type: 'object', properties: {} },
},
{
name: 'get_quick_market_intelligence',
description: 'Get AI-powered quick market intelligence (Gemini-cleaned news from MarketWatch - 15 articles max, very fast)',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'analyze_stocks',
description: 'Analyze multiple stocks with comprehensive technical indicators, news, and AI-powered recommendations. Returns RSI, trend, volatility, support/resistance, catalysts, and trade recommendations for each stock.',
inputSchema: {
type: 'object',
properties: {
symbols: {
type: 'array',
items: { type: 'string' },
description: 'Array of stock symbols to analyze (e.g., ["CLRB", "PLUG", "BE", "NVDA"])',
},
},
required: ['symbols'],
},
},
{
name: 'get_cleaned_news',
description: 'Get AI-powered cleaned and aggregated news from multiple sources (Google News + MarketWatch)',
inputSchema: {
type: 'object',
properties: {
include_google: {
type: 'boolean',
description: 'Include Google News feeds',
},
include_marketwatch: {
type: 'boolean',
description: 'Include MarketWatch feeds',
},
google_topics: {
type: 'array',
items: { type: 'string' },
description: 'Google News topics to include (BUSINESS, TECHNOLOGY, etc.)',
},
symbols: {
type: 'array',
items: { type: 'string' },
description: 'Stock symbols to search for',
},
max_articles_per_source: {
type: 'number',
description: 'Maximum articles per source (default 10)',
},
},
},
},
{
name: 'log_decision',
description: 'Log a trading decision with reasoning to decisive_actions/ folder',
inputSchema: {
type: 'object',
properties: {
action: {
type: 'string',
description: 'The action taken (BUY, SELL, HOLD, PASS)',
},
symbol: {
type: 'string',
description: 'Stock symbol (optional)',
},
reasoning: {
type: 'string',
description: 'Detailed reasoning for the decision',
},
market_data: {
type: 'object',
description: 'Relevant market data that influenced the decision',
},
},
required: ['action', 'reasoning'],
},
},
{
name: 'log_activity',
description: 'Log AI trading activity to the daily activity log (positions, intelligence, decisions)',
inputSchema: {
type: 'object',
properties: {
type: {
type: 'string',
description: 'Activity type: ANALYSIS, INTELLIGENCE, DECISION, POSITION_CHECK',
},
action: {
type: 'string',
description: 'Action description (e.g., "Analyzed 10 stocks", "Gathered market intelligence")',
},
symbol: {
type: 'string',
description: 'Stock symbol if applicable',
},
reasoning: {
type: 'string',
description: 'Reasoning or notes for this activity',
},
details: {
type: 'object',
description: 'Additional details as key-value pairs',
},
},
required: ['type', 'action'],
},
},
{
name: 'get_activity_log',
description: 'Get the current day\'s activity log showing all AI trading activities',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'place_options_order',
description: 'Place an options order (calls or puts)',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Options symbol in OCC format (e.g., TSLA251219C00400000 for TSLA Dec 19 2025 $400 Call)',
},
underlying: {
type: 'string',
description: 'Underlying stock symbol (e.g., TSLA)',
},
quantity: {
type: 'number',
description: 'Number of contracts to trade',
},
side: {
type: 'string',
description: 'Order side',
enum: ['buy', 'sell'],
},
position_intent: {
type: 'string',
description: 'Position intent (optional, defaults based on side)',
enum: ['buy_to_open', 'buy_to_close', 'sell_to_open', 'sell_to_close'],
},
order_type: {
type: 'string',
description: 'Order type',
enum: ['market', 'limit'],
},
limit_price: {
type: 'number',
description: 'Limit price per contract (required for limit orders)',
},
thesis: {
type: 'string',
description: 'Your one-paragraph rationale for this trade — captured to the trade-memory for future recall.',
},
strategy: {
type: 'string',
description: 'Trading strategy for this setup',
},
market_context: {
type: 'string',
description: 'Relevant market context for this setup',
},
},
required: ['symbol', 'quantity', 'side', 'order_type'],
},
},
{
name: 'get_options_positions',
description: 'Get all open options positions',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'get_options_position',
description: 'Get a specific options position by symbol',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Options symbol in OCC format',
},
},
required: ['symbol'],
},
},
{
name: 'get_options_chain',
description: 'Get available options contracts for an underlying symbol with optional filtering. Use filters to reduce token usage. Use this to find valid option symbols before placing orders.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Underlying stock symbol (e.g., SPY, TSLA, AAPL)',
},
expiration: {
type: 'string',
description: 'Expiration date in YYYY-MM-DD format (optional, defaults to next Friday)',
},
delta_min: {
type: 'number',
description: 'Minimum delta (absolute value, e.g., 0.4 for ATM options)',
},
delta_max: {
type: 'number',
description: 'Maximum delta (absolute value, e.g., 0.6 for ATM options)',
},
min_bid: {
type: 'number',
description: 'Minimum bid price to filter out illiquid options (e.g., 0.1)',
},
type: {
type: 'string',
description: 'Filter by option type: "call" or "put"',
enum: ['call', 'put'],
},
},
required: ['symbol'],
},
},
{
name: 'wait',
description: 'Wait for a specified duration in seconds. Useful for AI to pause between trading actions without blocking the user. Maximum 300 seconds (5 minutes).',
inputSchema: {
type: 'object',
properties: {
seconds: {
type: 'number',
description: 'Number of seconds to wait (1-300)',
},
reason: {
type: 'string',
description: 'Optional reason for waiting (e.g., "Monitoring position momentum")',
},
},
required: ['seconds'],
},
},
{
name: 'get_datetime',
description: 'Get the current date and time in a specified timezone. Defaults to America/New_York (US Eastern). Returns time, date, day of week, market status, and whether markets are likely open.',
inputSchema: {
type: 'object',
properties: {
timezone: {
type: 'string',
description: 'IANA timezone (e.g., "America/New_York", "America/Los_Angeles", "UTC"). Defaults to America/New_York.',
},
},
},
},
{
name: 'find_similar_setups',
description: 'Find historically similar trading setups using AI vector similarity search. Query with natural language (e.g., "SPY gap up scalp") to find past trades with similar setups, reasoning, and market context. Returns similar trades with results, reasoning, and similarity scores.',
inputSchema: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'Natural language query describing the setup (e.g., "SPY gap up momentum scalp", "NVDA earnings breakout swing")',
},
limit: {
type: 'number',
description: 'Number of similar trades to return (default: 5)',
},
symbol: {
type: 'string',
description: 'Optional: Filter by symbol (e.g., "SPY", "NVDA")',
},
strategy: {
type: 'string',
description: 'Optional: Filter by strategy ("SCALP", "SWING", "HOLD")',
},
action: {
type: 'string',
description: 'Optional: Filter by action (e.g., "BUY", "SELL")',
},
},
required: ['query'],
},
},
{
name: 'store_trade_setup',
description: 'Store a completed trade with AI embeddings for future similarity search. Use this after closing a trade to add it to the historical database with reasoning and market context.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Stock symbol (e.g., "SPY", "NVDA")',
},
action: {
type: 'string',
description: 'Trade action (e.g., "BUY", "SELL", "HOLD")',
},
strategy: {
type: 'string',
description: 'Strategy type ("SCALP", "SWING", "HOLD")',
},
result_pct: {
type: 'number',
description: 'Result percentage (e.g., 26.5 for +26.5%, -15.6 for -15.6%)',
},
result_dollars: {
type: 'number',
description: 'Result in dollars (e.g., 1920 for +$1920, -960 for -$960)',
},
reasoning: {
type: 'string',
description: 'Detailed trade reasoning and thesis',
},
market_context: {
type: 'string',
description: 'Market conditions, catalysts, and context',
},
},
required: ['symbol', 'action', 'strategy', 'reasoning', 'market_context'],
},
},
{
name: 'get_trade_stats',
description: 'Get statistics for trades matching filters (win rate, profit factor, avg result, best/worst). Useful for analyzing performance by symbol, strategy, or action.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Optional: Filter by symbol (e.g., "SPY")',
},
strategy: {
type: 'string',
description: 'Optional: Filter by strategy ("SCALP", "SWING")',
},
action: {
type: 'string',
description: 'Optional: Filter by action (e.g., "BUY")',
},
},
},
},
// ── Agent Self-Modification Tools ──────────────────────────
{
name: 'update_agent_prompt',
description: 'Update the active agent\'s custom system prompt. Use this when the user asks you to change your trading behavior, persona, or rules. The new prompt replaces the existing custom prompt.',
inputSchema: {
type: 'object',
properties: {
prompt: {
type: 'string',
description: 'The new system prompt text',
},
},
required: ['prompt'],
},
},
{
name: 'update_strategy_rules',
description: 'Create a new trading strategy with the given rules and assign it to the current agent. Existing strategies are NEVER modified — a new one is always created so the operator can review it on the Agents page. ONLY use this when the user EXPLICITLY asks you to change trading rules.',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Name for the new strategy (e.g., "Conservative Options v2")' },
rules: { type: 'string', description: 'The trading rules in markdown format' },
},
required: ['name', 'rules'],
},
},
{
name: 'get_agent_config',
description: 'Get the current agent configuration including active agent, strategy, model, heartbeat settings, and permissions. Useful for understanding your current setup before making changes.',