-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpm_watcher_single.py
More file actions
1428 lines (1169 loc) · 58.1 KB
/
pm_watcher_single.py
File metadata and controls
1428 lines (1169 loc) · 58.1 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 python3
"""
Prediction Market Watcher - Single File FastAPI Microservice
Exposes endpoints for evidence filtering, thesis generation, and decision making.
"""
import os
import sys
import json
import asyncio
import argparse
from typing import List, Dict, Any, Optional
from datetime import datetime
from dataclasses import dataclass, asdict
from enum import Enum
import uvicorn
from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from dotenv import load_dotenv
# LLM Providers
from openai import AsyncOpenAI
import google.generativeai as genai
# Kalshi imports
try:
from kalshi_python import Configuration, ApiClient
from kalshi_python.api import ExchangeApi, MarketsApi, PortfolioApi
KALSHI_AVAILABLE = True
except ImportError:
KALSHI_AVAILABLE = False
print("Warning: kalshi-python not available. Kalshi integration disabled.")
# Polymarket imports
try:
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, MarketOrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY, SELL
POLYMARKET_AVAILABLE = True
except ImportError:
POLYMARKET_AVAILABLE = False
print("Warning: py-clob-client not available. Polymarket integration disabled.")
# =============================================================================
# Data Models
# =============================================================================
class EvidenceItem(BaseModel):
"""Evidence item from web search or other sources"""
url: str = Field(..., description="Source URL")
title: str = Field(..., description="Title of the source")
summary: str = Field(..., description="Summary of the content")
timestamp: Optional[str] = Field(None, description="When this evidence was collected")
relevance_score: Optional[float] = Field(None, description="Relevance score 0-1")
class Market(BaseModel):
"""Prediction market definition"""
id: str = Field(..., description="Market identifier")
question: str = Field(..., description="Market question")
description: Optional[str] = Field(None, description="Detailed market description")
end_date: Optional[str] = Field(None, description="Market resolution date")
current_price: Optional[float] = Field(None, description="Current market price")
platform: Optional[str] = Field("polymarket", description="Market platform")
class Thesis(BaseModel):
"""Analysis thesis for a market"""
p_star: float = Field(..., description="Predicted probability", ge=0, le=1)
confidence: float = Field(..., description="Confidence in prediction", ge=0, le=1)
rationale: str = Field(..., description="Reasoning behind the prediction")
supporting_sources: List[str] = Field(..., description="URLs of supporting evidence")
risk_factors: Optional[List[str]] = Field(None, description="Identified risk factors")
class Decision(BaseModel):
"""Trading decision output"""
action: str = Field(..., description="Recommended action: buy, sell, hold")
size: float = Field(..., description="Position size (0-1)")
confidence: float = Field(..., description="Decision confidence", ge=0, le=1)
rationale: str = Field(..., description="Decision rationale")
max_loss: Optional[float] = Field(None, description="Maximum acceptable loss")
execution_disabled: bool = Field(True, description="Whether execution is disabled")
# Request/Response Models
class FilterEvidenceRequest(BaseModel):
items: List[EvidenceItem]
market: Market
class FilterEvidenceResponse(BaseModel):
evidence: List[EvidenceItem]
class ThesisRequest(BaseModel):
market: Market
evidence: List[EvidenceItem]
class ThesisResponse(BaseModel):
p_star: float
confidence: float
rationale: str
supporting_sources: List[str]
risk_factors: Optional[List[str]] = None
thesis: Optional[Thesis] = None
class DecideRequest(BaseModel):
market: Market
thesis: Thesis
class DecideResponse(BaseModel):
action: str
size: float
confidence: float
rationale: str
max_loss: Optional[float] = None
execution_disabled: bool = True
# =============================================================================
# Configuration
# =============================================================================
class Config:
"""Application configuration"""
def __init__(self):
env_path = os.path.join(os.getcwd(), ".env")
print(f"Loading env from: {env_path}")
load_dotenv(env_path)
self.llm_backend = os.getenv("LLM_BACKEND", "mock")
self.openai_api_key = os.getenv("OPENAI_API_KEY")
self.openai_base_url = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
self.openai_model = os.getenv("OPENAI_MODEL", "gpt-4")
self.openrouter_api_key = os.getenv("OPENROUTER_API_KEY")
self.openrouter_base_url = os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")
self.openrouter_model = os.getenv("OPENROUTER_MODEL", "meta-llama/llama-3.1-8b-instruct:free")
self.polymarket_enabled = os.getenv("POLYMARKET_ENABLED", "false").lower() == "true"
self.polymarket_api_key = os.getenv("POLYMARKET_API_KEY")
self.polymarket_private_key = os.getenv("POLYMARKET_PRIVATE_KEY")
self.polymarket_funder_address = os.getenv("POLYMARKET_FUNDER_ADDRESS")
self.kalshi_enabled = os.getenv("KALSHI_ENABLED", "false").lower() == "true"
self.kalshi_api_key = os.getenv("KALSHI_API_KEY")
self.kalshi_private_key = os.getenv("KALSHI_PRIVATE_KEY")
self.execution_enabled = os.getenv("EXECUTION_ENABLED", "false").lower() == "true"
self.gemini_api_key = os.getenv("GEMINI_API_KEY")
self.port = int(os.getenv("PORT", "8787"))
# Risk Management Configuration
self.max_position_size_usd = float(os.getenv("MAX_POSITION_SIZE_USD", "50.0"))
self.max_daily_loss_usd = float(os.getenv("MAX_DAILY_LOSS_USD", "100.0"))
def validate_production_config(self):
"""Validate that production configuration is complete"""
if self.llm_backend == "openai" and not self.openai_api_key:
raise ValueError("OPENAI_API_KEY is required when LLM_BACKEND=openai")
if self.llm_backend == "openrouter" and not self.openrouter_api_key:
raise ValueError("OPENROUTER_API_KEY is required when LLM_BACKEND=openrouter")
if self.llm_backend == "gemini" and not self.gemini_api_key:
raise ValueError("GEMINI_API_KEY is required when LLM_BACKEND=gemini")
raise ValueError("OPENROUTER_API_KEY is required when LLM_BACKEND=openrouter")
# =============================================================================
# Risk Management
# =============================================================================
class RiskManager:
"""
Enforces safety limits on trading decisions.
Acts as a circuit breaker and position sizer.
"""
def __init__(self, config: Config):
self.config = config
self.daily_loss = 0.0 # In a real app, this should be persisted (DB/Redis)
self.last_reset = datetime.utcnow().date()
def _reset_daily_stats_if_needed(self):
"""Reset daily stats if the day has changed"""
current_date = datetime.utcnow().date()
if current_date > self.last_reset:
self.daily_loss = 0.0
self.last_reset = current_date
def validate_decision(self, decision: DecideResponse, market: Market) -> DecideResponse:
"""
Validate and potentially modify a trading decision based on risk rules.
"""
self._reset_daily_stats_if_needed()
# Rule 1: If execution is disabled globally, ensure it's disabled in decision
if not self.config.execution_enabled:
decision.execution_disabled = True
return decision
# If action is HOLD, no risk check needed
if decision.action.lower() not in ["buy", "sell"]:
return decision
# Rule 2: Check Daily Loss Limit
# Note: This is a simple check. In production, we'd need to track realized PnL.
# Here we just stop trading if we've hit the limit.
if self.daily_loss >= self.config.max_daily_loss_usd:
print(f"Risk Alert: Daily loss limit reached (${self.daily_loss} >= ${self.config.max_daily_loss_usd})")
decision.action = "hold"
decision.rationale += " [RISK OVERRIDE: Daily loss limit reached]"
decision.execution_disabled = True
return decision
# Rule 3: Max Position Size
# We assume 'size' in decision is 0-1 (percentage of max size) or absolute amount?
# The prompt implies 0-1. Let's interpret it as percentage of MAX_POSITION_SIZE_USD for safety.
# Or if it's raw amount, we cap it.
# Let's assume the LLM returns a confidence-weighted size (0-1).
target_size_usd = decision.size * self.config.max_position_size_usd
# Cap at max position size
if target_size_usd > self.config.max_position_size_usd:
target_size_usd = self.config.max_position_size_usd
decision.rationale += f" [RISK: Capped at max size ${self.config.max_position_size_usd}]"
# Update the decision size to be the USD amount (or keep as ratio if downstream expects ratio)
# The PlaceOrderRequest expects 'amount'. Let's standardize on 'amount' being USD/Contracts.
# For now, we'll update the rationale to reflect the approved size.
decision.rationale += f" [RISK APPROVED: Size ${target_size_usd:.2f}]"
return decision
# Global Risk Manager
risk_manager = None
def get_risk_manager() -> RiskManager:
global risk_manager
if risk_manager is None:
risk_manager = RiskManager(config)
return risk_manager
# =============================================================================
# LLM Integration
# =============================================================================
class LLMProvider:
"""Abstract LLM provider interface"""
async def analyze_evidence(self, market: Market, evidence: List[EvidenceItem]) -> ThesisResponse:
raise NotImplementedError
async def make_decision(self, market: Market, thesis: Thesis) -> DecideResponse:
raise NotImplementedError
class OpenRouterProvider(LLMProvider):
"""OpenRouter provider for production use with various models"""
def __init__(self, config: Config):
self.config = config
# Import OpenAI only when needed (OpenRouter uses OpenAI-compatible API)
try:
import openai
self.client = openai.AsyncOpenAI(
api_key=config.openrouter_api_key,
base_url=config.openrouter_base_url
)
except ImportError:
raise ImportError("openai package required for OpenRouter provider. Install with: pip install openai")
async def analyze_evidence(self, market: Market, evidence: List[EvidenceItem]) -> ThesisResponse:
"""Generate thesis using OpenRouter"""
evidence_text = "\n".join([
f"- {item.title}: {item.summary} ({item.url})"
for item in evidence
])
prompt = f"""
Analyze the following prediction market and evidence to generate a thesis:
Market: {market.question}
Description: {market.description or "N/A"}
Current Price: {market.current_price or "Unknown"}
Evidence:
{evidence_text}
Provide a JSON response with exactly this structure:
{{
"p_star": 0.75,
"confidence": 0.8,
"rationale": "detailed reasoning here",
"supporting_sources": ["url1", "url2"],
"risk_factors": ["risk1", "risk2"]
}}
Important:
- p_star and confidence must be numbers between 0 and 1
- supporting_sources must be a list of strings (URLs)
- risk_factors must be a list of strings (not a single string)
- Be objective and base your analysis on the evidence provided
"""
try:
response = await self.client.chat.completions.create(
model=self.config.openrouter_model,
messages=[{"role": "user", "content": prompt}],
temperature=0.1
)
result = json.loads(response.choices[0].message.content)
# Ensure risk_factors is a list if provided
if "risk_factors" in result and isinstance(result["risk_factors"], str):
result["risk_factors"] = [result["risk_factors"]]
return ThesisResponse(**result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"LLM analysis failed: {str(e)}")
async def make_decision(self, market: Market, thesis: Thesis) -> DecideResponse:
"""Make trading decision using OpenRouter"""
prompt = f"""
Based on the following market analysis, make a trading decision:
Market: {market.question}
Current Price: {market.current_price or "Unknown"}
Thesis:
- Predicted Probability: {thesis.p_star}
- Confidence: {thesis.confidence}
- Rationale: {thesis.rationale}
Provide a JSON response with:
- action: "buy", "sell", or "hold"
- size: position size (0-1, where 1 is maximum position)
- confidence: decision confidence (0-1)
- rationale: decision reasoning
- max_loss: maximum acceptable loss (optional)
Consider risk management and position sizing carefully.
"""
try:
response = await self.client.chat.completions.create(
model=self.config.openrouter_model,
messages=[{"role": "user", "content": prompt}],
temperature=0.1
)
result = json.loads(response.choices[0].message.content)
result["execution_disabled"] = not self.config.execution_enabled
return DecideResponse(**result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Decision making failed: {str(e)}")
class OpenAIProvider(LLMProvider):
"""OpenAI GPT provider for production use"""
def __init__(self, config: Config):
self.config = config
# Import OpenAI only when needed
try:
import openai
self.client = openai.AsyncOpenAI(
api_key=config.openai_api_key,
base_url=config.openai_base_url
)
except ImportError:
raise ImportError("openai package required for OpenAI provider. Install with: pip install openai")
async def analyze_evidence(self, market: Market, evidence: List[EvidenceItem]) -> ThesisResponse:
"""Generate thesis using OpenAI"""
evidence_text = "\n".join([
f"- {item.title}: {item.summary} ({item.url})"
for item in evidence
])
prompt = f"""
Analyze the following prediction market and evidence to generate a thesis:
Market: {market.question}
Description: {market.description or "N/A"}
Current Price: {market.current_price or "Unknown"}
Evidence:
{evidence_text}
Provide a JSON response with:
- p_star: probability estimate (0-1)
- confidence: confidence in estimate (0-1)
- rationale: detailed reasoning
- supporting_sources: list of relevant URLs
- risk_factors: potential risks (optional)
Be objective and base your analysis on the evidence provided.
"""
try:
response = await self.client.chat.completions.create(
model=self.config.openai_model,
messages=[{"role": "user", "content": prompt}],
temperature=0.1
)
result = json.loads(response.choices[0].message.content)
return ThesisResponse(**result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"LLM analysis failed: {str(e)}")
async def make_decision(self, market: Market, thesis: Thesis) -> DecideResponse:
"""Make trading decision using OpenAI"""
prompt = f"""
Based on the following market analysis, make a trading decision:
Market: {market.question}
Current Price: {market.current_price or "Unknown"}
Thesis:
- Predicted Probability: {thesis.p_star}
- Confidence: {thesis.confidence}
- Rationale: {thesis.rationale}
Provide a JSON response with:
- action: "buy", "sell", or "hold"
- size: position size (0-1, where 1 is maximum position)
- confidence: decision confidence (0-1)
- rationale: decision reasoning
- max_loss: maximum acceptable loss (optional)
Consider risk management and position sizing carefully.
"""
try:
response = await self.client.chat.completions.create(
model=self.config.openai_model,
messages=[{"role": "user", "content": prompt}],
temperature=0.1
)
result = json.loads(response.choices[0].message.content)
result["execution_disabled"] = not self.config.execution_enabled
return DecideResponse(**result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Decision making failed: {str(e)}")
class MockProvider(LLMProvider):
"""Mock provider for testing only - should never be used in production"""
def __init__(self, config: Config):
self.config = config
if config.llm_backend == "openai":
raise ValueError("Mock provider should not be used when LLM_BACKEND=openai")
async def analyze_evidence(self, market: Market, evidence: List[EvidenceItem]) -> ThesisResponse:
"""Mock thesis generation - TEST ONLY"""
if self.config.llm_backend == "openai":
raise ValueError("Mock provider called in production mode")
return ThesisResponse(
p_star=0.65,
confidence=0.7,
rationale="Mock analysis - this should only appear in test mode",
supporting_sources=[item.url for item in evidence[:3]],
risk_factors=["This is mock data", "Not for production use"]
)
async def make_decision(self, market: Market, thesis: Thesis) -> DecideResponse:
"""Mock decision making - TEST ONLY"""
if self.config.llm_backend == "openai":
raise ValueError("Mock provider called in production mode")
return DecideResponse(
action="hold",
size=0.0,
confidence=0.5,
rationale="Mock decision - this should only appear in test mode",
execution_disabled=True
)
# =============================================================================
# FastAPI Application
# =============================================================================
# Global configuration
config = Config()
# Initialize FastAPI app
app = FastAPI(
title="Prediction Market Watcher",
description="Microservice for prediction market analysis and decision making",
version="1.0.0"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize LLM provider
def get_llm_provider() -> LLMProvider:
"""Get the appropriate LLM provider based on configuration"""
if config.llm_backend == "openai":
return OpenAIProvider(config)
elif config.llm_backend == "openrouter":
return OpenRouterProvider(config)
elif config.llm_backend == "polymarket":
if not POLYMARKET_AVAILABLE:
raise HTTPException(status_code=500, detail="Polymarket integration not available")
return PolymarketProvider(config)
elif config.llm_backend == "kalshi":
if not KALSHI_AVAILABLE:
raise HTTPException(status_code=500, detail="Kalshi integration not available")
return KalshiProvider(config)
elif config.llm_backend == "mock":
return MockProvider(config)
else:
raise HTTPException(status_code=500, detail=f"Unknown LLM backend: {config.llm_backend}")
# =============================================================================
# API Endpoints
# =============================================================================
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"ok": True,
"timestamp": datetime.utcnow().isoformat(),
"llm_backend": config.llm_backend,
"execution_enabled": config.execution_enabled,
"risk_config": {
"max_position_size": config.max_position_size_usd,
"max_daily_loss": config.max_daily_loss_usd
}
}
@app.post("/filter_evidence", response_model=FilterEvidenceResponse)
async def filter_evidence(request: FilterEvidenceRequest):
"""Filter and rank evidence items by relevance"""
try:
# Simple filtering logic - in production this could be more sophisticated
filtered_evidence = []
for item in request.items:
# Basic filtering criteria
if len(item.summary) < 10: # Too short
continue
if "404" in item.title.lower() or "not found" in item.title.lower():
continue
if not item.url.startswith(("http://", "https://")):
continue
# Add relevance score if not present
if item.relevance_score is None:
# Simple scoring based on summary length and title keywords
score = min(len(item.summary) / 500.0, 1.0)
item.relevance_score = score
filtered_evidence.append(item)
# Sort by relevance score (descending)
filtered_evidence.sort(key=lambda x: x.relevance_score or 0, reverse=True)
# Limit to top 10 items
filtered_evidence = filtered_evidence[:10]
return FilterEvidenceResponse(evidence=filtered_evidence)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Evidence filtering failed: {str(e)}")
@app.post("/thesis", response_model=ThesisResponse)
async def generate_thesis(request: ThesisRequest, llm: LLMProvider = Depends(get_llm_provider)):
"""Generate analysis thesis for a market based on evidence"""
try:
if not request.evidence:
raise HTTPException(status_code=400, detail="No evidence provided")
thesis = await llm.analyze_evidence(request.market, request.evidence)
return thesis
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Thesis generation failed: {str(e)}")
@app.post("/decide", response_model=DecideResponse)
async def make_decision(request: DecideRequest, llm: LLMProvider = Depends(get_llm_provider)):
"""Make trading decision based on market and thesis"""
try:
decision = await llm.make_decision(request.market, request.thesis)
# Risk Management Check
rm = get_risk_manager()
decision = rm.validate_decision(decision, request.market)
# Ensure execution is disabled by default if config says so (double check)
if not config.execution_enabled:
decision.execution_disabled = True
return decision
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Decision making failed: {str(e)}")
# =============================================================================
# Market Data and Trading Endpoints
# =============================================================================
class MarketDataRequest(BaseModel):
market_id: str = Field(..., description="Market identifier")
platform: str = Field(..., description="Platform (polymarket or kalshi)")
class MarketDataResponse(BaseModel):
market_id: str
platform: str
data: Dict[str, Any]
class PlaceOrderRequest(BaseModel):
market_id: str = Field(..., description="Market identifier")
platform: str = Field(..., description="Platform (polymarket or kalshi)")
side: str = Field(..., description="Order side (buy or sell)")
amount: float = Field(..., description="Order amount")
price: Optional[float] = Field(None, description="Order price (for limit orders)")
class PlaceOrderResponse(BaseModel):
success: bool
order_id: Optional[str] = None
message: str
details: Dict[str, Any] = {}
@app.get("/market/{platform}/{market_id}")
async def get_market_data(platform: str, market_id: str):
"""Get market data from specified platform"""
try:
if platform.lower() == "polymarket":
if not POLYMARKET_AVAILABLE:
raise HTTPException(status_code=400, detail="Polymarket integration not available")
provider = PolymarketProvider(config)
data = await provider.get_market_data(market_id)
return MarketDataResponse(
market_id=market_id,
platform="polymarket",
data=data
)
elif platform.lower() == "kalshi":
if not KALSHI_AVAILABLE:
raise HTTPException(status_code=400, detail="Kalshi integration not available")
provider = KalshiProvider(config)
data = await provider.get_market_data(market_id)
return MarketDataResponse(
market_id=market_id,
platform="kalshi",
data=data
)
else:
raise HTTPException(status_code=400, detail=f"Unsupported platform: {platform}")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to get market data: {str(e)}")
@app.post("/trade", response_model=PlaceOrderResponse)
async def place_order(request: PlaceOrderRequest):
"""Place an order on the specified platform"""
try:
if not config.execution_enabled:
return PlaceOrderResponse(
success=False,
message="Trading execution is disabled",
details={"execution_enabled": False}
)
if request.platform.lower() == "polymarket":
if not POLYMARKET_AVAILABLE:
raise HTTPException(status_code=400, detail="Polymarket integration not available")
provider = PolymarketProvider(config)
result = await provider.place_order(
request.market_id,
request.side,
request.amount,
request.price
)
return PlaceOrderResponse(
success=result.get("success", False),
order_id=result.get("order_id"),
message=result.get("message", "Order placed"),
details=result
)
elif request.platform.lower() == "kalshi":
if not KALSHI_AVAILABLE:
raise HTTPException(status_code=400, detail="Kalshi integration not available")
provider = KalshiProvider(config)
# Convert amount to int for Kalshi (cents)
kalshi_amount = int(request.amount * 100) if request.amount else 0
kalshi_price = int(request.price * 100) if request.price else None
result = await provider.place_order(
request.market_id,
request.side,
kalshi_amount,
kalshi_price
)
return PlaceOrderResponse(
success=result.get("success", False),
order_id=result.get("order_id"),
message=result.get("message", "Order placed"),
details=result
)
else:
raise HTTPException(status_code=400, detail=f"Unsupported platform: {request.platform}")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to place order: {str(e)}")
# =============================================================================
# CLI Interface
# =============================================================================
class PolymarketProvider(LLMProvider):
"""Polymarket integration provider for real market data and trading"""
def __init__(self, config: Config):
self.config = config
self.client = None
if POLYMARKET_AVAILABLE and config.polymarket_private_key:
try:
self.client = ClobClient(
host="https://clob.polymarket.com",
key=config.polymarket_private_key,
chain_id=137, # Polygon mainnet
signature_type=0, # EOA signature
funder=config.polymarket_funder_address
)
if self.client:
self.client.set_api_creds(self.client.create_or_derive_api_creds())
print("Polymarket client initialized successfully")
except Exception as e:
print(f"Failed to initialize Polymarket client: {e}")
self.client = None
else:
print("Polymarket not available or credentials missing")
async def get_market_data(self, market_id: str) -> Dict[str, Any]:
"""Get real market data from Polymarket"""
if not self.client:
raise HTTPException(status_code=503, detail="Polymarket client not available")
try:
# Get market price and orderbook data
midpoint = self.client.get_midpoint(market_id)
buy_price = self.client.get_price(market_id, side="BUY")
sell_price = self.client.get_price(market_id, side="SELL")
orderbook = self.client.get_order_book(market_id)
return {
"market_id": market_id,
"midpoint": midpoint,
"buy_price": buy_price,
"sell_price": sell_price,
"orderbook": orderbook,
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
print(f"Error fetching Polymarket data: {e}")
raise HTTPException(status_code=500, detail=f"Failed to fetch market data: {str(e)}")
async def place_order(self, market_id: str, side: str, amount: float, price: float = None) -> Dict[str, Any]:
"""Place an order on Polymarket"""
if not self.client:
raise HTTPException(status_code=503, detail="Polymarket client not available")
if not self.config.execution_enabled:
return {
"status": "simulation",
"message": "Order placement disabled - simulation mode",
"market_id": market_id,
"side": side,
"amount": amount,
"price": price
}
try:
if price is None:
# Market order
order_side = BUY if side.lower() == "buy" else SELL
mo = MarketOrderArgs(
token_id=market_id,
amount=amount,
side=order_side,
order_type=OrderType.FOK
)
signed_order = self.client.create_market_order(mo)
response = self.client.post_order(signed_order, OrderType.FOK)
else:
# Limit order
order_side = BUY if side.lower() == "buy" else SELL
order_args = OrderArgs(
token_id=market_id,
price=price,
size=amount,
side=order_side
)
signed_order = self.client.create_order(order_args)
response = self.client.post_order(signed_order, OrderType.GTC)
return {
"status": "success",
"order_response": response,
"market_id": market_id,
"side": side,
"amount": amount,
"price": price,
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
print(f"Error placing Polymarket order: {e}")
raise HTTPException(status_code=500, detail=f"Failed to place order: {str(e)}")
async def analyze_evidence(self, market: Market, evidence: List[EvidenceItem]) -> ThesisResponse:
"""Analyze evidence using real market data from Polymarket"""
try:
# Get real market data if market ID is provided
market_data = None
if hasattr(market, 'id') and market.id and self.client:
try:
market_data = await self.get_market_data(market.id)
except Exception as e:
print(f"Could not fetch market data: {e}")
# Use OpenRouter for LLM analysis with real market context
openrouter_provider = OpenRouterProvider(self.config)
# Enhance the market context with real data
enhanced_market = market
if market_data:
enhanced_market.current_price = market_data.get("midpoint", market.current_price)
enhanced_market.description = f"{market.description or ''}\n\nReal-time market data:\n- Current price: {market_data.get('midpoint', 'N/A')}\n- Buy price: {market_data.get('buy_price', 'N/A')}\n- Sell price: {market_data.get('sell_price', 'N/A')}"
return await openrouter_provider.analyze_evidence(enhanced_market, evidence)
except Exception as e:
print(f"Error in Polymarket analysis: {e}")
raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")
async def make_decision(self, market: Market, thesis: Thesis) -> DecideResponse:
"""Make trading decision with real Polymarket integration"""
try:
# Get real market data for decision making
market_data = None
if hasattr(market, 'id') and market.id and self.client:
try:
market_data = await self.get_market_data(market.id)
except Exception as e:
print(f"Could not fetch market data for decision: {e}")
# Use OpenRouter for decision logic with real market context
openrouter_provider = OpenRouterProvider(self.config)
# Enhance the market context with real data
enhanced_market = market
if market_data:
enhanced_market.current_price = market_data.get("midpoint", market.current_price)
decision = await openrouter_provider.make_decision(enhanced_market, thesis)
# If execution is enabled and we have a buy/sell decision, place the order
if (self.config.execution_enabled and
decision.action.lower() in ["buy", "sell"] and
hasattr(market, 'id') and market.id and
self.client):
try:
# Calculate order amount based on decision size
order_amount = decision.size * 100 # Convert to dollar amount
# Place the order
order_result = await self.place_order(
market_id=market.id,
side=decision.action,
amount=order_amount
)
# Update decision with execution details
decision.execution_disabled = False
decision.rationale += f"\n\nOrder executed: {order_result.get('status', 'unknown')}"
except Exception as e:
print(f"Order execution failed: {e}")
decision.rationale += f"\n\nOrder execution failed: {str(e)}"
return decision
except Exception as e:
print(f"Error in Polymarket decision: {e}")
raise HTTPException(status_code=500, detail=f"Decision failed: {str(e)}")
class KalshiProvider(LLMProvider):
"""Kalshi integration provider for real market data and trading"""
def __init__(self, config: Config):
self.config = config
self.client = None
self.market_api = None
self.exchange_api = None
self.portfolio_api = None
if KALSHI_AVAILABLE and config.kalshi_api_key:
try:
configuration = Configuration(
host="https://api.elections.kalshi.com/trade-api/v2",
api_key={'KEY': config.kalshi_api_key}
)
api_client = ApiClient(configuration)
# Set up authentication if private key is available
if config.kalshi_private_key and os.path.exists(config.kalshi_private_key):
api_client.set_kalshi_auth(config.kalshi_api_key, config.kalshi_private_key)
print(f"Kalshi authentication configured with key: {config.kalshi_private_key}")
else:
print("Warning: Kalshi private key not found, authentication will fail for trading")
self.exchange_api = ExchangeApi(api_client)
self.market_api = MarketsApi(api_client)
self.portfolio_api = PortfolioApi(api_client)
print("Kalshi client initialized successfully")
except Exception as e:
print(f"Failed to initialize Kalshi client: {e}")
self.client = None
else:
print("Kalshi not available or credentials missing")
async def get_market_data(self, market_id: str) -> Dict[str, Any]:
"""Get real market data from Kalshi"""
if not self.market_api:
raise HTTPException(status_code=503, detail="Kalshi client not available")
try:
# Get market information
market_response = self.market_api.get_market(market_id)
market = market_response.market
# Get orderbook data
orderbook_response = self.market_api.get_market_orderbook(market_id)
orderbook = orderbook_response.orderbook
return {
"market_id": market_id,
"title": market.title,
"subtitle": market.subtitle,
"yes_price": market.yes_bid if hasattr(market, 'yes_bid') else None,
"no_price": market.no_bid if hasattr(market, 'no_bid') else None,
"volume": market.volume,
"open_interest": market.open_interest,
"orderbook": {
"yes": orderbook.yes if orderbook else [],
"no": orderbook.no if orderbook else []
},
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
print(f"Error fetching Kalshi data: {e}")
raise HTTPException(status_code=500, detail=f"Failed to fetch market data: {str(e)}")
async def place_order(self, market_id: str, side: str, amount: int, price: int = None) -> Dict[str, Any]:
"""Place an order on Kalshi"""