stocknotebridge 3.2.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.
File without changes
@@ -0,0 +1,637 @@
1
+ # coding: utf-8
2
+ """
3
+ StockNote API Documentation
4
+
5
+ StockNote API is a set of Rest APIs using which users can build customized applications based on their trading requirements. It facilitates the users of the APIs to login, search symbols, place orders and execute them, view their order status, positions and holdings etc. This documentation provides you with all the necessary details to understand the SAMCO StockNote API collection. APIs are compatible with both Javascript and Python. For any issues or support, please raise ticket to us using the <a href=\"https://www.samco.in/support/index/tradeapi\">support link</a> and we will be happy to assist you. For Reference you can download postman collection <a href=\"http://developers.stocknote.com/doc/StockNoteApi.postman_collection.json\">Click here</a> For downloading a list of all tradeable scrips across exchanges please <a href=\"https://developers.stocknote.com/doc/ScripMaster.csv\">Click here</a> This is a CSV file which you can import into your database. Add 'session token' of login api response as 'x-session-token' in header param of all Apis. NOTE: To ensure stability and there by provide seamless services to our customers, Samco may set limits on your use of the StockNote APIs (for example, limit on the number of requests sent to a specific API) . If you have additional questions regarding the rate limits on APIs, please reach out to us using the <a href=\"https://www.samco.in/support/index/tradeapi\">support link</a> and we will be happy to assist you. # noqa: E501
6
+
7
+ OpenAPI spec version: 1.0
8
+
9
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
10
+ """
11
+
12
+ import datetime
13
+ import json
14
+ import mimetypes
15
+ from multiprocessing.pool import ThreadPool
16
+ import os
17
+ import re
18
+ import tempfile
19
+
20
+ from urllib.parse import quote
21
+
22
+ from snapi_py_client.configuration import Configuration
23
+
24
+ from snapi_py_client import rest
25
+
26
+
27
+ class ApiClient(object):
28
+ """Generic API client for Swagger client library builds.
29
+
30
+ Swagger generic API client. This client handles the client-
31
+ server communication, and is invariant across implementations. Specifics of
32
+ the methods and models for each application are generated from the Swagger
33
+ templates.
34
+
35
+ NOTE: This class is auto generated by the swagger code generator program.
36
+ Ref: https://github.com/swagger-api/swagger-codegen
37
+ Do not edit the class manually.
38
+
39
+ :param configuration: .Configuration object for this client
40
+ :param header_name: a header to pass when making calls to the API.
41
+ :param header_value: a header value to pass when making calls to
42
+ the API.
43
+ :param cookie: a cookie to include in the header when making calls
44
+ to the API
45
+ """
46
+
47
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
48
+ NATIVE_TYPES_MAPPING = {
49
+ 'int': int,
50
+ 'long': int,
51
+ 'float': float,
52
+ 'str': str,
53
+ 'bool': bool,
54
+ 'date': datetime.date,
55
+ 'datetime': datetime.datetime,
56
+ 'object': object,
57
+ }
58
+
59
+ def __init__(self, configuration=None, header_name=None, header_value=None,
60
+ cookie=None):
61
+ if configuration is None:
62
+ configuration = Configuration()
63
+ self.configuration = configuration
64
+
65
+ # Use the pool property to lazily initialize the ThreadPool.
66
+ self._pool = None
67
+ self.rest_client = rest.RESTClientObject(configuration)
68
+ self.default_headers = {}
69
+ if header_name is not None:
70
+ self.default_headers[header_name] = header_value
71
+ self.cookie = cookie
72
+ # Set default User-Agent.
73
+ self.user_agent = 'Swagger-Codegen/1.0.0/python'
74
+
75
+ def __del__(self):
76
+ if self._pool is not None:
77
+ self._pool.close()
78
+ self._pool.join()
79
+
80
+ @property
81
+ def pool(self):
82
+ if self._pool is None:
83
+ self._pool = ThreadPool()
84
+ return self._pool
85
+
86
+ @property
87
+ def user_agent(self):
88
+ """User agent for this API client"""
89
+ return self.default_headers['User-Agent']
90
+
91
+ @user_agent.setter
92
+ def user_agent(self, value):
93
+ self.default_headers['User-Agent'] = value
94
+
95
+ def set_default_header(self, header_name, header_value):
96
+ self.default_headers[header_name] = header_value
97
+
98
+ def __call_api(
99
+ self, resource_path, method, path_params=None,
100
+ query_params=None, header_params=None, body=None, post_params=None,
101
+ files=None, response_type=None, auth_settings=None,
102
+ _return_http_data_only=None, collection_formats=None,
103
+ _preload_content=True, _request_timeout=None):
104
+
105
+ config = self.configuration
106
+
107
+ # header parameters
108
+ header_params = header_params or {}
109
+ header_params.update(self.default_headers)
110
+ if self.cookie:
111
+ header_params['Cookie'] = self.cookie
112
+ if header_params:
113
+ header_params = self.sanitize_for_serialization(header_params)
114
+ header_params = dict(self.parameters_to_tuples(header_params,
115
+ collection_formats))
116
+
117
+ # path parameters
118
+ if path_params:
119
+ path_params = self.sanitize_for_serialization(path_params)
120
+ path_params = self.parameters_to_tuples(path_params,
121
+ collection_formats)
122
+ for k, v in path_params:
123
+ # specified safe chars, encode everything
124
+ resource_path = resource_path.replace(
125
+ '{%s}' % k,
126
+ quote(str(v), safe=config.safe_chars_for_path_param)
127
+ )
128
+
129
+ # query parameters
130
+ if query_params:
131
+ query_params = self.sanitize_for_serialization(query_params)
132
+ query_params = self.parameters_to_tuples(query_params,
133
+ collection_formats)
134
+
135
+ # post parameters
136
+ if post_params or files:
137
+ post_params = self.prepare_post_parameters(post_params, files)
138
+ post_params = self.sanitize_for_serialization(post_params)
139
+ post_params = self.parameters_to_tuples(post_params,
140
+ collection_formats)
141
+
142
+ # auth setting
143
+ self.update_params_for_auth(header_params, query_params, auth_settings)
144
+
145
+ # body
146
+ if body:
147
+ body = self.sanitize_for_serialization(body)
148
+
149
+ # request url
150
+ url = self.configuration.host + resource_path
151
+
152
+ # perform request and return response
153
+ response_data = self.request(
154
+ method, url, query_params=query_params, headers=header_params,
155
+ post_params=post_params, body=body,
156
+ _preload_content=_preload_content,
157
+ _request_timeout=_request_timeout)
158
+ self.last_response = response_data
159
+
160
+ return_data = response_data
161
+ if _preload_content:
162
+ # deserialize response data
163
+ if response_type:
164
+ return_data = self.deserialize(response_data, response_type)
165
+ else:
166
+ return_data = None
167
+
168
+ if _return_http_data_only:
169
+ return (return_data)
170
+ else:
171
+ return (return_data, response_data.status,
172
+ response_data.getheaders())
173
+
174
+ def sanitize_for_serialization(self, obj):
175
+ """Builds a JSON POST object.
176
+
177
+ If obj is None, return None.
178
+ If obj is str, int, long, float, bool, return directly.
179
+ If obj is datetime.datetime, datetime.date
180
+ convert to string in iso8601 format.
181
+ If obj is list, sanitize each element in the list.
182
+ If obj is dict, return the dict.
183
+ If obj is swagger model, return the properties dict.
184
+
185
+ :param obj: The data to serialize.
186
+ :return: The serialized form of data.
187
+ """
188
+ if obj is None:
189
+ return None
190
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
191
+ return obj
192
+ elif isinstance(obj, list):
193
+ return [self.sanitize_for_serialization(sub_obj)
194
+ for sub_obj in obj]
195
+ elif isinstance(obj, tuple):
196
+ return tuple(self.sanitize_for_serialization(sub_obj)
197
+ for sub_obj in obj)
198
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
199
+ return obj.isoformat()
200
+
201
+ if isinstance(obj, dict):
202
+ obj_dict = obj
203
+ else:
204
+ # Convert model obj to dict except
205
+ # attributes `swagger_types`, `attribute_map`
206
+ # and attributes which value is not None.
207
+ # Convert attribute name to json key in
208
+ # model definition for request.
209
+ obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
210
+ for attr, _ in obj.swagger_types.items()
211
+ if getattr(obj, attr) is not None}
212
+
213
+ return {key: self.sanitize_for_serialization(val)
214
+ for key, val in obj_dict.items()}
215
+
216
+ def deserialize(self, response, response_type):
217
+ """Deserializes response into an object.
218
+
219
+ :param response: RESTResponse object to be deserialized.
220
+ :param response_type: class literal for
221
+ deserialized object, or string of class name.
222
+
223
+ :return: deserialized object.
224
+ """
225
+ # handle file downloading
226
+ # save response body into a tmp file and return the instance
227
+ if response_type == "file":
228
+ return self.__deserialize_file(response)
229
+
230
+ # fetch data from response object
231
+ try:
232
+ data = json.loads(response.data)
233
+ data=json.dumps(data, indent=2)
234
+ # print("response data:",json.dumps(data, indent=2))
235
+ # print("=============================================================")
236
+ except ValueError:
237
+ data = response.data
238
+ # commented for no need to deserilize the response form the server
239
+ # return self.__deserialize(data, response_type)
240
+ return data;
241
+
242
+ def __deserialize(self, data, klass):
243
+ """Deserializes dict, list, str into an object.
244
+
245
+ :param data: dict, list or str.
246
+ :param klass: class literal, or string of class name.
247
+
248
+ :return: object.
249
+ """
250
+ if data is None:
251
+ return None
252
+
253
+ if type(klass) == str:
254
+ if klass.startswith('list['):
255
+ sub_kls = re.match(r'list\[(.*)\]', klass).group(1)
256
+ return [self.__deserialize(sub_data, sub_kls)
257
+ for sub_data in data]
258
+
259
+ if klass.startswith('dict('):
260
+ sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2)
261
+ return {k: self.__deserialize(v, sub_kls)
262
+ for k, v in data.items()}
263
+
264
+ # convert str to class
265
+ if klass in self.NATIVE_TYPES_MAPPING:
266
+ klass = self.NATIVE_TYPES_MAPPING[klass]
267
+ else:
268
+ klass = None #getattr(swagger_client.models, klass)
269
+
270
+ if klass in self.PRIMITIVE_TYPES:
271
+ return self.__deserialize_primitive(data, klass)
272
+ elif klass == object:
273
+ return self.__deserialize_object(data)
274
+ elif klass == datetime.date:
275
+ return self.__deserialize_date(data)
276
+ elif klass == datetime.datetime:
277
+ return self.__deserialize_datatime(data)
278
+ else:
279
+ return self.__deserialize_model(data, klass)
280
+
281
+ def call_api(self, resource_path, method,
282
+ path_params=None, query_params=None, header_params=None,
283
+ body=None, post_params=None, files=None,
284
+ response_type=None, auth_settings=None, async_req=None,
285
+ _return_http_data_only=None, collection_formats=None,
286
+ _preload_content=True, _request_timeout=None):
287
+ """Makes the HTTP request (synchronous) and returns deserialized data.
288
+
289
+ To make an async request, set the async_req parameter.
290
+
291
+ :param resource_path: Path to method endpoint.
292
+ :param method: Method to call.
293
+ :param path_params: Path parameters in the url.
294
+ :param query_params: Query parameters in the url.
295
+ :param header_params: Header parameters to be
296
+ placed in the request header.
297
+ :param body: Request body.
298
+ :param post_params dict: Request post form parameters,
299
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
300
+ :param auth_settings list: Auth Settings names for the request.
301
+ :param response: Response data type.
302
+ :param files dict: key -> filename, value -> filepath,
303
+ for `multipart/form-data`.
304
+ :param async_req bool: execute request asynchronously
305
+ :param _return_http_data_only: response data without head status code
306
+ and headers
307
+ :param collection_formats: dict of collection formats for path, query,
308
+ header, and post parameters.
309
+ :param _preload_content: if False, the urllib3.HTTPResponse object will
310
+ be returned without reading/decoding response
311
+ data. Default is True.
312
+ :param _request_timeout: timeout setting for this request. If one
313
+ number provided, it will be total request
314
+ timeout. It can also be a pair (tuple) of
315
+ (connection, read) timeouts.
316
+ :return:
317
+ If async_req parameter is True,
318
+ the request will be called asynchronously.
319
+ The method will return the request thread.
320
+ If parameter async_req is False or missing,
321
+ then the method will return the response directly.
322
+ """
323
+ if not async_req:
324
+ return self.__call_api(resource_path, method,
325
+ path_params, query_params, header_params,
326
+ body, post_params, files,
327
+ response_type, auth_settings,
328
+ _return_http_data_only, collection_formats,
329
+ _preload_content, _request_timeout)
330
+ else:
331
+ thread = self.pool.apply_async(self.__call_api, (resource_path,
332
+ method, path_params, query_params,
333
+ header_params, body,
334
+ post_params, files,
335
+ response_type, auth_settings,
336
+ _return_http_data_only,
337
+ collection_formats,
338
+ _preload_content, _request_timeout))
339
+ return thread
340
+
341
+ def request(self, method, url, query_params=None, headers=None,
342
+ post_params=None, body=None, _preload_content=True,
343
+ _request_timeout=None):
344
+ """Makes the HTTP request using RESTClient."""
345
+ if method == "GET":
346
+ return self.rest_client.GET(url,
347
+ query_params=query_params,
348
+ _preload_content=_preload_content,
349
+ _request_timeout=_request_timeout,
350
+ headers=headers)
351
+ elif method == "HEAD":
352
+ return self.rest_client.HEAD(url,
353
+ query_params=query_params,
354
+ _preload_content=_preload_content,
355
+ _request_timeout=_request_timeout,
356
+ headers=headers)
357
+ elif method == "OPTIONS":
358
+ return self.rest_client.OPTIONS(url,
359
+ query_params=query_params,
360
+ headers=headers,
361
+ post_params=post_params,
362
+ _preload_content=_preload_content,
363
+ _request_timeout=_request_timeout,
364
+ body=body)
365
+ elif method == "POST":
366
+ return self.rest_client.POST(url,
367
+ query_params=query_params,
368
+ headers=headers,
369
+ post_params=post_params,
370
+ _preload_content=_preload_content,
371
+ _request_timeout=_request_timeout,
372
+ body=body)
373
+ elif method == "PUT":
374
+ return self.rest_client.PUT(url,
375
+ query_params=query_params,
376
+ headers=headers,
377
+ post_params=post_params,
378
+ _preload_content=_preload_content,
379
+ _request_timeout=_request_timeout,
380
+ body=body)
381
+ elif method == "PATCH":
382
+ return self.rest_client.PATCH(url,
383
+ query_params=query_params,
384
+ headers=headers,
385
+ post_params=post_params,
386
+ _preload_content=_preload_content,
387
+ _request_timeout=_request_timeout,
388
+ body=body)
389
+ elif method == "DELETE":
390
+ return self.rest_client.DELETE(url,
391
+ query_params=query_params,
392
+ headers=headers,
393
+ _preload_content=_preload_content,
394
+ _request_timeout=_request_timeout,
395
+ body=body)
396
+ else:
397
+ raise ValueError(
398
+ "http method must be `GET`, `HEAD`, `OPTIONS`,"
399
+ " `POST`, `PATCH`, `PUT` or `DELETE`."
400
+ )
401
+
402
+ def parameters_to_tuples(self, params, collection_formats):
403
+ """Get parameters as list of tuples, formatting collections.
404
+
405
+ :param params: Parameters as dict or list of two-tuples
406
+ :param dict collection_formats: Parameter collection formats
407
+ :return: Parameters as list of tuples, collections formatted
408
+ """
409
+ new_params = []
410
+ if collection_formats is None:
411
+ collection_formats = {}
412
+ for k, v in (params.items() if isinstance(params, dict) else params): # noqa: E501
413
+ if k in collection_formats:
414
+ collection_format = collection_formats[k]
415
+ if collection_format == 'multi':
416
+ new_params.extend((k, value) for value in v)
417
+ else:
418
+ if collection_format == 'ssv':
419
+ delimiter = ' '
420
+ elif collection_format == 'tsv':
421
+ delimiter = '\t'
422
+ elif collection_format == 'pipes':
423
+ delimiter = '|'
424
+ else: # csv is the default
425
+ delimiter = ','
426
+ new_params.append(
427
+ (k, delimiter.join(str(value) for value in v)))
428
+ else:
429
+ new_params.append((k, v))
430
+ return new_params
431
+
432
+ def prepare_post_parameters(self, post_params=None, files=None):
433
+ """Builds form parameters.
434
+
435
+ :param post_params: Normal form parameters.
436
+ :param files: File parameters.
437
+ :return: Form parameters with files.
438
+ """
439
+ params = []
440
+
441
+ if post_params:
442
+ params = post_params
443
+
444
+ if files:
445
+ for k, v in files.items():
446
+ if not v:
447
+ continue
448
+ file_names = v if type(v) is list else [v]
449
+ for n in file_names:
450
+ with open(n, 'rb') as f:
451
+ filename = os.path.basename(f.name)
452
+ filedata = f.read()
453
+ mimetype = (mimetypes.guess_type(filename)[0] or
454
+ 'application/octet-stream')
455
+ params.append(
456
+ tuple([k, tuple([filename, filedata, mimetype])]))
457
+
458
+ return params
459
+
460
+ def select_header_accept(self, accepts):
461
+ """Returns `Accept` based on an array of accepts provided.
462
+
463
+ :param accepts: List of headers.
464
+ :return: Accept (e.g. application/json).
465
+ """
466
+ if not accepts:
467
+ return
468
+
469
+ accepts = [x.lower() for x in accepts]
470
+
471
+ if 'application/json' in accepts:
472
+ return 'application/json'
473
+ else:
474
+ return ', '.join(accepts)
475
+
476
+ def select_header_content_type(self, content_types):
477
+ """Returns `Content-Type` based on an array of content_types provided.
478
+
479
+ :param content_types: List of content-types.
480
+ :return: Content-Type (e.g. application/json).
481
+ """
482
+ if not content_types:
483
+ return 'application/json'
484
+
485
+ content_types = [x.lower() for x in content_types]
486
+
487
+ if 'application/json' in content_types or '*/*' in content_types:
488
+ return 'application/json'
489
+ else:
490
+ return content_types[0]
491
+
492
+ def update_params_for_auth(self, headers, querys, auth_settings):
493
+ """Updates header and query params based on authentication setting.
494
+
495
+ :param headers: Header parameters dict to be updated.
496
+ :param querys: Query parameters tuple list to be updated.
497
+ :param auth_settings: Authentication setting identifiers list.
498
+ """
499
+ if not auth_settings:
500
+ return
501
+
502
+ for auth in auth_settings:
503
+ auth_setting = self.configuration.auth_settings().get(auth)
504
+ if auth_setting:
505
+ if not auth_setting['value']:
506
+ continue
507
+ elif auth_setting['in'] == 'header':
508
+ headers[auth_setting['key']] = auth_setting['value']
509
+ elif auth_setting['in'] == 'query':
510
+ querys.append((auth_setting['key'], auth_setting['value']))
511
+ else:
512
+ raise ValueError(
513
+ 'Authentication token must be in `query` or `header`'
514
+ )
515
+
516
+ def __deserialize_file(self, response):
517
+ """Deserializes body to file
518
+
519
+ Saves response body into a file in a temporary folder,
520
+ using the filename from the `Content-Disposition` header if provided.
521
+
522
+ :param response: RESTResponse.
523
+ :return: file path.
524
+ """
525
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
526
+ os.close(fd)
527
+ os.remove(path)
528
+
529
+ content_disposition = response.getheader("Content-Disposition")
530
+ if content_disposition:
531
+ filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
532
+ content_disposition).group(1)
533
+ path = os.path.join(os.path.dirname(path), filename)
534
+
535
+ with open(path, "wb") as f:
536
+ f.write(response.data)
537
+
538
+ return path
539
+
540
+ def __deserialize_primitive(self, data, klass):
541
+ """Deserializes string to primitive type.
542
+
543
+ :param data: str.
544
+ :param klass: class literal.
545
+
546
+ :return: int, long, float, str, bool.
547
+ """
548
+ try:
549
+ return klass(data)
550
+ except UnicodeEncodeError:
551
+ return str(data)
552
+ except TypeError:
553
+ return data
554
+
555
+ def __deserialize_object(self, value):
556
+ """Return a original value.
557
+
558
+ :return: object.
559
+ """
560
+ return value
561
+
562
+ def __deserialize_date(self, string):
563
+ """Deserializes string to date.
564
+
565
+ :param string: str.
566
+ :return: date.
567
+ """
568
+ try:
569
+ from dateutil.parser import parse
570
+ return parse(string).date()
571
+ except ImportError:
572
+ return string
573
+ except ValueError:
574
+ raise rest.ApiException(
575
+ status=0,
576
+ reason="Failed to parse `{0}` as date object".format(string)
577
+ )
578
+
579
+ def __deserialize_datatime(self, string):
580
+ """Deserializes string to datetime.
581
+
582
+ The string should be in iso8601 datetime format.
583
+
584
+ :param string: str.
585
+ :return: datetime.
586
+ """
587
+ try:
588
+ from dateutil.parser import parse
589
+ return parse(string)
590
+ except ImportError:
591
+ return string
592
+ except ValueError:
593
+ raise rest.ApiException(
594
+ status=0,
595
+ reason=(
596
+ "Failed to parse `{0}` as datetime object"
597
+ .format(string)
598
+ )
599
+ )
600
+
601
+ def __hasattr(self, object, name):
602
+ return name in object.__class__.__dict__
603
+
604
+ def __deserialize_model(self, data, klass):
605
+ """Deserializes list or dict to model.
606
+
607
+ :param data: dict, list.
608
+ :param klass: class literal.
609
+ :return: model object.
610
+ """
611
+
612
+ if (not klass.swagger_types and
613
+ not self.__hasattr(klass, 'get_real_child_model')):
614
+ return data
615
+
616
+ kwargs = {}
617
+ if klass.swagger_types is not None:
618
+ for attr, attr_type in klass.swagger_types.items():
619
+ if (data is not None and
620
+ klass.attribute_map[attr] in data and
621
+ isinstance(data, (list, dict))):
622
+ value = data[klass.attribute_map[attr]]
623
+ kwargs[attr] = self.__deserialize(value, attr_type)
624
+
625
+ instance = klass(**kwargs)
626
+
627
+ if (isinstance(instance, dict) and
628
+ klass.swagger_types is not None and
629
+ isinstance(data, dict)):
630
+ for key, value in data.items():
631
+ if key not in klass.swagger_types:
632
+ instance[key] = value
633
+ if self.__hasattr(instance, 'get_real_child_model'):
634
+ klass_name = instance.get_real_child_model(data)
635
+ if klass_name:
636
+ instance = self.__deserialize(data, klass_name)
637
+ return instance