pmxt 1.0.0__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.
Files changed (56) hide show
  1. pmxt/__init__.py +58 -0
  2. pmxt/client.py +713 -0
  3. pmxt/models.py +296 -0
  4. pmxt/server_manager.py +242 -0
  5. pmxt-1.0.0.dist-info/METADATA +250 -0
  6. pmxt-1.0.0.dist-info/RECORD +56 -0
  7. pmxt-1.0.0.dist-info/WHEEL +5 -0
  8. pmxt-1.0.0.dist-info/top_level.txt +2 -0
  9. pmxt_internal/__init__.py +124 -0
  10. pmxt_internal/api/__init__.py +5 -0
  11. pmxt_internal/api/default_api.py +3722 -0
  12. pmxt_internal/api_client.py +804 -0
  13. pmxt_internal/api_response.py +21 -0
  14. pmxt_internal/configuration.py +578 -0
  15. pmxt_internal/exceptions.py +219 -0
  16. pmxt_internal/models/__init__.py +54 -0
  17. pmxt_internal/models/balance.py +93 -0
  18. pmxt_internal/models/base_request.py +91 -0
  19. pmxt_internal/models/base_response.py +93 -0
  20. pmxt_internal/models/cancel_order_request.py +94 -0
  21. pmxt_internal/models/create_order200_response.py +99 -0
  22. pmxt_internal/models/create_order_params.py +111 -0
  23. pmxt_internal/models/create_order_request.py +102 -0
  24. pmxt_internal/models/error_detail.py +87 -0
  25. pmxt_internal/models/error_response.py +93 -0
  26. pmxt_internal/models/exchange_credentials.py +93 -0
  27. pmxt_internal/models/fetch_balance200_response.py +103 -0
  28. pmxt_internal/models/fetch_markets200_response.py +103 -0
  29. pmxt_internal/models/fetch_markets_request.py +102 -0
  30. pmxt_internal/models/fetch_ohlcv200_response.py +103 -0
  31. pmxt_internal/models/fetch_ohlcv_request.py +102 -0
  32. pmxt_internal/models/fetch_ohlcv_request_args_inner.py +140 -0
  33. pmxt_internal/models/fetch_open_orders200_response.py +103 -0
  34. pmxt_internal/models/fetch_open_orders_request.py +94 -0
  35. pmxt_internal/models/fetch_order_book200_response.py +99 -0
  36. pmxt_internal/models/fetch_order_book_request.py +94 -0
  37. pmxt_internal/models/fetch_positions200_response.py +103 -0
  38. pmxt_internal/models/fetch_positions_request.py +94 -0
  39. pmxt_internal/models/fetch_trades200_response.py +103 -0
  40. pmxt_internal/models/fetch_trades_request.py +102 -0
  41. pmxt_internal/models/get_markets_by_slug_request.py +94 -0
  42. pmxt_internal/models/health_check200_response.py +89 -0
  43. pmxt_internal/models/history_filter_params.py +101 -0
  44. pmxt_internal/models/market_filter_params.py +113 -0
  45. pmxt_internal/models/market_outcome.py +95 -0
  46. pmxt_internal/models/order.py +139 -0
  47. pmxt_internal/models/order_book.py +106 -0
  48. pmxt_internal/models/order_level.py +89 -0
  49. pmxt_internal/models/position.py +101 -0
  50. pmxt_internal/models/price_candle.py +97 -0
  51. pmxt_internal/models/search_markets_request.py +102 -0
  52. pmxt_internal/models/search_markets_request_args_inner.py +140 -0
  53. pmxt_internal/models/trade.py +105 -0
  54. pmxt_internal/models/unified_market.py +120 -0
  55. pmxt_internal/py.typed +0 -0
  56. pmxt_internal/rest.py +263 -0
