天择加密量化开放框架下载
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

369 lines
12 KiB

1 year ago
  1. # coding: utf-8
  2. """
  3. Gate API v4
  4. Welcome to Gate.io API APIv4 provides spot, margin and futures trading operations. There are public APIs to retrieve the real-time market statistics, and private APIs which needs authentication to trade on user's behalf. # noqa: E501
  5. Contact: support@mail.gate.io
  6. Generated by: https://openapi-generator.tech
  7. """
  8. from __future__ import absolute_import
  9. import copy
  10. import logging
  11. import multiprocessing
  12. import sys
  13. import urllib3
  14. import six
  15. from six.moves import http_client as httplib
  16. class Configuration(object):
  17. """NOTE: This class is auto generated by OpenAPI Generator
  18. Ref: https://openapi-generator.tech
  19. Do not edit the class manually.
  20. :param host: Base url
  21. :param key: APIv4 key
  22. :param secret: APIv4 secret
  23. :param username: Username for HTTP basic authentication
  24. :param password: Password for HTTP basic authentication
  25. :param discard_unknown_keys: Boolean value indicating whether to discard
  26. unknown properties. A server may send a response that includes additional
  27. properties that are not known by the client in the following scenarios:
  28. 1. The OpenAPI document is incomplete, i.e. it does not match the server
  29. implementation.
  30. 2. The client was generated using an older version of the OpenAPI document
  31. and the server has been upgraded since then.
  32. If a schema in the OpenAPI document defines the additionalProperties attribute,
  33. then all undeclared properties received by the server are injected into the
  34. additional properties map. In that case, there are undeclared properties, and
  35. nothing to discard.
  36. :Example:
  37. You can set the APIv4 key and secret like:
  38. conf = gate_api.Configuration(
  39. key='example_key'
  40. secret='example_secret'
  41. )
  42. The following headers will be added to the HTTP request:
  43. KEY: example_key
  44. SIGN: generated_signature_using_example_secret
  45. Timestamp: request_timestamp
  46. """
  47. _default = None
  48. def __init__(
  49. self,
  50. host="https://api.gateio.ws/api/v4",
  51. key=None,
  52. secret=None,
  53. username=None,
  54. password=None,
  55. discard_unknown_keys=False,
  56. ):
  57. """Constructor"""
  58. self.host = host
  59. """Default Base url
  60. """
  61. self.temp_folder_path = None
  62. """Temp file folder for downloading files
  63. """
  64. # Authentication Settings
  65. # Init APIv4 authentication key and secret
  66. self.key = key
  67. """API key for APIv4 authentication
  68. """
  69. self.secret = secret
  70. """API secret for APIv4 authentication
  71. """
  72. self.username = username
  73. """Username for HTTP basic authentication
  74. """
  75. self.password = password
  76. """Password for HTTP basic authentication
  77. """
  78. self.discard_unknown_keys = discard_unknown_keys
  79. self.logger = {}
  80. """Logging Settings
  81. """
  82. self.logger["package_logger"] = logging.getLogger("gate_api")
  83. self.logger["urllib3_logger"] = logging.getLogger("urllib3")
  84. self.logger_format = '%(asctime)s %(levelname)s %(message)s'
  85. """Log format
  86. """
  87. self.logger_stream_handler = None
  88. """Log stream handler
  89. """
  90. self.logger_file_handler = None
  91. """Log file handler
  92. """
  93. self.logger_file = None
  94. """Debug file location
  95. """
  96. self.debug = False
  97. """Debug switch
  98. """
  99. self.verify_ssl = True
  100. """SSL/TLS verification
  101. Set this to false to skip verifying SSL certificate when calling API
  102. from https server.
  103. """
  104. self.ssl_ca_cert = None
  105. """Set this to customize the certificate file to verify the peer.
  106. """
  107. self.cert_file = None
  108. """client certificate file
  109. """
  110. self.key_file = None
  111. """client key file
  112. """
  113. self.assert_hostname = None
  114. """Set this to True/False to enable/disable SSL hostname verification.
  115. """
  116. self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
  117. """urllib3 connection pool's maximum number of connections saved
  118. per pool. urllib3 uses 1 connection as default value, but this is
  119. not the best value when you are making a lot of possibly parallel
  120. requests to the same host, which is often the case here.
  121. cpu_count * 5 is used as default value to increase performance.
  122. """
  123. self.proxy = None
  124. """Proxy URL
  125. """
  126. self.proxy_headers = None
  127. """Proxy headers
  128. """
  129. self.safe_chars_for_path_param = ''
  130. """Safe chars for path_param
  131. """
  132. self.retries = None
  133. """Adding retries to override urllib3 default value 3
  134. """
  135. # Disable client side validation
  136. self.client_side_validation = True
  137. def __deepcopy__(self, memo):
  138. cls = self.__class__
  139. result = cls.__new__(cls)
  140. memo[id(self)] = result
  141. for k, v in self.__dict__.items():
  142. if k not in ('logger', 'logger_file_handler'):
  143. setattr(result, k, copy.deepcopy(v, memo))
  144. # shallow copy of loggers
  145. result.logger = copy.copy(self.logger)
  146. # use setters to configure loggers
  147. result.logger_file = self.logger_file
  148. result.debug = self.debug
  149. return result
  150. def __setattr__(self, name, value):
  151. object.__setattr__(self, name, value)
  152. @classmethod
  153. def set_default(cls, default):
  154. """Set default instance of configuration.
  155. It stores default configuration, which can be
  156. returned by get_default_copy method.
  157. :param default: object of Configuration
  158. """
  159. cls._default = copy.deepcopy(default)
  160. @classmethod
  161. def get_default_copy(cls):
  162. """Return new instance of configuration.
  163. This method returns newly created, based on default constructor,
  164. object of Configuration class or returns a copy of default
  165. configuration passed by the set_default method.
  166. :return: The configuration object.
  167. """
  168. if cls._default is not None:
  169. return copy.deepcopy(cls._default)
  170. return Configuration()
  171. @property
  172. def logger_file(self):
  173. """The logger file.
  174. If the logger_file is None, then add stream handler and remove file
  175. handler. Otherwise, add file handler and remove stream handler.
  176. :return: The logger_file path.
  177. """
  178. return self.__logger_file
  179. @logger_file.setter
  180. def logger_file(self, value):
  181. """The logger file.
  182. If the logger_file is None, then add stream handler and remove file
  183. handler. Otherwise, add file handler and remove stream handler.
  184. :param value: The logger_file path.
  185. :type: str
  186. """
  187. self.__logger_file = value
  188. if self.__logger_file:
  189. # If set logging file,
  190. # then add file handler and remove stream handler.
  191. self.logger_file_handler = logging.FileHandler(self.__logger_file)
  192. self.logger_file_handler.setFormatter(self.logger_formatter)
  193. for _, logger in six.iteritems(self.logger):
  194. logger.addHandler(self.logger_file_handler)
  195. @property
  196. def debug(self):
  197. """Debug status
  198. :return: The debug status, True or False.
  199. """
  200. return self.__debug
  201. @debug.setter
  202. def debug(self, value):
  203. """Debug status
  204. :param value: The debug status, True or False.
  205. :type: bool
  206. """
  207. self.__debug = value
  208. if self.__debug:
  209. # if debug status is True, turn on debug logging
  210. for _, logger in six.iteritems(self.logger):
  211. logger.setLevel(logging.DEBUG)
  212. # turn on httplib debug
  213. httplib.HTTPConnection.debuglevel = 1
  214. else:
  215. # if debug status is False, turn off debug logging,
  216. # setting log level to default `logging.WARNING`
  217. for _, logger in six.iteritems(self.logger):
  218. logger.setLevel(logging.WARNING)
  219. # turn off httplib debug
  220. httplib.HTTPConnection.debuglevel = 0
  221. @property
  222. def logger_format(self):
  223. """The logger format.
  224. The logger_formatter will be updated when sets logger_format.
  225. :return: The format string.
  226. """
  227. return self.__logger_format
  228. @logger_format.setter
  229. def logger_format(self, value):
  230. """The logger format.
  231. The logger_formatter will be updated when sets logger_format.
  232. :param value: The format string.
  233. :type: str
  234. """
  235. self.__logger_format = value
  236. self.logger_formatter = logging.Formatter(self.__logger_format)
  237. def get_basic_auth_token(self):
  238. """Gets HTTP basic authentication header (string).
  239. :return: The token for basic HTTP authentication.
  240. """
  241. username = ""
  242. if self.username is not None:
  243. username = self.username
  244. password = ""
  245. if self.password is not None:
  246. password = self.password
  247. return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization')
  248. def auth_settings(self):
  249. """Gets Auth Settings dict for api client.
  250. :return: The Auth Settings information dict.
  251. """
  252. auth = {}
  253. if self.key is not None and self.secret is not None:
  254. auth['apiv4'] = {
  255. 'type': 'apiv4',
  256. 'in': 'header',
  257. 'key': 'SIGN',
  258. }
  259. return auth
  260. def to_debug_report(self):
  261. """Gets the essential information for debugging.
  262. :return: The report for debugging.
  263. """
  264. return (
  265. "Python SDK Debug Report:\n"
  266. "OS: {env}\n"
  267. "Python Version: {pyversion}\n"
  268. "Version of the API: 4.42.0\n"
  269. "SDK Package Version: 4.42.0".format(env=sys.platform, pyversion=sys.version)
  270. )
  271. def get_host_settings(self):
  272. """Gets an array of host settings
  273. :return: An array of host settings
  274. """
  275. return [
  276. {
  277. 'url': "https://api.gateio.ws/api/v4",
  278. 'description': "Real Trading",
  279. },
  280. {
  281. 'url': "https://fx-api-testnet.gateio.ws/api/v4",
  282. 'description': "TestNet Trading",
  283. },
  284. ]
  285. def get_host_from_settings(self, index, variables=None):
  286. """Gets host URL based on the index and variables
  287. :param index: array index of the host settings
  288. :param variables: hash of variable and the corresponding value
  289. :return: URL based on host settings
  290. """
  291. variables = {} if variables is None else variables
  292. servers = self.get_host_settings()
  293. try:
  294. server = servers[index]
  295. except IndexError:
  296. raise ValueError(
  297. "Invalid index {0} when selecting the host settings. "
  298. "Must be less than {1}".format(index, len(servers))
  299. )
  300. url = server['url']
  301. # go through variables and replace placeholders
  302. for variable_name, variable in server['variables'].items():
  303. used_value = variables.get(variable_name, variable['default_value'])
  304. if 'enum_values' in variable and used_value not in variable['enum_values']:
  305. raise ValueError(
  306. "The variable `{0}` in the host URL has invalid value "
  307. "{1}. Must be {2}.".format(variable_name, variables[variable_name], variable['enum_values'])
  308. )
  309. url = url.replace("{" + variable_name + "}", used_value)
  310. return url