polymarket-apis 0.2.6__py3-none-any.whl → 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of polymarket-apis might be problematic. Click here for more details.

@@ -25,26 +25,26 @@ class PolymarketDataClient:
25
25
  return urljoin(self.base_url, endpoint)
26
26
 
27
27
  def get_positions(
28
- self,
29
- user: str,
30
- condition_id: Optional[Union[str, list[str]]] = None,
31
- size_threshold: float = 1.0,
32
- redeemable: Optional[bool] = None,
33
- mergeable: Optional[bool] = None,
34
- title: Optional[str] = None,
35
- limit: int = 100,
36
- offset: int = 0,
37
- sort_by: Literal[
38
- "TOKENS",
39
- "CURRENT",
40
- "INITIAL",
41
- "CASHPNL",
42
- "PERCENTPNL",
43
- "TITLE",
44
- "RESOLVING",
45
- "PRICE",
46
- ] = "TOKENS",
47
- sort_direction: Literal["ASC", "DESC"] = "DESC",
28
+ self,
29
+ user: str,
30
+ condition_id: Optional[Union[str, list[str]]] = None,
31
+ size_threshold: float = 1.0,
32
+ redeemable: Optional[bool] = None,
33
+ mergeable: Optional[bool] = None,
34
+ title: Optional[str] = None,
35
+ limit: int = 100,
36
+ offset: int = 0,
37
+ sort_by: Literal[
38
+ "TOKENS",
39
+ "CURRENT",
40
+ "INITIAL",
41
+ "CASHPNL",
42
+ "PERCENTPNL",
43
+ "TITLE",
44
+ "RESOLVING",
45
+ "PRICE",
46
+ ] = "TOKENS",
47
+ sort_direction: Literal["ASC", "DESC"] = "DESC",
48
48
  ) -> list[Position]:
49
49
  params = {
50
50
  "user": user,
@@ -72,17 +72,17 @@ class PolymarketDataClient:
72
72
  return [Position(**pos) for pos in response.json()]
73
73
 
74
74
  def get_trades(
75
- self,
76
- limit: int = 100,
77
- offset: int = 0,
78
- taker_only: bool = True,
79
- filter_type: Optional[Literal["CASH", "TOKENS"]] = None,
80
- filter_amount: Optional[float] = None,
81
- condition_id: Optional[str] = None,
82
- user: Optional[str] = None,
83
- side: Optional[Literal["BUY", "SELL"]] = None,
75
+ self,
76
+ limit: int = 100,
77
+ offset: int = 0,
78
+ taker_only: bool = True,
79
+ filter_type: Optional[Literal["CASH", "TOKENS"]] = None,
80
+ filter_amount: Optional[float] = None,
81
+ condition_id: Optional[str] = None,
82
+ user: Optional[str] = None,
83
+ side: Optional[Literal["BUY", "SELL"]] = None,
84
84
  ) -> list[Trade]:
85
- params = {
85
+ params: dict[str, int | bool | str | float] = {
86
86
  "limit": min(limit, 500),
87
87
  "offset": offset,
88
88
  "takerOnly": taker_only,
@@ -103,17 +103,24 @@ class PolymarketDataClient:
103
103
  return [Trade(**trade) for trade in response.json()]
104
104
 
105
105
  def get_activity(
106
- self,
107
- user: str,
108
- limit: int = 100,
109
- offset: int = 0,
110
- condition_id: Optional[Union[str, list[str]]] = None,
111
- type: Optional[Union[Literal["TRADE", "SPLIT", "MERGE", "REDEEM", "REWARD", "CONVERSION"], list[Literal["TRADE", "SPLIT", "MERGE", "REDEEM", "REWARD", "CONVERSION"]]]] = None,
112
- start: Optional[datetime] = None,
113
- end: Optional[datetime] = None,
114
- side: Optional[Literal["BUY", "SELL"]] = None,
115
- sort_by: Literal["TIMESTAMP", "TOKENS", "CASH"] = "TIMESTAMP",
116
- sort_direction: Literal["ASC", "DESC"] = "DESC",
106
+ self,
107
+ user: str,
108
+ limit: int = 100,
109
+ offset: int = 0,
110
+ condition_id: Optional[Union[str, list[str]]] = None,
111
+ type: Optional[
112
+ Union[
113
+ Literal["TRADE", "SPLIT", "MERGE", "REDEEM", "REWARD", "CONVERSION"],
114
+ list[
115
+ Literal["TRADE", "SPLIT", "MERGE", "REDEEM", "REWARD", "CONVERSION"]
116
+ ],
117
+ ]
118
+ ] = None,
119
+ start: Optional[datetime] = None,
120
+ end: Optional[datetime] = None,
121
+ side: Optional[Literal["BUY", "SELL"]] = None,
122
+ sort_by: Literal["TIMESTAMP", "TOKENS", "CASH"] = "TIMESTAMP",
123
+ sort_direction: Literal["ASC", "DESC"] = "DESC",
117
124
  ) -> list[Activity]:
118
125
  params = {"user": user, "limit": min(limit, 500), "offset": offset}
119
126
  if isinstance(condition_id, str):
@@ -140,22 +147,20 @@ class PolymarketDataClient:
140
147
  return [Activity(**activity) for activity in response.json()]
141
148
 
142
149
  def get_holders(
143
- self,
144
- condition_id: str,
145
- limit: int = 20,
150
+ self,
151
+ condition_id: str,
152
+ limit: int = 20,
146
153
  ) -> list[HolderResponse]:
147
154
  """Takes in a condition_id and returns a list of at most 20 top holders for each corresponding token_id."""
148
155
  params = {"market": condition_id, "limit": limit}
149
156
  response = self.client.get(self._build_url("/holders"), params=params)
150
157
  response.raise_for_status()
151
- return [
152
- HolderResponse(**holder_data) for holder_data in response.json()
153
- ]
158
+ return [HolderResponse(**holder_data) for holder_data in response.json()]
154
159
 
155
160
  def get_value(
156
- self,
157
- user: str,
158
- condition_id: Optional[Union[str, list[str]]] = None,
161
+ self,
162
+ user: str,
163
+ condition_ids: Optional[Union[str, list[str]]] = None,
159
164
  ) -> ValueResponse:
160
165
  """
161
166
  Get the current value of a user's position in a set of markets.
@@ -166,10 +171,10 @@ class PolymarketDataClient:
166
171
  - list[str] --> sum of the values of positions.
167
172
  """
168
173
  params = {"user": user}
169
- if isinstance(condition_id, str):
170
- params["market"] = condition_id
171
- if isinstance(condition_id, list):
172
- params["market"] = ",".join(condition_id)
174
+ if isinstance(condition_ids, str):
175
+ params["market"] = condition_ids
176
+ if isinstance(condition_ids, list):
177
+ params["market"] = ",".join(condition_ids)
173
178
 
174
179
  response = self.client.get(self._build_url("/value"), params=params)
175
180
  response.raise_for_status()
@@ -178,10 +183,10 @@ class PolymarketDataClient:
178
183
  # website endpoints
179
184
 
180
185
  def get_pnl(
181
- self,
182
- user: EthAddress,
183
- period: Literal["all", "1m", "1w", "1d"] = "all",
184
- frequency: Literal["1h", "3h", "12h", "1d"] = "1h",
186
+ self,
187
+ user: EthAddress,
188
+ period: Literal["all", "1m", "1w", "1d"] = "all",
189
+ frequency: Literal["1h", "3h", "12h", "1d"] = "1h",
185
190
  ) -> list[TimeseriesPoint]:
186
191
  """Get a user's PnL timeseries in the last day, week, month or all with a given frequency."""
187
192
  params = {
@@ -190,22 +195,36 @@ class PolymarketDataClient:
190
195
  "fidelity": frequency,
191
196
  }
192
197
 
193
- response = self.client.get("https://user-pnl-api.polymarket.com/user-pnl", params=params)
198
+ response = self.client.get(
199
+ "https://user-pnl-api.polymarket.com/user-pnl", params=params
200
+ )
194
201
  response.raise_for_status()
195
202
  return [TimeseriesPoint(**point) for point in response.json()]
196
203
 
197
- def get_user_metric(self, user: EthAddress, metric: Literal["profit", "volume"] = "profit", window: Literal["1d", "7d", "30d", "all"] = "all"):
204
+ def get_user_metric(
205
+ self,
206
+ user: EthAddress,
207
+ metric: Literal["profit", "volume"] = "profit",
208
+ window: Literal["1d", "7d", "30d", "all"] = "all",
209
+ ):
198
210
  """Get a user's overall profit or volume in the last day, week, month or all."""
199
211
  params = {
200
212
  "address": user,
201
213
  "window": window,
202
214
  "limit": 1,
203
215
  }
204
- response = self.client.get("https://lb-api.polymarket.com/" + metric, params=params)
216
+ response = self.client.get(
217
+ "https://lb-api.polymarket.com/" + metric, params=params
218
+ )
205
219
  response.raise_for_status()
206
220
  return UserMetric(**response.json()[0])
207
221
 
208
- def get_leaderboard_user_rank(self, user: EthAddress, metric: Literal["profit", "volume"] = "profit", window: Literal["1d", "7d", "30d", "all"] = "all"):
222
+ def get_leaderboard_user_rank(
223
+ self,
224
+ user: EthAddress,
225
+ metric: Literal["profit", "volume"] = "profit",
226
+ window: Literal["1d", "7d", "30d", "all"] = "all",
227
+ ):
209
228
  """Get a user's rank on the leaderboard by profit or volume."""
210
229
  params = {
211
230
  "address": user,
@@ -216,17 +235,23 @@ class PolymarketDataClient:
216
235
  response.raise_for_status()
217
236
  return UserRank(**response.json()[0])
218
237
 
219
- def get_leaderboard_top_users(self, metric: Literal["profit", "volume"] = "profit", window: Literal["1d", "7d", "30d", "all"] = "all", limit: int = 100):
238
+ def get_leaderboard_top_users(
239
+ self,
240
+ metric: Literal["profit", "volume"] = "profit",
241
+ window: Literal["1d", "7d", "30d", "all"] = "all",
242
+ limit: int = 100,
243
+ ):
220
244
  """Get the leaderboard of the top at most 100 users by profit or volume."""
221
245
  params = {
222
246
  "window": window,
223
247
  "limit": limit,
224
248
  }
225
- response = self.client.get("https://lb-api.polymarket.com/" + metric, params=params)
249
+ response = self.client.get(
250
+ "https://lb-api.polymarket.com/" + metric, params=params
251
+ )
226
252
  response.raise_for_status()
227
253
  return [UserMetric(**user) for user in response.json()]
228
254
 
229
-
230
255
  def __enter__(self):
231
256
  return self
232
257
 
@@ -25,28 +25,28 @@ class PolymarketGammaClient:
25
25
  return urljoin(self.base_url, endpoint)
26
26
 
27
27
  def get_markets(
28
- self,
29
- limit: Optional[int] = None,
30
- offset: Optional[int] = None,
31
- order: Optional[str] = None,
32
- ascending: bool = True,
33
- ids: Optional[list[int]] = None,
34
- slugs: Optional[list[str]] = None,
35
- archived: Optional[bool] = None,
36
- active: Optional[bool] = None,
37
- closed: Optional[bool] = None,
38
- token_ids: Optional[list[str]] = None,
39
- condition_ids: Optional[list[str]] = None,
40
- liquidity_num_min: Optional[float] = None,
41
- liquidity_num_max: Optional[float] = None,
42
- volume_num_min: Optional[float] = None,
43
- volume_num_max: Optional[float] = None,
44
- start_date_min: Optional[datetime] = None,
45
- start_date_max: Optional[datetime] = None,
46
- end_date_min: Optional[datetime] = None,
47
- end_date_max: Optional[datetime] = None,
48
- tag_id: Optional[int] = None,
49
- related_tags: Optional[bool] = False,
28
+ self,
29
+ limit: Optional[int] = None,
30
+ offset: Optional[int] = None,
31
+ order: Optional[str] = None,
32
+ ascending: bool = True,
33
+ archived: Optional[bool] = None,
34
+ active: Optional[bool] = None,
35
+ closed: Optional[bool] = None,
36
+ slugs: Optional[list[str]] = None,
37
+ market_ids: Optional[list[int]] = None,
38
+ token_ids: Optional[list[str]] = None,
39
+ condition_ids: Optional[list[str]] = None,
40
+ tag_id: Optional[int] = None,
41
+ related_tags: Optional[bool] = False,
42
+ liquidity_num_min: Optional[float] = None,
43
+ liquidity_num_max: Optional[float] = None,
44
+ volume_num_min: Optional[float] = None,
45
+ volume_num_max: Optional[float] = None,
46
+ start_date_min: Optional[datetime] = None,
47
+ start_date_max: Optional[datetime] = None,
48
+ end_date_min: Optional[datetime] = None,
49
+ end_date_max: Optional[datetime] = None,
50
50
  ) -> list[GammaMarket]:
51
51
  params = {}
52
52
  if limit:
@@ -56,8 +56,6 @@ class PolymarketGammaClient:
56
56
  if order:
57
57
  params["order"] = order
58
58
  params["ascending"] = ascending
59
- if ids:
60
- params["id"] = ids
61
59
  if slugs:
62
60
  params["slug"] = slugs
63
61
  if archived is not None:
@@ -66,6 +64,8 @@ class PolymarketGammaClient:
66
64
  params["active"] = active
67
65
  if closed is not None:
68
66
  params["closed"] = closed
67
+ if market_ids:
68
+ params["id"] = market_ids
69
69
  if token_ids:
70
70
  params["clob_token_ids"] = token_ids
71
71
  if condition_ids:
@@ -102,28 +102,28 @@ class PolymarketGammaClient:
102
102
  return GammaMarket(**response.json())
103
103
 
104
104
  def get_events(
105
- self,
106
- limit: Optional[int] = None,
107
- offset: Optional[int] = None,
108
- order: Optional[str] = None,
109
- ascending: bool = True,
110
- event_ids: Optional[Union[str, list[str]]] = None,
111
- slugs: Optional[list[str]] = None,
112
- archived: Optional[bool] = None,
113
- active: Optional[bool] = None,
114
- closed: Optional[bool] = None,
115
- liquidity_min: Optional[float] = None,
116
- liquidity_max: Optional[float] = None,
117
- volume_min: Optional[float] = None,
118
- volume_max: Optional[float] = None,
119
- start_date_min: Optional[datetime] = None,
120
- start_date_max: Optional[datetime] = None,
121
- end_date_min: Optional[datetime] = None,
122
- end_date_max: Optional[datetime] = None,
123
- tag: Optional[str] = None,
124
- tag_id: Optional[int] = None,
125
- tag_slug: Optional[str] = None,
126
- related_tags: bool = False,
105
+ self,
106
+ limit: Optional[int] = None,
107
+ offset: Optional[int] = None,
108
+ order: Optional[str] = None,
109
+ ascending: bool = True,
110
+ event_ids: Optional[Union[str, list[str]]] = None,
111
+ slugs: Optional[list[str]] = None,
112
+ archived: Optional[bool] = None,
113
+ active: Optional[bool] = None,
114
+ closed: Optional[bool] = None,
115
+ liquidity_min: Optional[float] = None,
116
+ liquidity_max: Optional[float] = None,
117
+ volume_min: Optional[float] = None,
118
+ volume_max: Optional[float] = None,
119
+ start_date_min: Optional[datetime] = None,
120
+ start_date_max: Optional[datetime] = None,
121
+ end_date_min: Optional[datetime] = None,
122
+ end_date_max: Optional[datetime] = None,
123
+ tag: Optional[str] = None,
124
+ tag_id: Optional[int] = None,
125
+ tag_slug: Optional[str] = None,
126
+ related_tags: bool = False,
127
127
  ) -> list[Event]:
128
128
  params = {}
129
129
  if limit:
@@ -178,26 +178,26 @@ class PolymarketGammaClient:
178
178
  return Event(**response.json())
179
179
 
180
180
  def get_all_events(
181
- self,
182
- order: Optional[str] = None,
183
- ascending: bool = True,
184
- event_ids: Optional[Union[str, list[str]]] = None,
185
- slugs: Optional[list[str]] = None,
186
- archived: Optional[bool] = None,
187
- active: Optional[bool] = None,
188
- closed: Optional[bool] = None,
189
- liquidity_min: Optional[float] = None,
190
- liquidity_max: Optional[float] = None,
191
- volume_min: Optional[float] = None,
192
- volume_max: Optional[float] = None,
193
- start_date_min: Optional[datetime] = None,
194
- start_date_max: Optional[datetime] = None,
195
- end_date_min: Optional[datetime] = None,
196
- end_date_max: Optional[datetime] = None,
197
- tag: Optional[str] = None,
198
- tag_id: Optional[int] = None,
199
- tag_slug: Optional[str] = None,
200
- related_tags: bool = False,
181
+ self,
182
+ order: Optional[str] = None,
183
+ ascending: bool = True,
184
+ event_ids: Optional[Union[str, list[str]]] = None,
185
+ slugs: Optional[list[str]] = None,
186
+ archived: Optional[bool] = None,
187
+ active: Optional[bool] = None,
188
+ closed: Optional[bool] = None,
189
+ liquidity_min: Optional[float] = None,
190
+ liquidity_max: Optional[float] = None,
191
+ volume_min: Optional[float] = None,
192
+ volume_max: Optional[float] = None,
193
+ start_date_min: Optional[datetime] = None,
194
+ start_date_max: Optional[datetime] = None,
195
+ end_date_min: Optional[datetime] = None,
196
+ end_date_max: Optional[datetime] = None,
197
+ tag: Optional[str] = None,
198
+ tag_id: Optional[int] = None,
199
+ tag_slug: Optional[str] = None,
200
+ related_tags: bool = False,
201
201
  ) -> list[Event]:
202
202
  offset = 0
203
203
  events = []
@@ -236,20 +236,39 @@ class PolymarketGammaClient:
236
236
  return events
237
237
 
238
238
  def search_events(
239
- self,
240
- query: str,
241
- active: bool = True,
242
- status: Optional[Literal["active", "resolved"]] = "active",
243
- sort: Literal["volume", "volume_24hr", "liquidity", "start_date", "end_date", "competitive"] = "volume_24hr",
244
- page: int = 1,
245
- limit_per_type: int = 50, # max is 50
239
+ self,
240
+ query: str,
241
+ active: bool = True,
242
+ status: Optional[Literal["active", "resolved"]] = "active",
243
+ sort: Literal[
244
+ "volume",
245
+ "volume_24hr",
246
+ "liquidity",
247
+ "start_date",
248
+ "end_date",
249
+ "competitive",
250
+ ] = "volume_24hr",
251
+ page: int = 1,
252
+ limit_per_type: int = 50, # max is 50
253
+ presets: Optional[
254
+ Literal["EventsHybrid", "EventsTitle"]
255
+ | list[Literal["EventsHybrid", "EventsTitle"]]
256
+ ] = None,
246
257
  ) -> EventList:
247
258
  """Search for events by query. Should emulate the website search function."""
248
- params = {"q": query,"page": page, "limit_per_type": limit_per_type, "events_status": status, "active": active, "presets": "EventsTitle"}
259
+ params = {
260
+ "q": query,
261
+ "page": page,
262
+ "limit_per_type": limit_per_type,
263
+ "events_status": status,
264
+ "active": active,
265
+ }
249
266
  if sort:
250
267
  params["sort"] = sort
251
268
  if sort == "end_date":
252
269
  params["ascending"] = "true"
270
+ if presets:
271
+ params["presets"] = presets
253
272
  response = self.client.get(self._build_url("/public-search"), params=params)
254
273
  response.raise_for_status()
255
274
  return EventList(**response.json())
@@ -299,7 +318,9 @@ class PolymarketGammaClient:
299
318
  for source in citations:
300
319
  print(f"- {source.get('url', 'Unknown URL')}")
301
320
 
302
- def grok_election_market_explanation(self, candidate_name: str, election_title: str):
321
+ def grok_election_market_explanation(
322
+ self, candidate_name: str, election_title: str
323
+ ):
303
324
  text = f"Provide candidate information for {candidate_name} in the {election_title} on Polymarket."
304
325
  json_payload = {
305
326
  "id": generate_random_id(),
@@ -0,0 +1,60 @@
1
+ from typing import Literal
2
+
3
+ from gql import Client, gql
4
+ from gql.transport.httpx import HTTPXAsyncTransport, HTTPXTransport
5
+
6
+ from ..utilities.config import GRAPHQL_ENDPOINTS
7
+
8
+
9
+ class PolymarketGraphQLClient:
10
+ """Synchronous GraphQL client for Polymarket subgraphs."""
11
+
12
+ def __init__(
13
+ self,
14
+ endpoint_name: Literal[
15
+ "activity_subgraph",
16
+ "fpmm_subgraph",
17
+ "open_interest_subgraph",
18
+ "orderbook_subgraph",
19
+ "pnl_subgraph",
20
+ "positions_subgraph",
21
+ "sports_oracle_subgraph",
22
+ "wallet_subgraph",
23
+ ],
24
+ ) -> None:
25
+ endpoint_url = GRAPHQL_ENDPOINTS[endpoint_name]
26
+ self.transport = HTTPXTransport(url=endpoint_url)
27
+ self.client = Client(
28
+ transport=self.transport, fetch_schema_from_transport=False
29
+ )
30
+
31
+ def query(self, query_string: str) -> dict:
32
+ with self.client as session:
33
+ return session.execute(gql(query_string))
34
+
35
+
36
+ class AsyncPolymarketGraphQLClient:
37
+ """Asynchronous GraphQL client for Polymarket subgraphs."""
38
+
39
+ def __init__(
40
+ self,
41
+ endpoint_name: Literal[
42
+ "activity_subgraph",
43
+ "fpmm_subgraph",
44
+ "open_interest_subgraph",
45
+ "orderbook_subgraph",
46
+ "pnl_subgraph",
47
+ "positions_subgraph",
48
+ "sports_oracle_subgraph",
49
+ "wallet_subgraph",
50
+ ],
51
+ ) -> None:
52
+ endpoint_url = GRAPHQL_ENDPOINTS[endpoint_name]
53
+ self.transport = HTTPXAsyncTransport(url=endpoint_url)
54
+ self.client = Client(
55
+ transport=self.transport, fetch_schema_from_transport=False
56
+ )
57
+
58
+ async def query(self, query_string: str) -> dict:
59
+ async with self.client as session:
60
+ return await session.execute(gql(query_string))