@@ -0,0 +1,21 @@
1
+ """API response object."""
2
+
3
+ from __future__ import annotations
4
+ from typing import Optional, Generic, Mapping, TypeVar
5
+ from pydantic import Field, StrictInt, StrictBytes, BaseModel
6
+
7
+ T = TypeVar("T")
8
+
9
+ class ApiResponse(BaseModel, Generic[T]):
10
+ """
11
+ API response object
12
+ """
13
+
14
+ status_code: StrictInt = Field(description="HTTP status code")
15
+ headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
16
+ data: T = Field(description="Deserialized data given the data type")
17
+ raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
18
+
19
+ model_config = {
20
+ "arbitrary_types_allowed": True
21
+ }
@@ -0,0 +1,578 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ PMXT Sidecar API
5
+
6
+ A unified local sidecar API for prediction markets (Polymarket, Kalshi). This API acts as a JSON-RPC-style gateway. Each endpoint corresponds to a specific method on the generic exchange implementation.
7
+
8
+ The version of the OpenAPI document: 0.4.4
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ import copy
16
+ import http.client as httplib
17
+ import logging
18
+ from logging import FileHandler
19
+ import multiprocessing
20
+ import sys
21
+ from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union
22
+ from typing_extensions import NotRequired, Self
23
+
24
+ import urllib3
25
+
26
+
27
+ JSON_SCHEMA_VALIDATION_KEYWORDS = {
28
+ 'multipleOf', 'maximum', 'exclusiveMaximum',
29
+ 'minimum', 'exclusiveMinimum', 'maxLength',
30
+ 'minLength', 'pattern', 'maxItems', 'minItems'
31
+ }
32
+
33
+ ServerVariablesT = Dict[str, str]
34
+
35
+ GenericAuthSetting = TypedDict(
36
+ "GenericAuthSetting",
37
+ {
38
+ "type": str,
39
+ "in": str,
40
+ "key": str,
41
+ "value": str,
42
+ },
43
+ )
44
+
45
+
46
+ OAuth2AuthSetting = TypedDict(
47
+ "OAuth2AuthSetting",
48
+ {
49
+ "type": Literal["oauth2"],
50
+ "in": Literal["header"],
51
+ "key": Literal["Authorization"],
52
+ "value": str,
53
+ },
54
+ )
55
+
56
+
57
+ APIKeyAuthSetting = TypedDict(
58
+ "APIKeyAuthSetting",
59
+ {
60
+ "type": Literal["api_key"],
61
+ "in": str,
62
+ "key": str,
63
+ "value": Optional[str],
64
+ },
65
+ )
66
+
67
+
68
+ BasicAuthSetting = TypedDict(
69
+ "BasicAuthSetting",
70
+ {
71
+ "type": Literal["basic"],
72
+ "in": Literal["header"],
73
+ "key": Literal["Authorization"],
74
+ "value": Optional[str],
75
+ },
76
+ )
77
+
78
+
79
+ BearerFormatAuthSetting = TypedDict(
80
+ "BearerFormatAuthSetting",
81
+ {
82
+ "type": Literal["bearer"],
83
+ "in": Literal["header"],
84
+ "format": Literal["JWT"],
85
+ "key": Literal["Authorization"],
86
+ "value": str,
87
+ },
88
+ )
89
+
90
+
91
+ BearerAuthSetting = TypedDict(
92
+ "BearerAuthSetting",
93
+ {
94
+ "type": Literal["bearer"],
95
+ "in": Literal["header"],
96
+ "key": Literal["Authorization"],
97
+ "value": str,
98
+ },
99
+ )
100
+
101
+
102
+ HTTPSignatureAuthSetting = TypedDict(
103
+ "HTTPSignatureAuthSetting",
104
+ {
105
+ "type": Literal["http-signature"],
106
+ "in": Literal["header"],
107
+ "key": Literal["Authorization"],
108
+ "value": None,
109
+ },
110
+ )
111
+
112
+
113
+ AuthSettings = TypedDict(
114
+ "AuthSettings",
115
+ {
116
+ },
117
+ total=False,
118
+ )
119
+
120
+
121
+ class HostSettingVariable(TypedDict):
122
+ description: str
123
+ default_value: str
124
+ enum_values: List[str]
125
+
126
+
127
+ class HostSetting(TypedDict):
128
+ url: str
129
+ description: str
130
+ variables: NotRequired[Dict[str, HostSettingVariable]]
131
+
132
+
133
+ class Configuration:
134
+ """This class contains various settings of the API client.
135
+
136
+ :param host: Base url.
137
+ :param ignore_operation_servers
138
+ Boolean to ignore operation servers for the API client.
139
+ Config will use `host` as the base url regardless of the operation servers.
140
+ :param api_key: Dict to store API key(s).
141
+ Each entry in the dict specifies an API key.
142
+ The dict key is the name of the security scheme in the OAS specification.
143
+ The dict value is the API key secret.
144
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
145
+ The dict key is the name of the security scheme in the OAS specification.
146
+ The dict value is an API key prefix when generating the auth data.
147
+ :param username: Username for HTTP basic authentication.
148
+ :param password: Password for HTTP basic authentication.
149
+ :param access_token: Access token.
150
+ :param server_index: Index to servers configuration.
151
+ :param server_variables: Mapping with string values to replace variables in
152
+ templated server configuration. The validation of enums is performed for
153
+ variables with defined enum values before.
154
+ :param server_operation_index: Mapping from operation ID to an index to server
155
+ configuration.
156
+ :param server_operation_variables: Mapping from operation ID to a mapping with
157
+ string values to replace variables in templated server configuration.
158
+ The validation of enums is performed for variables with defined enum
159
+ values before.
160
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
161
+ in PEM format.
162
+ :param retries: Number of retries for API requests.
163
+ :param ca_cert_data: verify the peer using concatenated CA certificate data
164
+ in PEM (str) or DER (bytes) format.
165
+ :param cert_file: the path to a client certificate file, for mTLS.
166
+ :param key_file: the path to a client key file, for mTLS.
167
+
168
+ """
169
+
170
+ _default: ClassVar[Optional[Self]] = None
171
+
172
+ def __init__(
173
+ self,
174
+ host: Optional[str]=None,
175
+ api_key: Optional[Dict[str, str]]=None,
176
+ api_key_prefix: Optional[Dict[str, str]]=None,
177
+ username: Optional[str]=None,
178
+ password: Optional[str]=None,
179
+ access_token: Optional[str]=None,
180
+ server_index: Optional[int]=None,
181
+ server_variables: Optional[ServerVariablesT]=None,
182
+ server_operation_index: Optional[Dict[int, int]]=None,
183
+ server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
184
+ ignore_operation_servers: bool=False,
185
+ ssl_ca_cert: Optional[str]=None,
186
+ retries: Optional[int] = None,
187
+ ca_cert_data: Optional[Union[str, bytes]] = None,
188
+ cert_file: Optional[str]=None,
189
+ key_file: Optional[str]=None,
190
+ *,
191
+ debug: Optional[bool] = None,
192
+ ) -> None:
193
+ """Constructor
194
+ """
195
+ self._base_path = "http://localhost:3847" if host is None else host
196
+ """Default Base url
197
+ """
198
+ self.server_index = 0 if server_index is None and host is None else server_index
199
+ self.server_operation_index = server_operation_index or {}
200
+ """Default server index
201
+ """
202
+ self.server_variables = server_variables or {}
203
+ self.server_operation_variables = server_operation_variables or {}
204
+ """Default server variables
205
+ """
206
+ self.ignore_operation_servers = ignore_operation_servers
207
+ """Ignore operation servers
208
+ """
209
+ self.temp_folder_path = None
210
+ """Temp file folder for downloading files
211
+ """
212
+ # Authentication Settings
213
+ self.api_key = {}
214
+ if api_key:
215
+ self.api_key = api_key
216
+ """dict to store API key(s)
217
+ """
218
+ self.api_key_prefix = {}
219
+ if api_key_prefix:
220
+ self.api_key_prefix = api_key_prefix
221
+ """dict to store API prefix (e.g. Bearer)
222
+ """
223
+ self.refresh_api_key_hook = None
224
+ """function hook to refresh API key if expired
225
+ """
226
+ self.username = username
227
+ """Username for HTTP basic authentication
228
+ """
229
+ self.password = password
230
+ """Password for HTTP basic authentication
231
+ """
232
+ self.access_token = access_token
233
+ """Access token
234
+ """
235
+ self.logger = {}
236
+ """Logging Settings
237
+ """
238
+ self.logger["package_logger"] = logging.getLogger("pmxt_internal")
239
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
240
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
241
+ """Log format
242
+ """
243
+ self.logger_stream_handler = None
244
+ """Log stream handler
245
+ """
246
+ self.logger_file_handler: Optional[FileHandler] = None
247
+ """Log file handler
248
+ """
249
+ self.logger_file = None
250
+ """Debug file location
251
+ """
252
+ if debug is not None:
253
+ self.debug = debug
254
+ else:
255
+ self.__debug = False
256
+ """Debug switch
257
+ """
258
+
259
+ self.verify_ssl = True
260
+ """SSL/TLS verification
261
+ Set this to false to skip verifying SSL certificate when calling API
262
+ from https server.
263
+ """
264
+ self.ssl_ca_cert = ssl_ca_cert
265
+ """Set this to customize the certificate file to verify the peer.
266
+ """
267
+ self.ca_cert_data = ca_cert_data
268
+ """Set this to verify the peer using PEM (str) or DER (bytes)
269
+ certificate data.
270
+ """
271
+ self.cert_file = cert_file
272
+ """client certificate file
273
+ """
274
+ self.key_file = key_file
275
+ """client key file
276
+ """
277
+ self.assert_hostname = None
278
+ """Set this to True/False to enable/disable SSL hostname verification.
279
+ """
280
+ self.tls_server_name = None
281
+ """SSL/TLS Server Name Indication (SNI)
282
+ Set this to the SNI value expected by the server.
283
+ """
284
+
285
+ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
286
+ """urllib3 connection pool's maximum number of connections saved
287
+ per pool. urllib3 uses 1 connection as default value, but this is
288
+ not the best value when you are making a lot of possibly parallel
289
+ requests to the same host, which is often the case here.
290
+ cpu_count * 5 is used as default value to increase performance.
291
+ """
292
+
293
+ self.proxy: Optional[str] = None
294
+ """Proxy URL
295
+ """
296
+ self.proxy_headers = None
297
+ """Proxy headers
298
+ """
299
+ self.safe_chars_for_path_param = ''
300
+ """Safe chars for path_param
301
+ """
302
+ self.retries = retries
303
+ """Adding retries to override urllib3 default value 3
304
+ """
305
+ # Enable client side validation
306
+ self.client_side_validation = True
307
+
308
+ self.socket_options = None
309
+ """Options to pass down to the underlying urllib3 socket
310
+ """
311
+
312
+ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
313
+ """datetime format
314
+ """
315
+
316
+ self.date_format = "%Y-%m-%d"
317
+ """date format
318
+ """
319
+
320
+ def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
321
+ cls = self.__class__
322
+ result = cls.__new__(cls)
323
+ memo[id(self)] = result
324
+ for k, v in self.__dict__.items():
325
+ if k not in ('logger', 'logger_file_handler'):
326
+ setattr(result, k, copy.deepcopy(v, memo))
327
+ # shallow copy of loggers
328
+ result.logger = copy.copy(self.logger)
329
+ # use setters to configure loggers
330
+ result.logger_file = self.logger_file
331
+ result.debug = self.debug
332
+ return result
333
+
334
+ def __setattr__(self, name: str, value: Any) -> None:
335
+ object.__setattr__(self, name, value)
336
+
337
+ @classmethod
338
+ def set_default(cls, default: Optional[Self]) -> None:
339
+ """Set default instance of configuration.
340
+
341
+ It stores default configuration, which can be
342
+ returned by get_default_copy method.
343
+
344
+ :param default: object of Configuration
345
+ """
346
+ cls._default = default
347
+
348
+ @classmethod
349
+ def get_default_copy(cls) -> Self:
350
+ """Deprecated. Please use `get_default` instead.
351
+
352
+ Deprecated. Please use `get_default` instead.
353
+
354
+ :return: The configuration object.
355
+ """
356
+ return cls.get_default()
357
+
358
+ @classmethod
359
+ def get_default(cls) -> Self:
360
+ """Return the default configuration.
361
+
362
+ This method returns newly created, based on default constructor,
363
+ object of Configuration class or returns a copy of default
364
+ configuration.
365
+
366
+ :return: The configuration object.
367
+ """
368
+ if cls._default is None:
369
+ cls._default = cls()
370
+ return cls._default
371
+
372
+ @property
373
+ def logger_file(self) -> Optional[str]:
374
+ """The logger file.
375
+
376
+ If the logger_file is None, then add stream handler and remove file
377
+ handler. Otherwise, add file handler and remove stream handler.
378
+
379
+ :param value: The logger_file path.
380
+ :type: str
381
+ """
382
+ return self.__logger_file
383
+
384
+ @logger_file.setter
385
+ def logger_file(self, value: Optional[str]) -> None:
386
+ """The logger file.
387
+
388
+ If the logger_file is None, then add stream handler and remove file
389
+ handler. Otherwise, add file handler and remove stream handler.
390
+
391
+ :param value: The logger_file path.
392
+ :type: str
393
+ """
394
+ self.__logger_file = value
395
+ if self.__logger_file:
396
+ # If set logging file,
397
+ # then add file handler and remove stream handler.
398
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
399
+ self.logger_file_handler.setFormatter(self.logger_formatter)
400
+ for _, logger in self.logger.items():
401
+ logger.addHandler(self.logger_file_handler)
402
+
403
+ @property
404
+ def debug(self) -> bool:
405
+ """Debug status
406
+
407
+ :param value: The debug status, True or False.
408
+ :type: bool
409
+ """
410
+ return self.__debug
411
+
412
+ @debug.setter
413
+ def debug(self, value: bool) -> None:
414
+ """Debug status
415
+
416
+ :param value: The debug status, True or False.
417
+ :type: bool
418
+ """
419
+ self.__debug = value
420
+ if self.__debug:
421
+ # if debug status is True, turn on debug logging
422
+ for _, logger in self.logger.items():
423
+ logger.setLevel(logging.DEBUG)
424
+ # turn on httplib debug
425
+ httplib.HTTPConnection.debuglevel = 1
426
+ else:
427
+ # if debug status is False, turn off debug logging,
428
+ # setting log level to default `logging.WARNING`
429
+ for _, logger in self.logger.items():
430
+ logger.setLevel(logging.WARNING)
431
+ # turn off httplib debug
432
+ httplib.HTTPConnection.debuglevel = 0
433
+
434
+ @property
435
+ def logger_format(self) -> str:
436
+ """The logger format.
437
+
438
+ The logger_formatter will be updated when sets logger_format.
439
+
440
+ :param value: The format string.
441
+ :type: str
442
+ """
443
+ return self.__logger_format
444
+
445
+ @logger_format.setter
446
+ def logger_format(self, value: str) -> None:
447
+ """The logger format.
448
+
449
+ The logger_formatter will be updated when sets logger_format.
450
+
451
+ :param value: The format string.
452
+ :type: str
453
+ """
454
+ self.__logger_format = value
455
+ self.logger_formatter = logging.Formatter(self.__logger_format)
456
+
457
+ def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
458
+ """Gets API key (with prefix if set).
459
+
460
+ :param identifier: The identifier of apiKey.
461
+ :param alias: The alternative identifier of apiKey.
462
+ :return: The token for api key authentication.
463
+ """
464
+ if self.refresh_api_key_hook is not None:
465
+ self.refresh_api_key_hook(self)
466
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
467
+ if key:
468
+ prefix = self.api_key_prefix.get(identifier)
469
+ if prefix:
470
+ return "%s %s" % (prefix, key)
471
+ else:
472
+ return key
473
+
474
+ return None
475
+
476
+ def get_basic_auth_token(self) -> Optional[str]:
477
+ """Gets HTTP basic authentication header (string).
478
+
479
+ :return: The token for basic HTTP authentication.
480
+ """
481
+ username = ""
482
+ if self.username is not None:
483
+ username = self.username
484
+ password = ""
485
+ if self.password is not None:
486
+ password = self.password
487
+
488
+ return urllib3.util.make_headers(
489
+ basic_auth=username + ':' + password
490
+ ).get('authorization')
491
+
492
+ def auth_settings(self)-> AuthSettings:
493
+ """Gets Auth Settings dict for api client.
494
+
495
+ :return: The Auth Settings information dict.
496
+ """
497
+ auth: AuthSettings = {}
498
+ return auth
499
+
500
+ def to_debug_report(self) -> str:
501
+ """Gets the essential information for debugging.
502
+
503
+ :return: The report for debugging.
504
+ """
505
+ return "Python SDK Debug Report:\n"\
506
+ "OS: {env}\n"\
507
+ "Python Version: {pyversion}\n"\
508
+ "Version of the API: 0.4.4\n"\
509
+ "SDK Package Version: 1.0.0".\
510
+ format(env=sys.platform, pyversion=sys.version)
511
+
512
+ def get_host_settings(self) -> List[HostSetting]:
513
+ """Gets an array of host settings
514
+
515
+ :return: An array of host settings
516
+ """
517
+ return [
518
+ {
519
+ 'url': "http://localhost:3847",
520
+ 'description': "Local development server",
521
+ }
522
+ ]
523
+
524
+ def get_host_from_settings(
525
+ self,
526
+ index: Optional[int],
527
+ variables: Optional[ServerVariablesT]=None,
528
+ servers: Optional[List[HostSetting]]=None,
529
+ ) -> str:
530
+ """Gets host URL based on the index and variables
531
+ :param index: array index of the host settings
532
+ :param variables: hash of variable and the corresponding value
533
+ :param servers: an array of host settings or None
534
+ :return: URL based on host settings
535
+ """
536
+ if index is None:
537
+ return self._base_path
538
+
539
+ variables = {} if variables is None else variables
540
+ servers = self.get_host_settings() if servers is None else servers
541
+
542
+ try:
543
+ server = servers[index]
544
+ except IndexError:
545
+ raise ValueError(
546
+ "Invalid index {0} when selecting the host settings. "
547
+ "Must be less than {1}".format(index, len(servers)))
548
+
549
+ url = server['url']
550
+
551
+ # go through variables and replace placeholders
552
+ for variable_name, variable in server.get('variables', {}).items():
553
+ used_value = variables.get(
554
+ variable_name, variable['default_value'])
555
+
556
+ if 'enum_values' in variable \
557
+ and variable['enum_values'] \
558
+ and used_value not in variable['enum_values']:
559
+ raise ValueError(
560
+ "The variable `{0}` in the host URL has invalid value "
561
+ "{1}. Must be {2}.".format(
562
+ variable_name, variables[variable_name],
563
+ variable['enum_values']))
564
+
565
+ url = url.replace("{" + variable_name + "}", used_value)
566
+
567
+ return url
568
+
569
+ @property
570
+ def host(self) -> str:
571
+ """Return generated host."""
572
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
573
+
574
+ @host.setter
575
+ def host(self, value: str) -> None:
576
+ """Fix base path."""
577
+ self._base_path = value
578
+ self.server_index = None