kalshi-python-async 3.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 (151) hide show
  1. kalshi_python_async/__init__.py +272 -0
  2. kalshi_python_async/api/__init__.py +19 -0
  3. kalshi_python_async/api/api_keys_api.py +1098 -0
  4. kalshi_python_async/api/communications_api.py +3216 -0
  5. kalshi_python_async/api/events_api.py +1941 -0
  6. kalshi_python_async/api/exchange_api.py +1263 -0
  7. kalshi_python_async/api/fcm_api.py +792 -0
  8. kalshi_python_async/api/incentive_programs_api.py +346 -0
  9. kalshi_python_async/api/live_data_api.py +564 -0
  10. kalshi_python_async/api/market_api.py +2568 -0
  11. kalshi_python_async/api/milestone_api.py +689 -0
  12. kalshi_python_async/api/multivariate_api.py +1486 -0
  13. kalshi_python_async/api/order_groups_api.py +1375 -0
  14. kalshi_python_async/api/orders_api.py +2913 -0
  15. kalshi_python_async/api/portfolio_api.py +1572 -0
  16. kalshi_python_async/api/search_api.py +516 -0
  17. kalshi_python_async/api/structured_targets_api.py +605 -0
  18. kalshi_python_async/api_client.py +833 -0
  19. kalshi_python_async/api_response.py +21 -0
  20. kalshi_python_async/auth.py +89 -0
  21. kalshi_python_async/configuration.py +622 -0
  22. kalshi_python_async/exceptions.py +216 -0
  23. kalshi_python_async/models/__init__.py +136 -0
  24. kalshi_python_async/models/accept_quote_request.py +94 -0
  25. kalshi_python_async/models/amend_order_request.py +120 -0
  26. kalshi_python_async/models/amend_order_response.py +96 -0
  27. kalshi_python_async/models/announcement.py +108 -0
  28. kalshi_python_async/models/api_key.py +89 -0
  29. kalshi_python_async/models/associated_event.py +105 -0
  30. kalshi_python_async/models/batch_cancel_orders_individual_response.py +111 -0
  31. kalshi_python_async/models/batch_cancel_orders_request.py +87 -0
  32. kalshi_python_async/models/batch_cancel_orders_response.py +95 -0
  33. kalshi_python_async/models/batch_create_orders_individual_response.py +114 -0
  34. kalshi_python_async/models/batch_create_orders_request.py +95 -0
  35. kalshi_python_async/models/batch_create_orders_response.py +95 -0
  36. kalshi_python_async/models/batch_get_market_candlesticks_response.py +95 -0
  37. kalshi_python_async/models/bid_ask_distribution.py +101 -0
  38. kalshi_python_async/models/cancel_order_response.py +93 -0
  39. kalshi_python_async/models/create_api_key_request.py +89 -0
  40. kalshi_python_async/models/create_api_key_response.py +87 -0
  41. kalshi_python_async/models/create_market_in_multivariate_event_collection_request.py +95 -0
  42. kalshi_python_async/models/create_market_in_multivariate_event_collection_response.py +89 -0
  43. kalshi_python_async/models/create_order_group_request.py +88 -0
  44. kalshi_python_async/models/create_order_group_response.py +87 -0
  45. kalshi_python_async/models/create_order_request.py +159 -0
  46. kalshi_python_async/models/create_order_response.py +91 -0
  47. kalshi_python_async/models/create_quote_request.py +93 -0
  48. kalshi_python_async/models/create_quote_response.py +87 -0
  49. kalshi_python_async/models/create_rfq_request.py +97 -0
  50. kalshi_python_async/models/create_rfq_response.py +87 -0
  51. kalshi_python_async/models/daily_schedule.py +89 -0
  52. kalshi_python_async/models/decrease_order_request.py +90 -0
  53. kalshi_python_async/models/decrease_order_response.py +91 -0
  54. kalshi_python_async/models/error_response.py +93 -0
  55. kalshi_python_async/models/event_data.py +133 -0
  56. kalshi_python_async/models/event_position.py +105 -0
  57. kalshi_python_async/models/exchange_status.py +97 -0
  58. kalshi_python_async/models/fill.py +134 -0
  59. kalshi_python_async/models/forecast_percentiles_point.py +101 -0
  60. kalshi_python_async/models/generate_api_key_request.py +87 -0
  61. kalshi_python_async/models/generate_api_key_response.py +89 -0
  62. kalshi_python_async/models/get_api_keys_response.py +95 -0
  63. kalshi_python_async/models/get_balance_response.py +91 -0
  64. kalshi_python_async/models/get_communications_id_response.py +87 -0
  65. kalshi_python_async/models/get_event_candlesticks_response.py +104 -0
  66. kalshi_python_async/models/get_event_forecast_percentiles_history_response.py +95 -0
  67. kalshi_python_async/models/get_event_metadata_response.py +123 -0
  68. kalshi_python_async/models/get_event_response.py +101 -0
  69. kalshi_python_async/models/get_events_candlesticks_response.py +95 -0
  70. kalshi_python_async/models/get_events_candlesticks_response_events_inner.py +106 -0
  71. kalshi_python_async/models/get_events_response.py +107 -0
  72. kalshi_python_async/models/get_exchange_announcements_response.py +95 -0
  73. kalshi_python_async/models/get_exchange_schedule_response.py +91 -0
  74. kalshi_python_async/models/get_fills_response.py +97 -0
  75. kalshi_python_async/models/get_filters_by_sports_response.py +102 -0
  76. kalshi_python_async/models/get_incentive_programs_response.py +97 -0
  77. kalshi_python_async/models/get_live_data_response.py +91 -0
  78. kalshi_python_async/models/get_live_datas_response.py +95 -0
  79. kalshi_python_async/models/get_market_candlesticks_response.py +97 -0
  80. kalshi_python_async/models/get_market_orderbook_response.py +91 -0
  81. kalshi_python_async/models/get_market_response.py +91 -0
  82. kalshi_python_async/models/get_markets_response.py +97 -0
  83. kalshi_python_async/models/get_milestone_response.py +91 -0
  84. kalshi_python_async/models/get_milestones_response.py +97 -0
  85. kalshi_python_async/models/get_multivariate_event_collection_lookup_history_response.py +95 -0
  86. kalshi_python_async/models/get_multivariate_event_collection_response.py +91 -0
  87. kalshi_python_async/models/get_multivariate_event_collections_response.py +97 -0
  88. kalshi_python_async/models/get_multivariate_events_response.py +97 -0
  89. kalshi_python_async/models/get_order_group_response.py +89 -0
  90. kalshi_python_async/models/get_order_groups_response.py +95 -0
  91. kalshi_python_async/models/get_order_queue_position_response.py +87 -0
  92. kalshi_python_async/models/get_order_queue_positions_response.py +95 -0
  93. kalshi_python_async/models/get_order_response.py +91 -0
  94. kalshi_python_async/models/get_orders_response.py +97 -0
  95. kalshi_python_async/models/get_portfolio_resting_order_total_value_response.py +87 -0
  96. kalshi_python_async/models/get_positions_response.py +107 -0
  97. kalshi_python_async/models/get_quote_response.py +91 -0
  98. kalshi_python_async/models/get_quotes_response.py +97 -0
  99. kalshi_python_async/models/get_rfq_response.py +91 -0
  100. kalshi_python_async/models/get_rfqs_response.py +97 -0
  101. kalshi_python_async/models/get_series_fee_changes_response.py +95 -0
  102. kalshi_python_async/models/get_series_list_response.py +95 -0
  103. kalshi_python_async/models/get_series_response.py +91 -0
  104. kalshi_python_async/models/get_settlements_response.py +97 -0
  105. kalshi_python_async/models/get_structured_target_response.py +91 -0
  106. kalshi_python_async/models/get_structured_targets_response.py +97 -0
  107. kalshi_python_async/models/get_tags_for_series_categories_response.py +87 -0
  108. kalshi_python_async/models/get_trades_response.py +97 -0
  109. kalshi_python_async/models/get_user_data_timestamp_response.py +88 -0
  110. kalshi_python_async/models/incentive_program.py +121 -0
  111. kalshi_python_async/models/live_data.py +91 -0
  112. kalshi_python_async/models/lookup_point.py +102 -0
  113. kalshi_python_async/models/lookup_tickers_for_market_in_multivariate_event_collection_request.py +95 -0
  114. kalshi_python_async/models/lookup_tickers_for_market_in_multivariate_event_collection_response.py +89 -0
  115. kalshi_python_async/models/maintenance_window.py +90 -0
  116. kalshi_python_async/models/market.py +307 -0
  117. kalshi_python_async/models/market_candlestick.py +108 -0
  118. kalshi_python_async/models/market_candlesticks_response.py +97 -0
  119. kalshi_python_async/models/market_metadata.py +91 -0
  120. kalshi_python_async/models/market_position.py +110 -0
  121. kalshi_python_async/models/milestone.py +120 -0
  122. kalshi_python_async/models/multivariate_event_collection.py +122 -0
  123. kalshi_python_async/models/mve_selected_leg.py +91 -0
  124. kalshi_python_async/models/order.py +189 -0
  125. kalshi_python_async/models/order_group.py +89 -0
  126. kalshi_python_async/models/order_queue_position.py +91 -0
  127. kalshi_python_async/models/order_status.py +38 -0
  128. kalshi_python_async/models/orderbook.py +94 -0
  129. kalshi_python_async/models/percentile_point.py +93 -0
  130. kalshi_python_async/models/price_distribution.py +157 -0
  131. kalshi_python_async/models/price_range.py +91 -0
  132. kalshi_python_async/models/quote.py +153 -0
  133. kalshi_python_async/models/rfq.py +129 -0
  134. kalshi_python_async/models/schedule.py +105 -0
  135. kalshi_python_async/models/scope_list.py +87 -0
  136. kalshi_python_async/models/self_trade_prevention_type.py +37 -0
  137. kalshi_python_async/models/series.py +129 -0
  138. kalshi_python_async/models/series_fee_change.py +103 -0
  139. kalshi_python_async/models/settlement.py +118 -0
  140. kalshi_python_async/models/settlement_source.py +89 -0
  141. kalshi_python_async/models/sport_filter_details.py +102 -0
  142. kalshi_python_async/models/structured_target.py +98 -0
  143. kalshi_python_async/models/ticker_pair.py +98 -0
  144. kalshi_python_async/models/trade.py +113 -0
  145. kalshi_python_async/models/weekly_schedule.py +154 -0
  146. kalshi_python_async/py.typed +0 -0
  147. kalshi_python_async/rest.py +213 -0
  148. kalshi_python_async-3.0.0.dist-info/METADATA +78 -0
  149. kalshi_python_async-3.0.0.dist-info/RECORD +151 -0
  150. kalshi_python_async-3.0.0.dist-info/WHEEL +5 -0
  151. kalshi_python_async-3.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,622 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Kalshi Trade API Manual Endpoints
