Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

polymarkets update

tilakpatel223df7067ca419
diff --git a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy1.txt b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy1.txt
index 058d567ee..5b0c0074c 100644
--- a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy1.txt
+++ b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy1.txt
@@ -13,6 +13,12 @@ exchange-calendars>=4.0
bt>=1.1.2
ffn>=1.1.2
+# peewee is a transitive dependency of zipline-reloaded (via empyrical-reloaded)
+# Pin it explicitly so UV can resolve it early; the PEEWEE_NO_SQLITE_EXTENSIONS=1
+# env var set during install prevents the C extension build that fails on
+# embedded Python (missing sqlite3.h header).
+peewee>=3.17.0
+
# Time series and forecasting (NumPy 1.x dependent)
gluonts[torch]==0.16.2
functime==0.1.10
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
index f6687569f..a8e557780 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
@@ -510,12 +510,21 @@ class CoreAgent:
# =================================================================
model_config = config.get("model", {})
provider = model_config.get("provider") or self._resolve_model_config()["provider"]
+
+ # Pass any extra model-level kwargs (e.g. max_tool_rounds for FinceptChat)
+ extra_model_kwargs = {
+ k: v for k, v in model_config.items()
+ if k not in {"provider", "model_id", "temperature", "max_tokens"}
+ and v is not None
+ }
+
model = ModelsRegistry.create_model(
provider=provider,
model_id=model_config.get("model_id"),
api_keys=self.api_keys,
temperature=model_config.get("temperature"),
max_tokens=model_config.get("max_tokens"),
+ **extra_model_kwargs,
)
agent_kwargs = {"model": model}
diff --git a/fincept-terminal-desktop/src-tauri/src/setup/install.rs b/fincept-terminal-desktop/src-tauri/src/setup/install.rs
index d8b527a18..2283edd3a 100644
--- a/fincept-terminal-desktop/src-tauri/src/setup/install.rs
+++ b/fincept-terminal-desktop/src-tauri/src/setup/install.rs
@@ -618,6 +618,11 @@ pub(super) async fn install_packages_in_venv(
cmd
};
+ // Set environment variables to prevent C extension build failures
+ // on embedded Python which lacks development headers (sqlite3.h, etc.)
+ cmd.env("PEEWEE_NO_SQLITE_EXTENSIONS", "1");
+ cmd.env("PEEWEE_NO_C_EXTENSION", "1");
+
let venv_python_str = venv_python.to_str().ok_or_else(|| format!("Invalid venv python path encoding: {:?}", venv_python))?;
let requirements_path_str = requirements_path.to_str().ok_or_else(|| format!("Invalid requirements path encoding: {:?}", requirements_path))?;
cmd.args(&[
diff --git a/fincept-terminal-desktop/src/components/tabs/polymarket/BotDeployView.tsx b/fincept-terminal-desktop/src/components/tabs/polymarket/BotDeployView.tsx
index 01b4cf685..e2b6ec0c9 100644
--- a/fincept-terminal-desktop/src/components/tabs/polymarket/BotDeployView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/polymarket/BotDeployView.tsx
@@ -9,9 +9,9 @@ import {
polymarketBotService,
BotStrategy, RiskConfig, BotLLMConfig,
DEFAULT_STRATEGY, DEFAULT_RISK_CONFIG, DEFAULT_LLM_CONFIG,
- StrategyType,
+ StrategyType, EventMode,
} from '@/services/polymarket/polymarketBotService';
-import { getLLMConfigs } from '@/services/core/sqliteService';
+import { getLLMConfigs, type LLMConfig } from '@/services/core/sqliteService';
// ─── Constants ────────────────────────────────────────────────────────────────
@@ -90,23 +90,36 @@ const BotDeployView: React.FC<Props> = ({ onDeployed }) => {
const [strategy, setStrategy] = useState<BotStrategy>({ ...DEFAULT_STRATEGY });
const [riskConfig, setRiskConfig] = useState<RiskConfig>({ ...DEFAULT_RISK_CONFIG });
const [llmConfig, setLlmConfig] = useState<BotLLMConfig>({ ...DEFAULT_LLM_CONFIG });
- const [llmProviders, setLlmProviders] = useState<Array<{ provider: string; model: string }>>([]);
+ // Each entry = one configured provider with its default model
+ const [llmProviders, setLlmProviders] = useState<LLMConfig[]>([]);
const [deploying, setDeploying] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
getLLMConfigs().then((configs) => {
- const providers = configs
- .filter((c) => c.api_key || c.provider === 'ollama' || c.provider === 'fincept')
- .map((c) => ({ provider: c.provider, model: c.model }));
- setLlmProviders(providers);
- if (providers.length > 0) {
- const active = configs.find((c) => c.is_active);
- if (active) setLlmConfig((prev) => ({ ...prev, provider: active.provider, modelId: active.model }));
+ // Include providers that have an API key, or special providers that don't need one
+ const usable = configs.filter(
+ (c) => c.api_key || c.provider === 'ollama' || c.provider === 'fincept',
+ );
+ setLlmProviders(usable);
+ // Pre-select the active provider if one is configured
+ const active = usable.find((c) => c.is_active) ?? usable[0];
+ if (active) {
+ setLlmConfig((prev) => ({ ...prev, provider: active.provider, modelId: active.model }));
}
}).catch(() => {});
}, []);
+ // When the user picks a different provider, auto-populate the model with that provider's default
+ const handleProviderChange = (provider: string) => {
+ const cfg = llmProviders.find((c) => c.provider === provider);
+ setLlmConfig((prev) => ({
+ ...prev,
+ provider,
+ modelId: cfg?.model ?? prev.modelId,
+ }));
+ };
+
const handleDeploy = async () => {
if (!botName.trim()) { setError('Bot name is required'); return; }
setError(null);
@@ -267,6 +280,77 @@ const BotDeployView: React.FC<Props> = ({ onDeployed }) => {
/>
</div>
</div>
+
+ {/* ── Event Targeting ─────────────────────────────────────────────── */}
+ <SectionHeader label="EVENT TARGETING" />
+ <div style={{ padding: '8px 10px' }}>
+ {/* Mode selector */}
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '3px', marginBottom: '8px' }}>
+ {([
+ { mode: 'all' as EventMode, label: 'ALL MKTS', desc: 'Flat top-N scan' },
+ { mode: 'specific' as EventMode, label: 'SPECIFIC', desc: 'Pick event slugs' },
+ { mode: 'dynamic' as EventMode, label: 'DYNAMIC', desc: 'Keyword discovery' },
+ ]).map(({ mode, label, desc }) => {
+ const active = strategy.eventMode === mode;
+ return (
+ <button
+ key={mode}
+ onClick={() => patchStrategy({ eventMode: mode })}
+ title={desc}
+ style={{
+ padding: '5px 2px', border: `1px solid ${active ? C.cyan : C.dim}`,
+ backgroundColor: active ? `${C.cyan}18` : C.panel,
+ color: active ? C.cyan : C.muted,
+ fontSize: '7px', fontWeight: 'bold', cursor: 'pointer', fontFamily: 'inherit',
+ letterSpacing: '0.04em',
+ }}
+ >
+ {label}
+ </button>
+ );
+ })}
+ </div>
+
+ {strategy.eventMode === 'all' && (
+ <div style={{ fontSize: '9px', color: C.muted, padding: '4px 6px', border: `1px solid ${C.dim}` }}>
+ Bot scans top {strategy.marketsPerScan} active markets each cycle — no event filter.
+ </div>
+ )}
+
+ {strategy.eventMode === 'specific' && (
+ <div>
+ <label style={S.label}>EVENT SLUGS (one per line)</label>
+ <textarea
+ style={{ ...S.input, height: '56px', resize: 'none' }}
+ placeholder={'e.g.\nwill-trump-win-2024\nbtc-100k-2025'}
+ value={strategy.eventSlugs.join('\n')}
+ onChange={(e) =>
+ patchStrategy({ eventSlugs: e.target.value.split('\n').map((s) => s.trim()).filter(Boolean) })
+ }
+ />
+ <div style={{ fontSize: '8px', color: C.muted, marginTop: '3px' }}>
+ Bot fetches markets from these events only. Find slugs on polymarket.com event URLs.
+ </div>
+ </div>
+ )}
+
+ {strategy.eventMode === 'dynamic' && (
+ <div>
+ <label style={S.label}>DISCOVERY KEYWORDS (comma-sep)</label>
+ <input
+ style={S.input}
+ placeholder="e.g. election, bitcoin, AI, fed rate"
+ value={strategy.eventKeywords.join(', ')}
+ onChange={(e) =>
+ patchStrategy({ eventKeywords: e.target.value.split(',').map((s) => s.trim()).filter(Boolean) })
+ }
+ />
+ <div style={{ fontSize: '8px', color: C.muted, marginTop: '3px' }}>
+ Agent searches events matching these keywords each cycle and analyses their markets.
+ </div>
+ </div>
+ )}
+ </div>
</div>
{/* ── Col 2: AI Model ──────────────────────────────────────────────── */}
@@ -276,24 +360,46 @@ const BotDeployView: React.FC<Props> = ({ onDeployed }) => {
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', marginBottom: '6px' }}>
<div>
<label style={S.label}>PROVIDER</label>
- <select style={S.select} value={llmConfig.provider} onChange={(e) => patchLLM({ provider: e.target.value })}>
+ <select
+ style={S.select}
+ value={llmConfig.provider}
+ onChange={(e) => handleProviderChange(e.target.value)}
+ >
{llmProviders.length > 0 ? (
- llmProviders.map((p) => (
- <option key={`${p.provider}:${p.model}`} value={p.provider}>{p.provider.toUpperCase()}</option>
+ llmProviders.map((c) => (
+ <option key={c.provider} value={c.provider}>
+ {c.provider.toUpperCase()}
+ </option>
))
) : (
- <option value="fincept">FINCEPT</option>
+ <option value="fincept">FINCEPT (default)</option>
)}
</select>
</div>
<div>
<label style={S.label}>MODEL ID</label>
- <input
- style={S.input}
- placeholder="e.g. gpt-4o"
- value={llmConfig.modelId}
- onChange={(e) => patchLLM({ modelId: e.target.value })}
- />
+ {/* Show a dropdown of models for the selected provider if multiple are configured,
+ otherwise allow manual entry */}
+ {llmProviders.filter((c) => c.provider === llmConfig.provider).length > 1 ? (
+ <select
+ style={S.select}
+ value={llmConfig.modelId}
+ onChange={(e) => patchLLM({ modelId: e.target.value })}
+ >
+ {llmProviders
+ .filter((c) => c.provider === llmConfig.provider)
+ .map((c) => (
+ <option key={c.model} value={c.model}>{c.model}</option>
+ ))}
+ </select>
+ ) : (
+ <input
+ style={S.input}
+ placeholder="e.g. gpt-4o"
+ value={llmConfig.modelId}
+ onChange={(e) => patchLLM({ modelId: e.target.value })}
+ />
+ )}
</div>
</div>
@@ -391,9 +497,9 @@ const BotDeployView: React.FC<Props> = ({ onDeployed }) => {
}}>
{[
{ label: 'STRATEGY', value: STRATEGY_INFO[strategy.type].label, color: STRATEGY_INFO[strategy.type].color },
- { label: 'MODEL', value: llmConfig.provider.toUpperCase(), color: C.cyan },
+ { label: 'MODEL', value: `${llmConfig.provider.toUpperCase()} / ${llmConfig.modelId}`, color: C.cyan },
{ label: 'EXPOSURE', value: `${riskConfig.maxExposureUsdc} USDC`, color: C.white },
- { label: 'INTERVAL', value: `${strategy.scanIntervalMs / 60000}m`, color: C.white },
+ { label: 'EVENTS', value: strategy.eventMode === 'specific' ? `${strategy.eventSlugs.length} SLUG${strategy.eventSlugs.length !== 1 ? 'S' : ''}` : strategy.eventMode === 'dynamic' ? `${strategy.eventKeywords.length} KWD${strategy.eventKeywords.length !== 1 ? 'S' : ''}` : 'ALL', color: C.cyan },
].map((item) => (
<div key={item.label} style={{ padding: '6px 8px', borderRight: `1px solid ${C.border}` }}>
<div style={{ fontSize: '7px', color: C.muted, letterSpacing: '0.06em', marginBottom: '2px' }}>{item.label}</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/polymarket/BotMonitorView.tsx b/fincept-terminal-desktop/src/components/tabs/polymarket/BotMonitorView.tsx
index 62139cd72..4ba319c32 100644
--- a/fincept-terminal-desktop/src/components/tabs/polymarket/BotMonitorView.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/polymarket/BotMonitorView.tsx
@@ -467,14 +467,20 @@ const BotMonitorView: React.FC<Props> = ({ onCreateNew }) => {
const loadBots = useCallback(async () => {
const list = await polymarketBotService.getBots();
setBots(list);
- if (!selectedId && list.length > 0) setSelectedId(list[0].id);
- }, [selectedId]);
+ setSelectedId((prev) => {
+ // If nothing selected yet, pick the first bot
+ if (!prev && list.length > 0) return list[0].id;
+ // If the currently selected bot no longer exists, clear selection
+ if (prev && !list.find((b) => b.id === prev)) return list[0]?.id ?? null;
+ return prev;
+ });
+ }, []);
useEffect(() => {
loadBots();
const unsub = polymarketBotService.subscribe(() => loadBots());
return unsub;
- }, []);
+ }, [loadBots]);
useEffect(() => {
if (!selectedId) { setDecisions([]); return; }
@@ -547,7 +553,18 @@ const BotMonitorView: React.FC<Props> = ({ onCreateNew }) => {
onStart={() => polymarketBotService.startBot(b.id)}
onPause={() => polymarketBotService.pauseBot(b.id)}
onStop={() => polymarketBotService.stopBot(b.id)}
- onDelete={async () => { await polymarketBotService.deleteBot(b.id); if (selectedId === b.id) setSelectedId(null); }}
+ onDelete={async () => {
+ // Optimistically remove from UI immediately so the bot disappears on click
+ setBots((prev) => {
+ const next = prev.filter((x) => x.id !== b.id);
+ // If the deleted bot was selected, move selection to the next available bot
+ if (selectedId === b.id) {
+ setSelectedId(next[0]?.id ?? null);
+ }
+ return next;
+ });
+ await polymarketBotService.deleteBot(b.id);
+ }}
/>
))}
</div>
diff --git a/fincept-terminal-desktop/src/services/agentService.ts b/fincept-terminal-desktop/src/services/agentService.ts
index ac54aeff0..166559498 100644
--- a/fincept-terminal-desktop/src/services/agentService.ts
+++ b/fincept-terminal-desktop/src/services/agentService.ts
@@ -68,12 +68,17 @@ const BLOCKED_TERMINAL_TOOLS = new Set([
/**
* Fetch internal TypeScript MCP tool definitions, filter to safe read-only tools,
* and return them ready for injection into an agent payload.
+ * If `requestedToolNames` is provided, only return tools matching those names.
*/
-async function getTerminalToolDefinitions(): Promise<AgentConfig['terminal_tools']> {
+async function getTerminalToolDefinitions(requestedToolNames?: string[]): Promise<AgentConfig['terminal_tools']> {
try {
const allTools = await mcpToolService.getAllTools();
return allTools
- .filter(t => t.serverId === INTERNAL_SERVER_ID && !BLOCKED_TERMINAL_TOOLS.has(t.name))
+ .filter(t =>
+ t.serverId === INTERNAL_SERVER_ID &&
+ !BLOCKED_TERMINAL_TOOLS.has(t.name) &&
+ (!requestedToolNames || requestedToolNames.includes(t.name))
+ )
.map(t => ({
name: t.name,
description: t.description || `Terminal tool: ${t.name}`,
@@ -87,16 +92,24 @@ async function getTerminalToolDefinitions(): Promise<AgentConfig['terminal_tools
/**
* Execute a CoreAgent action with the given payload.
* Automatically injects internal TypeScript MCP tool definitions if the action is 'run'.
+ *
+ * For Fincept provider (which has a ~50KB payload limit) we skip the full tool list,
+ * but still inject tools when the agent explicitly requests specific ones — those are
+ * small enough to stay well under the limit.
*/
async function execute<T = any>(payload: AgentPayload): Promise<AgentResponse<T>> {
try {
- // Inject terminal tool schemas for 'run' actions so Python can use TypeScript tools.
- // Skip for Fincept provider — its endpoint has a ~50KB payload limit and terminal tools
- // are not needed there (the Portfolio Analyst agent uses its own built-in MCP tools).
if (payload.action === 'run' && payload.config) {
const provider = payload.config.model?.provider?.toLowerCase() ?? '';
const isFincept = provider === 'fincept' || provider === 'fincept-llm';
+ // Requested tool names from the agent config (e.g. polymarket bot tools)
+ const requestedTools: string[] | undefined =
+ Array.isArray(payload.config.tools) && payload.config.tools.length > 0
+ ? payload.config.tools
+ : undefined;
+
if (!isFincept) {
+ // Non-Fincept: inject the full terminal tool set
const terminalTools = await getTerminalToolDefinitions();
if (terminalTools && terminalTools.length > 0) {
payload = {
@@ -104,6 +117,15 @@ async function execute<T = any>(payload: AgentPayload): Promise<AgentResponse<T>
config: { ...payload.config, terminal_tools: terminalTools },
};
}
+ } else if (requestedTools) {
+ // Fincept with specific tool requests: inject only those tools to stay under payload limit
+ const terminalTools = await getTerminalToolDefinitions(requestedTools);
+ if (terminalTools && terminalTools.length > 0) {
+ payload = {
+ ...payload,
+ config: { ...payload.config, terminal_tools: terminalTools },
+ };
+ }
}
}
const result = await invoke<string>('execute_core_agent', { payload });
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/PolymarketMCPBridge.ts b/fincept-terminal-desktop/src/services/mcp/internal/PolymarketMCPBridge.ts
index c81c58a10..3ebfbdbee 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/PolymarketMCPBridge.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/PolymarketMCPBridge.ts
@@ -22,6 +22,7 @@ export class PolymarketMCPBridge {
closed: params.closed ?? false,
order: params.order,
ascending: params.ascending ?? false,
+ tag_id: params.tag_id,
});
},
@@ -30,13 +31,32 @@ export class PolymarketMCPBridge {
},
polymarketGetMarketDetail: async (marketId) => {
- // Fetch the market and its order book (if CLOB token IDs are available)
- const market = await polymarketApiService.getMarkets({
- limit: 1,
- // Use market_ids filter when available; fallback to full list search
- }).then((markets) =>
- markets.find((m: any) => m.id === marketId || m.conditionId === marketId)
- );
+ // Try fetching by ID query param (Gamma API supports ?id=...)
+ // Fall back to conditionId search if the first attempt returns nothing
+ let market: any = null;
+
+ const byId = await polymarketApiService.getMarkets({ limit: 1 } as any).catch(() => null);
+ // Build the URL manually since getMarkets doesn't accept arbitrary params
+ const directUrl = `https://gamma-api.polymarket.com/markets?id=${encodeURIComponent(marketId)}&limit=1`;
+ try {
+ const resp = await fetch(directUrl);
+ if (resp.ok) {
+ const data = await resp.json();
+ market = Array.isArray(data) ? data[0] : data;
+ }
+ } catch { /* fall through */ }
+
+ // Also try by conditionId if no result yet
+ if (!market) {
+ const condUrl = `https://gamma-api.polymarket.com/markets?condition_id=${encodeURIComponent(marketId)}&limit=1`;
+ try {
+ const resp = await fetch(condUrl);
+ if (resp.ok) {
+ const data = await resp.json();
+ market = Array.isArray(data) ? data[0] : data;
+ }
+ } catch { /* fall through */ }
+ }
if (!market) {
throw new Error(`Market ${marketId} not found`);
@@ -73,6 +93,7 @@ export class PolymarketMCPBridge {
limit: params.limit ?? 10,
active: params.active ?? true,
closed: params.closed ?? false,
+ tag_id: params.tag_id,
});
},
@@ -86,6 +107,40 @@ export class PolymarketMCPBridge {
limit,
});
},
+
+ // ── Extended tools ──────────────────────────────────────────────────────
+
+ polymarketGetEventBySlug: async (slug) => {
+ return polymarketApiService.getEventBySlug(slug);
+ },
+
+ polymarketGetMarketBySlug: async (slug) => {
+ return polymarketApiService.getMarketBySlug(slug);
+ },
+
+ polymarketGetTopHolders: async (conditionId, limit = 20) => {
+ return polymarketApiService.getTopHolders(conditionId, limit);
+ },
+
+ polymarketGetOpenInterest: async (conditionIds) => {
+ return polymarketApiService.getOpenInterest(conditionIds);
+ },
+
+ polymarketGetEnrichedOrderBook: async (tokenId) => {
+ return polymarketApiService.getOrderBookEnriched(tokenId);
+ },
+
+ polymarketGetMidpoint: async (tokenId) => {
+ return polymarketApiService.getMidpoint(tokenId);
+ },
+
+ polymarketGetTags: async () => {
+ return polymarketApiService.getTags();
+ },
+
+ polymarketGetBalance: async () => {
+ return polymarketApiService.getBalanceAllowance('COLLATERAL');
+ },
});
this.connected = true;
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/polymarket.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/polymarket.ts
index 2cfd901b9..e058c802a 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/polymarket.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/polymarket.ts
@@ -34,6 +34,10 @@ export const polymarketTools: InternalTool[] = [
type: 'boolean',
description: 'Sort ascending (default: false = descending)',
},
+ tag_id: {
+ type: 'string',
+ description: 'Filter by Polymarket category tag ID (use polymarket_get_tags to discover valid IDs)',
+ },
},
required: [],
},
@@ -48,6 +52,7 @@ export const polymarketTools: InternalTool[] = [
closed: args.closed ?? false,
order: args.order,
ascending: args.ascending ?? false,
+ tag_id: args.tag_id,
});
// Return simplified view for LLM consumption
const simplified = markets.slice(0, args.limit ?? 20).map((m: any) => ({
@@ -258,6 +263,10 @@ export const polymarketTools: InternalTool[] = [
type: 'boolean',
description: 'Filter to active events only (default: true)',
},
+ tag_id: {
+ type: 'string',
+ description: 'Filter events by category tag ID (use polymarket_get_tags to discover valid IDs)',
+ },
},
required: [],
},
@@ -270,6 +279,7 @@ export const polymarketTools: InternalTool[] = [
limit: args.limit ?? 10,
active: args.active ?? true,
closed: false,
+ tag_id: args.tag_id,
});
const simplified = events.slice(0, args.limit ?? 10).map((e: any) => ({
id: e.id,
@@ -340,4 +350,310 @@ export const polymarketTools: InternalTool[] = [
}
},
},
+
+ // ── Extended tools ───────────────────────────────────────────────────────────
+
+ {
+ name: 'polymarket_get_event_by_slug',
+ description:
+ 'Fetch a Polymarket event and ALL its nested markets by event slug. Returns each market\'s clobTokenIds (YES=index 0, NO=index 1) so you can immediately call order book and price history tools. Use this for event-targeted bots instead of a flat market scan.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ slug: {
+ type: 'string',
+ description: 'Event slug from the Polymarket URL, e.g. "will-trump-win-2024"',
+ },
+ },
+ required: ['slug'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.polymarketGetEventBySlug) {
+ return { success: false, error: 'Polymarket context not available' };
+ }
+ try {
+ const event = await contexts.polymarketGetEventBySlug(args.slug);
+ return {
+ success: true,
+ data: {
+ id: event.id,
+ slug: event.slug,
+ title: event.title,
+ description: event.description?.slice(0, 300),
+ startDate: event.startDate,
+ endDate: event.endDate,
+ volume: event.volume,
+ liquidity: event.liquidity,
+ markets: (event.markets ?? []).map((m: any) => ({
+ id: m.id,
+ question: m.question,
+ outcomes: m.outcomes,
+ prices: m.outcomePrices,
+ volume: m.volume,
+ liquidity: m.liquidity,
+ endDate: m.endDate,
+ acceptingOrders: m.acceptingOrders,
+ // YES token = index 0, NO token = index 1
+ yes_token_id: m.clobTokenIds?.[0] ?? null,
+ no_token_id: m.clobTokenIds?.[1] ?? null,
+ })),
+ market_count: event.markets?.length ?? 0,
+ },
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message ?? 'Failed to fetch event by slug' };
+ }
+ },
+ },
+
+ {
+ name: 'polymarket_get_market_by_slug',
+ description:
+ 'Fetch a single Polymarket market by its URL slug. Returns clobTokenIds for direct order book access.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ slug: {
+ type: 'string',
+ description: 'Market slug from the Polymarket URL',
+ },
+ },
+ required: ['slug'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.polymarketGetMarketBySlug) {
+ return { success: false, error: 'Polymarket context not available' };
+ }
+ try {
+ const m = await contexts.polymarketGetMarketBySlug(args.slug);
+ return {
+ success: true,
+ data: {
+ id: m.id,
+ slug: m.slug,
+ question: m.question,
+ outcomes: m.outcomes,
+ prices: m.outcomePrices,
+ volume: m.volume,
+ liquidity: m.liquidity,
+ endDate: m.endDate,
+ acceptingOrders: m.acceptingOrders,
+ yes_token_id: m.clobTokenIds?.[0] ?? null,
+ no_token_id: m.clobTokenIds?.[1] ?? null,
+ },
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message ?? 'Failed to fetch market by slug' };
+ }
+ },
+ },
+
+ {
+ name: 'polymarket_get_tags',
+ description:
+ 'Get all Polymarket category tags with their IDs. Use the returned tag_id values to filter polymarket_get_markets and polymarket_get_events by category (e.g. politics, crypto, sports).',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ required: [],
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.polymarketGetTags) {
+ return { success: false, error: 'Polymarket context not available' };
+ }
+ try {
+ const tags = await contexts.polymarketGetTags();
+ const simplified = tags.map((t: any) => ({
+ id: t.id,
+ label: t.label ?? t.slug ?? t.name,
+ slug: t.slug,
+ }));
+ return { success: true, data: simplified, count: simplified.length };
+ } catch (error: any) {
+ return { success: false, error: error?.message ?? 'Failed to fetch tags' };
+ }
+ },
+ },
+
+ {
+ name: 'polymarket_get_top_holders',
+ description:
+ 'Get the top token holders for a Polymarket market. Shows whale concentration — useful as a contrarian signal (high concentration = crowded trade).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ condition_id: {
+ type: 'string',
+ description: 'The market condition ID (from polymarket_get_markets or polymarket_get_market_detail)',
+ },
+ limit: {
+ type: 'number',
+ description: 'Number of top holders to return (default: 20)',
+ },
+ },
+ required: ['condition_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.polymarketGetTopHolders) {
+ return { success: false, error: 'Polymarket context not available' };
+ }
+ try {
+ const result = await contexts.polymarketGetTopHolders(args.condition_id, args.limit ?? 20);
+ const holders: any[] = result.holders ?? result ?? [];
+ // Compute concentration: top-5 share of total
+ const total = holders.reduce((s: number, h: any) => s + (parseFloat(h.size ?? h.amount ?? '0')), 0);
+ const top5 = holders.slice(0, 5).reduce((s: number, h: any) => s + (parseFloat(h.size ?? h.amount ?? '0')), 0);
+ const concentration = total > 0 ? ((top5 / total) * 100).toFixed(1) : null;
+ return {
+ success: true,
+ data: {
+ top5_concentration_pct: concentration,
+ total_holders: holders.length,
+ holders: holders.slice(0, args.limit ?? 20).map((h: any) => ({
+ address: h.proxyWallet ?? h.address,
+ size: h.size ?? h.amount,
+ outcome_index: h.outcomeIndex,
+ })),
+ },
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message ?? 'Failed to fetch top holders' };
+ }
+ },
+ },
+
+ {
+ name: 'polymarket_get_enriched_order_book',
+ description:
+ 'Get an enriched order book for a Polymarket token including tick_size, min_order_size, and last_trade_price. More useful than the basic order book for sizing orders correctly.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ token_id: {
+ type: 'string',
+ description: 'The CLOB token ID (YES or NO token)',
+ },
+ },
+ required: ['token_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.polymarketGetEnrichedOrderBook) {
+ return { success: false, error: 'Polymarket context not available' };
+ }
+ try {
+ const book = await contexts.polymarketGetEnrichedOrderBook(args.token_id);
+ const bestBid = book.bids?.[0]?.price ?? null;
+ const bestAsk = book.asks?.[0]?.price ?? null;
+ const spread = bestBid && bestAsk
+ ? (parseFloat(bestAsk) - parseFloat(bestBid)).toFixed(4)
+ : null;
+ return {
+ success: true,
+ data: {
+ token_id: book.asset_id,
+ best_bid: bestBid,
+ best_ask: bestAsk,
+ spread,
+ last_trade_price: book.last_trade_price ?? null,
+ tick_size: book.tick_size ?? null,
+ min_order_size: book.min_order_size ?? null,
+ neg_risk: book.neg_risk ?? null,
+ top_bids: book.bids?.slice(0, 5),
+ top_asks: book.asks?.slice(0, 5),
+ },
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message ?? 'Failed to fetch enriched order book' };
+ }
+ },
+ },
+
+ {
+ name: 'polymarket_get_midpoint',
+ description:
+ 'Get the midpoint price for a Polymarket token — the fair value between best bid and best ask. Faster than computing it manually from the order book.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ token_id: {
+ type: 'string',
+ description: 'The CLOB token ID (YES or NO token)',
+ },
+ },
+ required: ['token_id'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.polymarketGetMidpoint) {
+ return { success: false, error: 'Polymarket context not available' };
+ }
+ try {
+ const result = await contexts.polymarketGetMidpoint(args.token_id);
+ return {
+ success: true,
+ data: {
+ token_id: args.token_id,
+ mid: result.mid ?? result.price ?? result,
+ },
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message ?? 'Failed to fetch midpoint' };
+ }
+ },
+ },
+
+ {
+ name: 'polymarket_get_balance',
+ description:
+ 'Get the available USDC collateral balance for trading on Polymarket. Requires credentials to be configured. Use this before recommending a trade size to ensure sufficient funds.',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ required: [],
+ },
+ handler: async (_args, contexts) => {
+ if (!contexts.polymarketGetBalance) {
+ return { success: false, error: 'Polymarket context not available or credentials not set' };
+ }
+ try {
+ const result = await contexts.polymarketGetBalance();
+ return {
+ success: true,
+ data: {
+ available_usdc: result.balance,
+ allowance: result.allowance,
+ },
+ };
+ } catch (error: any) {
+ return { success: false, error: error?.message ?? 'Failed to fetch balance (credentials required)' };
+ }
+ },
+ },
+
+ {
+ name: 'polymarket_get_open_interest',
+ description:
+ 'Get open interest (total outstanding token value) for one or more Polymarket markets. High OI relative to volume indicates held positions — useful for liquidity assessment.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ condition_ids: {
+ type: 'string',
+ description: 'Comma-separated list of market condition IDs',
+ },
+ },
+ required: ['condition_ids'],
+ },
+ handler: async (args, contexts) => {
+ if (!contexts.polymarketGetOpenInterest) {
+ return { success: false, error: 'Polymarket context not available' };
+ }
+ try {
+ const ids = String(args.condition_ids).split(',').map((s: string) => s.trim()).filter(Boolean);
+ const result = await contexts.polymarketGetOpenInterest(ids);
+ return { success: true, data: result, count: result?.length ?? 0 };
+ } catch (error: any) {
+ return { success: false, error: error?.message ?? 'Failed to fetch open interest' };
+ }
+ },
+ },
];
diff --git a/fincept-terminal-desktop/src/services/mcp/internal/types.ts b/fincept-terminal-desktop/src/services/mcp/internal/types.ts
index bfc37bd68..02b3391e2 100644
--- a/fincept-terminal-desktop/src/services/mcp/internal/types.ts
+++ b/fincept-terminal-desktop/src/services/mcp/internal/types.ts
@@ -304,6 +304,7 @@ export interface TerminalContexts {
closed?: boolean;
order?: string;
ascending?: boolean;
+ tag_id?: string;
}) => Promise<any[]>;
polymarketSearch?: (query: string, type?: 'markets' | 'events' | 'all') => Promise<any>;
polymarketGetMarketDetail?: (marketId: string) => Promise<any>;
@@ -317,9 +318,19 @@ export interface TerminalContexts {
limit?: number;
active?: boolean;
closed?: boolean;
+ tag_id?: string;
}) => Promise<any[]>;
polymarketGetOpenOrders?: () => Promise<any[]>;
polymarketGetTrades?: (tokenId: string, limit?: number) => Promise<any[]>;
+ // Extended tools
+ polymarketGetEventBySlug?: (slug: string) => Promise<any>;
+ polymarketGetMarketBySlug?: (slug: string) => Promise<any>;
+ polymarketGetTopHolders?: (conditionId: string, limit?: number) => Promise<any>;
+ polymarketGetOpenInterest?: (conditionIds: string[]) => Promise<any>;
+ polymarketGetEnrichedOrderBook?: (tokenId: string) => Promise<any>;
+ polymarketGetMidpoint?: (tokenId: string) => Promise<any>;
+ polymarketGetTags?: () => Promise<any[]>;
+ polymarketGetBalance?: () => Promise<any>;
// ============================================================================
// Data Mapping
diff --git a/fincept-terminal-desktop/src/services/polymarket/polymarketBotService.ts b/fincept-terminal-desktop/src/services/polymarket/polymarketBotService.ts
index 548d15d9e..5c9540694 100644
--- a/fincept-terminal-desktop/src/services/polymarket/polymarketBotService.ts
+++ b/fincept-terminal-desktop/src/services/polymarket/polymarketBotService.ts
@@ -29,6 +29,8 @@ export type BotStatus = 'idle' | 'running' | 'paused' | 'stopped' | 'error';
export type StrategyType = 'analyst' | 'contrarian' | 'momentum' | 'arbitrage' | 'custom';
+export type EventMode = 'all' | 'specific' | 'dynamic';
+
export interface BotStrategy {
/** Broad strategy archetype */
type: StrategyType;
@@ -44,6 +46,17 @@ export interface BotStrategy {
minConfidence: number;
/** Maximum markets to scan per cycle */
marketsPerScan: number;
+ /**
+ * Event targeting mode:
+ * 'all' — scan flat list of top markets (original behaviour)
+ * 'specific' — only analyse markets belonging to the listed event slugs
+ * 'dynamic' — discover events matching eventKeywords each cycle
+ */
+ eventMode: EventMode;
+ /** Option 1 — specific Polymarket event slugs (used when eventMode='specific') */
+ eventSlugs: string[];
+ /** Option 2 — keywords for dynamic event discovery (used when eventMode='dynamic') */
+ eventKeywords: string[];
}
export interface RiskConfig {
@@ -154,6 +167,9 @@ export const DEFAULT_STRATEGY: BotStrategy = {
maxOpenPositions: 3,
minConfidence: 70,
marketsPerScan: 20,
+ eventMode: 'all',
+ eventSlugs: [],
+ eventKeywords: [],
};
export const DEFAULT_RISK_CONFIG: RiskConfig = {
@@ -190,18 +206,34 @@ function buildAgentInstructions(bot: PolymarketBot): string {
? `Focus on these market categories: ${bot.strategy.focusCategories.join(', ')}.`
: 'Scan all available market categories.';
+ const { eventMode, eventSlugs, eventKeywords } = bot.strategy;
+ let eventNote = '';
+ if (eventMode === 'specific' && eventSlugs.length > 0) {
+ eventNote = `\nEVENT TARGETING (specific): You are ONLY authorised to trade markets that belong to these Polymarket events: ${eventSlugs.map((s) => `"${s}"`).join(', ')}. Call polymarket_get_event_by_slug for each slug — the response includes yes_token_id and no_token_id for every nested market so you can call order book and price history tools directly.`;
+ } else if (eventMode === 'dynamic' && eventKeywords.length > 0) {
+ eventNote = `\nEVENT TARGETING (dynamic): At the start of each cycle, use polymarket_search_markets or polymarket_get_events to discover active events matching these topics: ${eventKeywords.map((k) => `"${k}"`).join(', ')}. Then call polymarket_get_event_by_slug for the top events to retrieve their nested markets with token IDs.`;
+ }
+
return `You are a Polymarket trading agent running in autonomous mode.
${strategyBlocks[bot.strategy.type]}
-${focusNote}
+${focusNote}${eventNote}
Your task each cycle:
-1. Use polymarket_get_markets to fetch active markets (limit ${bot.strategy.marketsPerScan}, order by volume, active: true)
-2. Recall your previous trade decisions and outcomes using recall_memories
+${eventMode === 'specific' && eventSlugs.length > 0
+ ? `1. Use polymarket_get_events or polymarket_search_markets to fetch markets for the target event slugs
+2. Recall your previous trade decisions and outcomes using recall_memories`
+ : eventMode === 'dynamic' && eventKeywords.length > 0
+ ? `1. Use polymarket_search_markets or polymarket_get_events to discover events matching the keywords
+2. Recall your previous trade decisions and outcomes using recall_memories`
+ : `1. Use polymarket_get_markets to fetch active markets (limit ${bot.strategy.marketsPerScan}, order by volume, active: true)
+2. Recall your previous trade decisions and outcomes using recall_memories`}
3. Identify markets where current price deviates from your assessed true probability by at least 5%
-4. For top 3–5 candidates: use polymarket_get_order_book to check liquidity
-5. Use polymarket_get_price_history (interval: 1w) for trend context
-6. Only recommend if confidence >= ${bot.strategy.minConfidence}
+4. For top 3–5 candidates: use polymarket_get_enriched_order_book (preferred) or polymarket_get_order_book to check liquidity, tick_size, and last_trade_price
+5. Use polymarket_get_price_history (interval: 1w) for trend context; use polymarket_get_midpoint for current fair value
+6. Optionally use polymarket_get_top_holders to check whale concentration (contrarian signal)
+7. Only recommend if confidence >= ${bot.strategy.minConfidence}
+8. Use polymarket_get_balance to verify available USDC before recommending size
Output ONLY a JSON array of trade recommendations. Each item:
{
@@ -393,11 +425,17 @@ async function syncPositionToDb(position: BotPosition): Promise<void> {
}).catch((e) => console.warn('[BotService] Position DB sync failed:', e));
}
+// ─── Global timer registry ─────────────────────────────────────────────────────
+// Stored at module scope so HMR re-instantiation of the class can still clear
+// timers that were started by a previous instance of PolymarketBotService.
+const _globalTimers: Map<string, ReturnType<typeof setInterval>> = new Map();
+
// ─── Service Class ────────────────────────────────────────────────────────────
class PolymarketBotService {
private bots: Map<string, PolymarketBot> = new Map();
- private timers: Map<string, ReturnType<typeof setInterval>> = new Map();
+ // Proxy timer access through the module-level map so HMR never orphans timers
+ private get timers() { return _globalTimers; }
private listeners: Set<() => void> = new Set();
private loaded = false;
@@ -516,6 +554,13 @@ class PolymarketBotService {
throw new Error('Scan interval must be at least 30 seconds');
}
+ // Clear any orphaned timer for this bot (e.g. from HMR or a previous run)
+ const existing = this.timers.get(id);
+ if (existing) {
+ clearInterval(existing);
+ this.timers.delete(id);
+ }
+
this.updateBotStatus(id, 'running');
// Run immediately, then on interval
@@ -557,9 +602,19 @@ class PolymarketBotService {
}
async deleteBot(id: string): Promise<void> {
- await this.stopBot(id);
+ // Stop timer without triggering a save (skipSave=true) to avoid the race where
+ // updateBotStatus fire-and-forgets a save that writes the bot back after we delete it.
+ const timer = this.timers.get(id);
+ if (timer) {
+ clearInterval(timer);
+ this.timers.delete(id);
+ }
+ this.updateBotStatus(id, 'stopped', true /* skipSave */);
+
+ // Now remove from memory and persist the deletion
this.bots.delete(id);
await this.save();
+
// Clean up decisions from key-value storage
await storageService.remove(`${STORAGE_KEY_DECISIONS_PREFIX}${id}`);
// Delete from SQLite (CASCADE removes decisions + positions)
@@ -577,6 +632,30 @@ class PolymarketBotService {
decision.approved = true;
decision.pendingApproval = false;
+ // If token ID was missing when the decision was created, try to resolve it now
+ // by fetching the market detail directly from the Gamma API.
+ if (!decision.tokenId && decision.marketId) {
+ try {
+ const url = `https://gamma-api.polymarket.com/markets?id=${encodeURIComponent(decision.marketId)}&limit=1`;
+ const resp = await fetch(url);
+ if (resp.ok) {
+ const data = await resp.json();
+ const market = Array.isArray(data) ? data[0] : data;
+ const tokenIds: string[] = market?.clobTokenIds ?? [];
+ // YES token is index 0, NO token is index 1
+ if (decision.action === 'buy_no' || decision.action === 'sell_no') {
+ decision.tokenId = tokenIds[1] ?? tokenIds[0] ?? null;
+ } else {
+ decision.tokenId = tokenIds[0] ?? null;
+ }
+ // Strip the "[Token ID unavailable]" prefix from reasoning now that we have it
+ decision.reasoning = decision.reasoning.replace(/^\[Token ID unavailable[^\]]*\]\s*/i, '');
+ }
+ } catch {
+ // Non-fatal — executeDecision will handle null tokenId gracefully
+ }
+ }
+
await this.executeDecision(botId, decision);
await this.saveDecisions(botId, decisions);
@@ -616,6 +695,13 @@ class PolymarketBotService {
console.log(`[BotService] Running cycle for bot "${bot.name}" (${botId})`);
+ // Reset daily P&L at the start of a new calendar day
+ const lastCycle = bot.stats.lastCycleAt ? new Date(bot.stats.lastCycleAt) : null;
+ if (lastCycle && lastCycle.toDateString() !== new Date().toDateString()) {
+ bot.stats.dailyPnlUsdc = 0;
+ this.bots.set(botId, bot);
+ }
+
try {
// 1. Build agent config from bot's LLM config
const agentConfig = this.buildBotAgentConfig(bot);
@@ -629,6 +715,12 @@ class PolymarketBotService {
// 4. Run the agent
const response = await runAgent(query, agentConfig, apiKeys, `bot_session_${botId}`);
+ // ── Mid-flight abort check ─────────────────────────────────────────────
+ // Stop/pause may have been called while the agent was running.
+ // If so, silently discard the result — do not write error state or stats.
+ const botAfterAgent = this.bots.get(botId);
+ if (!botAfterAgent || botAfterAgent.status !== 'running') return;
+
if (!response.success) {
this.setBotError(botId, response.error ?? 'Agent returned failure');
return;
@@ -649,11 +741,30 @@ class PolymarketBotService {
const decisions = await this.loadDecisions(botId);
let newDecisionCount = 0;
+ // Build fast-lookup sets for deduplication
+ // Key: `${marketId}:${action}` — prevents queuing the same trade twice
+ const pendingKeys = new Set(
+ decisions
+ .filter((d) => d.pendingApproval)
+ .map((d) => `${d.marketId}:${d.action}`),
+ );
+ // Markets with an existing open position — don't re-enter
+ const openMarketIds = new Set(
+ bot.positions.filter((p) => !p.closedAt).map((p) => p.marketId),
+ );
+
for (const raw of rawDecisions) {
const action = (raw.action ?? 'skip') as DecisionAction;
if (action === 'hold' || action === 'skip') continue;
if ((raw.confidence ?? 0) < bot.strategy.minConfidence) continue;
- if (!raw.token_id || !raw.market_id) continue;
+ if (!raw.market_id) continue; // market_id is required; token_id may be filled later
+
+ // Skip if this exact market+action is already awaiting user approval
+ if (pendingKeys.has(`${raw.market_id}:${action}`)) continue;
+
+ // Skip buy recommendations when bot already holds a position in this market
+ const isBuy = action === 'buy_yes' || action === 'buy_no';
+ if (isBuy && openMarketIds.has(raw.market_id)) continue;
const sizeUsdc = Math.min(
raw.recommended_size_usdc ?? 10,
@@ -689,9 +800,12 @@ class PolymarketBotService {
continue;
}
- if (bot.riskConfig.requireApproval) {
- // Queue for user approval
+ if (bot.riskConfig.requireApproval || !decision.tokenId) {
+ // Queue for user approval (also required when token_id missing — can't execute without it)
decision.pendingApproval = true;
+ if (!decision.tokenId) {
+ decision.reasoning = `[Token ID unavailable — manual review required] ${decision.reasoning}`;
+ }
decisions.push(decision);
} else {
// Auto-execute
@@ -721,19 +835,21 @@ class PolymarketBotService {
).catch(() => {/* non-fatal */});
}
- // 8. Update stats
+ // 8. Update stats — only if still running (stop/pause may have fired mid-cycle)
const updatedBot = this.bots.get(botId);
- if (updatedBot) {
+ if (updatedBot && updatedBot.status === 'running') {
updatedBot.stats.totalCycles += 1;
updatedBot.stats.totalDecisions += newDecisionCount;
updatedBot.stats.lastCycleAt = new Date().toISOString();
updatedBot.lastError = undefined;
this.bots.set(botId, updatedBot);
+ await this.saveDecisions(botId, decisions);
+ await this.save();
+ this.notify();
+ } else {
+ // Bot was stopped/paused during the agent run — persist decisions only, don't touch status
+ await this.saveDecisions(botId, decisions);
}
-
- await this.saveDecisions(botId, decisions);
- await this.save();
- this.notify();
} catch (error: any) {
console.error(`[BotService] Cycle error for ${botId}:`, error);
this.setBotError(botId, error?.message ?? 'Unknown error during cycle');
@@ -743,13 +859,17 @@ class PolymarketBotService {
// ── Execution ────────────────────────────────────────────────────────────────
private async executeDecision(botId: string, decision: BotDecision): Promise<void> {
- const bot = this.bots.get(botId);
- if (!bot || !decision.tokenId) return;
+ if (!decision.tokenId) return;
const isBuy = decision.action === 'buy_yes' || decision.action === 'buy_no';
+ const isSell = decision.action === 'sell_yes' || decision.action === 'sell_no';
try {
if (isBuy) {
+ // Re-fetch bot at point of mutation to avoid stale-reference race with concurrent cycles
+ const bot = this.bots.get(botId);
+ if (!bot) return;
+
// Place limit order slightly above best ask for faster fill
const orderBook = await polymarketApiService.getOrderBook(decision.tokenId).catch(() => null);
const bestAsk = orderBook?.asks?.[0]?.price ?? String(decision.priceAtDecision + 0.01);
@@ -766,7 +886,10 @@ class PolymarketBotService {
decision.orderId = orderResp.order_id;
decision.executed = true;
- // Track position
+ // Re-fetch again after the async order call (another cycle may have mutated bot)
+ const freshBot = this.bots.get(botId);
+ if (!freshBot) return;
+
const position: BotPosition = {
id: `pos_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
botId,
@@ -782,15 +905,52 @@ class PolymarketBotService {
unrealizedPnlPct: 0,
};
- bot.positions.push(position);
- bot.stats.tradesExecuted += 1;
- this.bots.set(botId, bot);
+ freshBot.positions.push(position);
+ freshBot.stats.tradesExecuted += 1;
+ this.bots.set(botId, freshBot);
- // Sync new position to SQLite
await syncPositionToDb(position);
- console.log(`[BotService] Order placed for bot ${botId}: ${orderResp.order_id}`);
+ console.log(`[BotService] BUY order placed for bot ${botId}: ${orderResp.order_id}`);
+
+ } else if (isSell) {
+ // Find the matching open position to close
+ const bot = this.bots.get(botId);
+ if (!bot) return;
+
+ const openPosition = bot.positions.find(
+ (p) => !p.closedAt && p.tokenId === decision.tokenId,
+ );
+ if (!openPosition) {
+ console.warn(`[BotService] Sell decision for ${decision.tokenId} but no open position found — skipping`);
+ decision.executed = false;
+ return;
+ }
+
+ // Cancel existing open order first (non-fatal if already filled)
+ if (openPosition.orderId) {
+ await polymarketApiService.cancelOrder(openPosition.orderId).catch(() => {});
+ }
+
+ // Place a market sell (price at best bid)
+ const orderBook = await polymarketApiService.getOrderBook(decision.tokenId).catch(() => null);
+ const bestBid = orderBook?.bids?.[0]?.price ?? String(decision.priceAtDecision - 0.01);
+ const price = Math.max(parseFloat(bestBid) - 0.005, 0.001).toFixed(3);
+ const size = (openPosition.sizeUsdc / parseFloat(price)).toFixed(2);
+
+ const orderResp = await polymarketApiService.createOrder({
+ token_id: decision.tokenId,
+ price,
+ size,
+ side: 'SELL',
+ });
+
+ decision.orderId = orderResp.order_id;
+ decision.executed = true;
+
+ // Close the position
+ await this.closePosition(botId, openPosition, 'manual', parseFloat(price));
+ console.log(`[BotService] SELL order placed for bot ${botId}: ${orderResp.order_id}`);
}
- // Sell actions would follow a similar pattern with the existing cancelOrder / createOrder(SELL)
} catch (error: any) {
console.error(`[BotService] Execution error for ${botId}:`, error);
decision.executed = false;
@@ -897,7 +1057,7 @@ class PolymarketBotService {
// ── Helpers ──────────────────────────────────────────────────────────────────
private buildBotAgentConfig(bot: PolymarketBot): AgentConfig {
- return buildAgentConfig(
+ const config = buildAgentConfig(
bot.llmConfig.provider,
bot.llmConfig.modelId,
buildAgentInstructions(bot),
@@ -907,9 +1067,17 @@ class PolymarketBotService {
'polymarket_search_markets',
'polymarket_get_market_detail',
'polymarket_get_order_book',
+ 'polymarket_get_enriched_order_book',
'polymarket_get_price_history',
+ 'polymarket_get_midpoint',
'polymarket_get_events',
+ 'polymarket_get_event_by_slug',
+ 'polymarket_get_market_by_slug',
'polymarket_get_trades',
+ 'polymarket_get_top_holders',
+ 'polymarket_get_open_interest',
+ 'polymarket_get_tags',
+ 'polymarket_get_balance',
'calculator',
],
temperature: bot.llmConfig.temperature,
@@ -927,10 +1095,19 @@ class PolymarketBotService {
? { enabled: true, pii_detection: false, injection_check: true, financial_compliance: true }
: undefined,
agentic_memory: bot.llmConfig.enableMemory
- ? { enabled: true, user_id: `bot_${bot.id}` }
+ ? { enabled: true, user_id: `polymarket_bot_${bot.id}` }
: undefined,
},
);
+
+ // Polymarket analysis needs many tool rounds (fetch markets → details → order books → history).
+ // Raise the FinceptChat round limit so the agent isn't cut off mid-analysis.
+ // For other providers this field is ignored (they use Agno's native tool loop).
+ if (config.model) {
+ (config.model as any).max_tool_rounds = 15;
+ }
+
+ return config;
}
private async buildCycleQuery(bot: PolymarketBot): Promise<string> {
@@ -977,21 +1154,47 @@ class PolymarketBotService {
.join('\n')}`
: '';
- return `Run your Polymarket market analysis cycle now. Scan for trading opportunities and return your structured recommendations as a JSON array.${memoryContext}${perfContext}${positionContext}`;
+ // ── Pending decisions (already queued, awaiting approval) ─────────────────
+ const allDecisions = await this.loadDecisions(bot.id);
+ const pendingDecisions = allDecisions.filter((d) => d.pendingApproval);
+ const pendingContext =
+ pendingDecisions.length > 0
+ ? `\n\nAlready queued (PENDING approval — do NOT recommend these again):\n${pendingDecisions
+ .map((d) => `- ${d.action.toUpperCase()} "${d.marketQuestion}" [market: ${d.marketId}]`)
+ .join('\n')}`
+ : '';
+
+ // ── Event targeting directive ─────────────────────────────────────────────
+ const { eventMode, eventSlugs, eventKeywords } = bot.strategy;
+ let eventDirective = '';
+ if (eventMode === 'specific' && eventSlugs.length > 0) {
+ eventDirective = `\n\nTARGET EVENTS this cycle (fetch markets from these slugs only): ${eventSlugs.join(', ')}`;
+ } else if (eventMode === 'dynamic' && eventKeywords.length > 0) {
+ eventDirective = `\n\nDYNAMIC EVENT DISCOVERY: Search for active events/markets matching: ${eventKeywords.join(', ')}`;
+ }
+
+ return `Run your Polymarket market analysis cycle now. Scan for trading opportunities and return your structured recommendations as a JSON array.${eventDirective}${memoryContext}${perfContext}${positionContext}${pendingContext}`;
}
- private updateBotStatus(id: string, status: BotStatus): void {
+ private updateBotStatus(id: string, status: BotStatus, skipSave = false): void {
const bot = this.bots.get(id);
if (!bot) return;
bot.status = status;
this.bots.set(id, bot);
- this.save().catch(() => {});
+ if (!skipSave) this.save().catch(() => {});
this.notify();
}
private setBotError(id: string, message: string): void {
const bot = this.bots.get(id);
if (!bot) return;
+ // Never overwrite an intentional stop/pause with error status.
+ // This prevents an in-flight cycle from clobbering the user's stop action.
+ if (bot.status === 'stopped' || bot.status === 'paused') {
+ bot.lastError = message; // record the error text but keep the user's status
+ this.bots.set(id, bot);
+ return; // skip save/notify — status didn't change
+ }
bot.status = 'error';
bot.lastError = message;
this.bots.set(id, bot);