5
+
6
+ Manually defined OpenAPI spec for endpoints being migrated to spec-first approach
7
+
8
+ The version of the OpenAPI document: 3.0.0
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 sys
20
+ from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union
21
+ from typing_extensions import NotRequired, Self
22
+
23
+ import urllib3
24
+
25
+
26
+ JSON_SCHEMA_VALIDATION_KEYWORDS = {
27
+ 'multipleOf', 'maximum', 'exclusiveMaximum',
28
+ 'minimum', 'exclusiveMinimum', 'maxLength',
29
+ 'minLength', 'pattern', 'maxItems', 'minItems'
30
+ }
31
+
32
+ ServerVariablesT = Dict[str, str]
33
+
34
+ GenericAuthSetting = TypedDict(
35
+ "GenericAuthSetting",
36
+ {
37
+ "type": str,
38
+ "in": str,
39
+ "key": str,
40
+ "value": str,
41
+ },
42
+ )
43
+
44
+
45
+ OAuth2AuthSetting = TypedDict(
46
+ "OAuth2AuthSetting",
47
+ {
48
+ "type": Literal["oauth2"],
49
+ "in": Literal["header"],
50
+ "key": Literal["Authorization"],
51
+ "value": str,
52
+ },
53
+ )
54
+
55
+
56
+ APIKeyAuthSetting = TypedDict(
57
+ "APIKeyAuthSetting",
58
+ {
59
+ "type": Literal["api_key"],
60
+ "in": str,
61
+ "key": str,
62
+ "value": Optional[str],
63
+ },
64
+ )
65
+
66
+
67
+ BasicAuthSetting = TypedDict(
68
+ "BasicAuthSetting",
69
+ {
70
+ "type": Literal["basic"],
71
+ "in": Literal["header"],
72
+ "key": Literal["Authorization"],
73
+ "value": Optional[str],
74
+ },
75
+ )
76
+
77
+
78
+ BearerFormatAuthSetting = TypedDict(
79
+ "BearerFormatAuthSetting",
80
+ {
81
+ "type": Literal["bearer"],
82
+ "in": Literal["header"],
83
+ "format": Literal["JWT"],
84
+ "key": Literal["Authorization"],
85
+ "value": str,
86
+ },
87
+ )
88
+
89
+
90
+ BearerAuthSetting = TypedDict(
91
+ "BearerAuthSetting",
92
+ {
93
+ "type": Literal["bearer"],
94
+ "in": Literal["header"],
95
+ "key": Literal["Authorization"],
96
+ "value": str,
97
+ },
98
+ )
99
+
100
+
101
+ HTTPSignatureAuthSetting = TypedDict(
102
+ "HTTPSignatureAuthSetting",
103
+ {
104
+ "type": Literal["http-signature"],
105
+ "in": Literal["header"],
106
+ "key": Literal["Authorization"],
107
+ "value": None,
108
+ },
109
+ )
110
+
111
+
112
+ AuthSettings = TypedDict(
113
+ "AuthSettings",
114
+ {
115
+ "kalshiAccessKey": APIKeyAuthSetting,
116
+ "kalshiAccessSignature": APIKeyAuthSetting,
117
+ "kalshiAccessTimestamp": APIKeyAuthSetting,
118
+ },
119
+ total=False,
120
+ )
121
+
122
+
123
+ class HostSettingVariable(TypedDict):
124
+ description: str
125
+ default_value: str
126
+ enum_values: List[str]
127
+
128
+
129
+ class HostSetting(TypedDict):
130
+ url: str
131
+ description: str
132
+ variables: NotRequired[Dict[str, HostSettingVariable]]
133
+
134
+
135
+ class Configuration:
136
+ """This class contains various settings of the API client.
137
+
138
+ :param host: Base url.
139
+ :param ignore_operation_servers
140
+ Boolean to ignore operation servers for the API client.
141
+ Config will use `host` as the base url regardless of the operation servers.
142
+ :param api_key: Dict to store API key(s).
143
+ Each entry in the dict specifies an API key.
144
+ The dict key is the name of the security scheme in the OAS specification.
145
+ The dict value is the API key secret.
146
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
147
+ The dict key is the name of the security scheme in the OAS specification.
148
+ The dict value is an API key prefix when generating the auth data.
149
+ :param username: Username for HTTP basic authentication.
150
+ :param password: Password for HTTP basic authentication.
151
+ :param access_token: Access token.
152
+ :param server_index: Index to servers configuration.
153
+ :param server_variables: Mapping with string values to replace variables in
154
+ templated server configuration. The validation of enums is performed for
155
+ variables with defined enum values before.
156
+ :param server_operation_index: Mapping from operation ID to an index to server
157
+ configuration.
158
+ :param server_operation_variables: Mapping from operation ID to a mapping with
159
+ string values to replace variables in templated server configuration.
160
+ The validation of enums is performed for variables with defined enum
161
+ values before.
162
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
163
+ in PEM format.
164
+ :param retries: Number of retries for API requests.
165
+ :param ca_cert_data: verify the peer using concatenated CA certificate data
166
+ in PEM (str) or DER (bytes) format.
167
+ :param cert_file: the path to a client certificate file, for mTLS.
168
+ :param key_file: the path to a client key file, for mTLS.
169
+
170
+ :Example:
171
+
172
+ API Key Authentication Example.
173
+ Given the following security scheme in the OpenAPI specification:
174
+ components:
175
+ securitySchemes:
176
+ cookieAuth: # name for the security scheme
177
+ type: apiKey
178
+ in: cookie
179
+ name: JSESSIONID # cookie name
180
+
181
+ You can programmatically set the cookie:
182
+
183
+ conf = kalshi_python_async.Configuration(
184
+ api_key={'cookieAuth': 'abc123'}
185
+ api_key_prefix={'cookieAuth': 'JSESSIONID'}
186
+ )
187
+
188
+ The following cookie will be added to the HTTP request:
189
+ Cookie: JSESSIONID abc123
190
+ """
191
+
192
+ _default: ClassVar[Optional[Self]] = None
193
+
194
+ def __init__(
195
+ self,
196
+ host: Optional[str]=None,
197
+ api_key: Optional[Dict[str, str]]=None,
198
+ api_key_prefix: Optional[Dict[str, str]]=None,
199
+ username: Optional[str]=None,
200
+ password: Optional[str]=None,
201
+ access_token: Optional[str]=None,
202
+ server_index: Optional[int]=None,
203
+ server_variables: Optional[ServerVariablesT]=None,
204
+ server_operation_index: Optional[Dict[int, int]]=None,
205
+ server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
206
+ ignore_operation_servers: bool=False,
207
+ ssl_ca_cert: Optional[str]=None,
208
+ retries: Optional[int] = None,
209
+ ca_cert_data: Optional[Union[str, bytes]] = None,
210
+ cert_file: Optional[str]=None,
211
+ key_file: Optional[str]=None,
212
+ *,
213
+ debug: Optional[bool] = None,
214
+ ) -> None:
215
+ """Constructor
216
+ """
217
+ self._base_path = "https://api.elections.kalshi.com/trade-api/v2" if host is None else host
218
+ """Default Base url
219
+ """
220
+ self.server_index = 0 if server_index is None and host is None else server_index
221
+ self.server_operation_index = server_operation_index or {}
222
+ """Default server index
223
+ """
224
+ self.server_variables = server_variables or {}
225
+ self.server_operation_variables = server_operation_variables or {}
226
+ """Default server variables
227
+ """
228
+ self.ignore_operation_servers = ignore_operation_servers
229
+ """Ignore operation servers
230
+ """
231
+ self.temp_folder_path = None
232
+ """Temp file folder for downloading files
233
+ """
234
+ # Authentication Settings
235
+ self.api_key = {}
236
+ if api_key:
237
+ self.api_key = api_key
238
+ """dict to store API key(s)
239
+ """
240
+ self.api_key_prefix = {}
241
+ if api_key_prefix:
242
+ self.api_key_prefix = api_key_prefix
243
+ """dict to store API prefix (e.g. Bearer)
244
+ """
245
+ self.refresh_api_key_hook = None
246
+ """function hook to refresh API key if expired
247
+ """
248
+ self.username = username
249
+ """Username for HTTP basic authentication
250
+ """
251
+ self.password = password
252
+ """Password for HTTP basic authentication
253
+ """
254
+ self.access_token = access_token
255
+ """Access token
256
+ """
257
+ self.logger = {}
258
+ """Logging Settings
259
+ """
260
+ self.logger["package_logger"] = logging.getLogger("kalshi_python_async")
261
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
262
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
263
+ """Log format
264
+ """
265
+ self.logger_stream_handler = None
266
+ """Log stream handler
267
+ """
268
+ self.logger_file_handler: Optional[FileHandler] = None
269
+ """Log file handler
270
+ """
271
+ self.logger_file = None
272
+ """Debug file location
273
+ """
274
+ if debug is not None:
275
+ self.debug = debug
276
+ else:
277
+ self.__debug = False
278
+ """Debug switch
279
+ """
280
+
281
+ self.verify_ssl = True
282
+ """SSL/TLS verification
283
+ Set this to false to skip verifying SSL certificate when calling API
284
+ from https server.
285
+ """
286
+ self.ssl_ca_cert = ssl_ca_cert
287
+ """Set this to customize the certificate file to verify the peer.
288
+ """
289
+ self.ca_cert_data = ca_cert_data
290
+ """Set this to verify the peer using PEM (str) or DER (bytes)
291
+ certificate data.
292
+ """
293
+ self.cert_file = cert_file
294
+ """client certificate file
295
+ """
296
+ self.key_file = key_file
297
+ """client key file
298
+ """
299
+ self.assert_hostname = None
300
+ """Set this to True/False to enable/disable SSL hostname verification.
301
+ """
302
+ self.tls_server_name = None
303
+ """SSL/TLS Server Name Indication (SNI)
304
+ Set this to the SNI value expected by the server.
305
+ """
306
+
307
+ self.connection_pool_maxsize = 100
308
+ """This value is passed to the aiohttp to limit simultaneous connections.
309
+ Default values is 100, None means no-limit.
310
+ """
311
+
312
+ self.proxy: Optional[str] = None
313
+ """Proxy URL
314
+ """
315
+ self.proxy_headers = None
316
+ """Proxy headers
317
+ """
318
+ self.safe_chars_for_path_param = ''
319
+ """Safe chars for path_param
320
+ """
321
+ self.retries = retries
322
+ """Adding retries to override urllib3 default value 3
323
+ """
324
+ # Enable client side validation
325
+ self.client_side_validation = True
326
+
327
+ self.socket_options = None
328
+ """Options to pass down to the underlying urllib3 socket
329
+ """
330
+
331
+ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
332
+ """datetime format
333
+ """
334
+
335
+ self.date_format = "%Y-%m-%d"
336
+ """date format
337
+ """
338
+
339
+ def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
340
+ cls = self.__class__
341
+ result = cls.__new__(cls)
342
+ memo[id(self)] = result
343
+ for k, v in self.__dict__.items():
344
+ if k not in ('logger', 'logger_file_handler'):
345
+ setattr(result, k, copy.deepcopy(v, memo))
346
+ # shallow copy of loggers
347
+ result.logger = copy.copy(self.logger)
348
+ # use setters to configure loggers
349
+ result.logger_file = self.logger_file
350
+ result.debug = self.debug
351
+ return result
352
+
353
+ def __setattr__(self, name: str, value: Any) -> None:
354
+ object.__setattr__(self, name, value)
355
+
356
+ @classmethod
357
+ def set_default(cls, default: Optional[Self]) -> None:
358
+ """Set default instance of configuration.
359
+
360
+ It stores default configuration, which can be
361
+ returned by get_default_copy method.
362
+
363
+ :param default: object of Configuration
364
+ """
365
+ cls._default = default
366
+
367
+ @classmethod
368
+ def get_default_copy(cls) -> Self:
369
+ """Deprecated. Please use `get_default` instead.
370
+
371
+ Deprecated. Please use `get_default` instead.
372
+
373
+ :return: The configuration object.
374
+ """
375
+ return cls.get_default()
376
+
377
+ @classmethod
378
+ def get_default(cls) -> Self:
379
+ """Return the default configuration.
380
+
381
+ This method returns newly created, based on default constructor,
382
+ object of Configuration class or returns a copy of default
383
+ configuration.
384
+
385
+ :return: The configuration object.
386
+ """
387
+ if cls._default is None:
388
+ cls._default = cls()
389
+ return cls._default
390
+
391
+ @property
392
+ def logger_file(self) -> Optional[str]:
393
+ """The logger file.
394
+
395
+ If the logger_file is None, then add stream handler and remove file
396
+ handler. Otherwise, add file handler and remove stream handler.
397
+
398
+ :param value: The logger_file path.
399
+ :type: str
400
+ """
401
+ return self.__logger_file
402
+
403
+ @logger_file.setter
404
+ def logger_file(self, value: Optional[str]) -> None:
405
+ """The logger file.
406
+
407
+ If the logger_file is None, then add stream handler and remove file
408
+ handler. Otherwise, add file handler and remove stream handler.
409
+
410
+ :param value: The logger_file path.
411
+ :type: str
412
+ """
413
+ self.__logger_file = value
414
+ if self.__logger_file:
415
+ # If set logging file,
416
+ # then add file handler and remove stream handler.
417
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
418
+ self.logger_file_handler.setFormatter(self.logger_formatter)
419
+ for _, logger in self.logger.items():
420
+ logger.addHandler(self.logger_file_handler)
421
+
422
+ @property
423
+ def debug(self) -> bool:
424
+ """Debug status
425
+
426
+ :param value: The debug status, True or False.
427
+ :type: bool
428
+ """
429
+ return self.__debug
430
+
431
+ @debug.setter
432
+ def debug(self, value: bool) -> None:
433
+ """Debug status
434
+
435
+ :param value: The debug status, True or False.
436
+ :type: bool
437
+ """
438
+ self.__debug = value
439
+ if self.__debug:
440
+ # if debug status is True, turn on debug logging
441
+ for _, logger in self.logger.items():
442
+ logger.setLevel(logging.DEBUG)
443
+ # turn on httplib debug
444
+ httplib.HTTPConnection.debuglevel = 1
445
+ else:
446
+ # if debug status is False, turn off debug logging,
447
+ # setting log level to default `logging.WARNING`
448
+ for _, logger in self.logger.items():
449
+ logger.setLevel(logging.WARNING)
450
+ # turn off httplib debug
451
+ httplib.HTTPConnection.debuglevel = 0
452
+
453
+ @property
454
+ def logger_format(self) -> str:
455
+ """The logger format.
456
+
457
+ The logger_formatter will be updated when sets logger_format.
458
+
459
+ :param value: The format string.
460
+ :type: str
461
+ """
462
+ return self.__logger_format
463
+
464
+ @logger_format.setter
465
+ def logger_format(self, value: str) -> None:
466
+ """The logger format.
467
+
468
+ The logger_formatter will be updated when sets logger_format.
469
+
470
+ :param value: The format string.
471
+ :type: str
472
+ """
473
+ self.__logger_format = value
474
+ self.logger_formatter = logging.Formatter(self.__logger_format)
475
+
476
+ def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
477
+ """Gets API key (with prefix if set).
478
+
479
+ :param identifier: The identifier of apiKey.
480
+ :param alias: The alternative identifier of apiKey.
481
+ :return: The token for api key authentication.
482
+ """
483
+ if self.refresh_api_key_hook is not None:
484
+ self.refresh_api_key_hook(self)
485
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
486
+ if key:
487
+ prefix = self.api_key_prefix.get(identifier)
488
+ if prefix:
489
+ return "%s %s" % (prefix, key)
490
+ else:
491
+ return key
492
+
493
+ return None
494
+
495
+ def get_basic_auth_token(self) -> Optional[str]:
496
+ """Gets HTTP basic authentication header (string).
497
+
498
+ :return: The token for basic HTTP authentication.
499
+ """
500
+ username = ""
501
+ if self.username is not None:
502
+ username = self.username
503
+ password = ""
504
+ if self.password is not None:
505
+ password = self.password
506
+ return urllib3.util.make_headers(
507
+ basic_auth=username + ':' + password
508
+ ).get('authorization')
509
+
510
+ def auth_settings(self)-> AuthSettings:
511
+ """Gets Auth Settings dict for api client.
512
+
513
+ :return: The Auth Settings information dict.
514
+ """
515
+ auth: AuthSettings = {}
516
+ if 'kalshiAccessKey' in self.api_key:
517
+ auth['kalshiAccessKey'] = {
518
+ 'type': 'api_key',
519
+ 'in': 'header',
520
+ 'key': 'KALSHI-ACCESS-KEY',
521
+ 'value': self.get_api_key_with_prefix(
522
+ 'kalshiAccessKey',
523
+ ),
524
+ }
525
+ if 'kalshiAccessSignature' in self.api_key:
526
+ auth['kalshiAccessSignature'] = {
527
+ 'type': 'api_key',
528
+ 'in': 'header',
529
+ 'key': 'KALSHI-ACCESS-SIGNATURE',
530
+ 'value': self.get_api_key_with_prefix(
531
+ 'kalshiAccessSignature',
532
+ ),
533
+ }
534
+ if 'kalshiAccessTimestamp' in self.api_key:
535
+ auth['kalshiAccessTimestamp'] = {
536
+ 'type': 'api_key',
537
+ 'in': 'header',
538
+ 'key': 'KALSHI-ACCESS-TIMESTAMP',
539
+ 'value': self.get_api_key_with_prefix(
540
+ 'kalshiAccessTimestamp',
541
+ ),
542
+ }
543
+ return auth
544
+
545
+ def to_debug_report(self) -> str:
546
+ """Gets the essential information for debugging.
547
+
548
+ :return: The report for debugging.
549
+ """
550
+ return "Python SDK Debug Report:\n"\
551
+ "OS: {env}\n"\
552
+ "Python Version: {pyversion}\n"\
553
+ "Version of the API: 3.0.0\n"\
554
+ "SDK Package Version: 3.0.0".\
555
+ format(env=sys.platform, pyversion=sys.version)
556
+
557
+ def get_host_settings(self) -> List[HostSetting]:
558
+ """Gets an array of host settings
559
+
560
+ :return: An array of host settings
561
+ """
562
+ return [
563
+ {
564
+ 'url': "https://api.elections.kalshi.com/trade-api/v2",
565
+ 'description': "Production server",
566
+ }
567
+ ]
568
+
569
+ def get_host_from_settings(
570
+ self,
571
+ index: Optional[int],
572
+ variables: Optional[ServerVariablesT]=None,
573
+ servers: Optional[List[HostSetting]]=None,
574
+ ) -> str:
575
+ """Gets host URL based on the index and variables
576
+ :param index: array index of the host settings
577
+ :param variables: hash of variable and the corresponding value
578
+ :param servers: an array of host settings or None
579
+ :return: URL based on host settings
580
+ """
581
+ if index is None:
582
+ return self._base_path
583
+
584
+ variables = {} if variables is None else variables
585
+ servers = self.get_host_settings() if servers is None else servers
586
+
587
+ try:
588
+ server = servers[index]
589
+ except IndexError:
590
+ raise ValueError(
591
+ "Invalid index {0} when selecting the host settings. "
592
+ "Must be less than {1}".format(index, len(servers)))
593
+
594
+ url = server['url']
595
+
596
+ # go through variables and replace placeholders
597
+ for variable_name, variable in server.get('variables', {}).items():
598
+ used_value = variables.get(
599
+ variable_name, variable['default_value'])
600
+
601
+ if 'enum_values' in variable \
602
+ and used_value not in variable['enum_values']:
603
+ raise ValueError(
604
+ "The variable `{0}` in the host URL has invalid value "
605
+ "{1}. Must be {2}.".format(
606
+ variable_name, variables[variable_name],
607
+ variable['enum_values']))
608
+
609
+ url = url.replace("{" + variable_name + "}", used_value)
610
+
611
+ return url
612
+
613
+ @property
614
+ def host(self) -> str:
615
+ """Return generated host."""
616
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
617
+
618
+ @host.setter
619
+ def host(self, value: str) -> None:
620
+ """Fix base path."""
621
+ self._base_path = value
622
+ self.server_index = None