binance-sdk-c2c 1.0.0__tar.gz

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.
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 - 2025-07-17
4
+
5
+ - Initial release
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Binance
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.1
2
+ Name: binance-sdk-c2c
3
+ Version: 1.0.0
4
+ Summary: Official Binance C2C SDK - A lightweight library that provides a convenient interface to Binance's C2C REST API
5
+ License: MIT
6
+ Author: Binance
7
+ Requires-Python: >=3.9,<=3.13
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Provides-Extra: dev
16
+ Requires-Dist: aiohttp (>=3.9,<4.0)
17
+ Requires-Dist: binance-common (==1.0.0)
18
+ Requires-Dist: black (>=25.1.0,<26.0.0)
19
+ Requires-Dist: pycryptodome (>=3.17,<4.0)
20
+ Requires-Dist: pydantic (>=2.10.0)
21
+ Requires-Dist: pytest (>=6.2.5) ; extra == "dev"
22
+ Requires-Dist: requests (>=2.31.0)
23
+ Requires-Dist: ruff (>=0.12.0,<0.13.0)
24
+ Requires-Dist: websocket-client (>=1.6.3)
25
+ Requires-Dist: websockets (>=15.0.1,<16.0.0)
26
+ Description-Content-Type: text/markdown
27
+
28
+ # Binance Python C2C SDK
29
+
30
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/binance/binance-connector-python/ci-c2c.yml)](https://github.com/binance/binance-connector-python/actions)
31
+ [![Open Issues](https://img.shields.io/github/issues/binance/binance-connector-python)](https://github.com/binance/binance-connector-python/issues)
32
+ [![Code Style: Black](https://img.shields.io/badge/code_style-black-black)](https://black.readthedocs.io/en/stable/)
33
+ [![PyPI version](https://img.shields.io/pypi/v/binance-sdk-c2c)](https://pypi.python.org/pypi/binance-sdk-c2c)
34
+ [![PyPI Downloads](https://img.shields.io/pypi/dm/binance-sdk-c2c.svg)](https://pypi.org/project/binance-sdk-c2c/)
35
+ [![Python version](https://img.shields.io/pypi/pyversions/binance-connector)](https://www.python.org/downloads/)
36
+ [![Known Vulnerabilities](https://img.shields.io/badge/security-scanned-brightgreen)](https://github.com/binance/binance-connector-python/security)
37
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
38
+
39
+ This is a client library for the Binance C2C SDK API, enabling developers to interact programmatically with Binance's C2C trading platform. The library provides tools to query Fiat transaction history through the REST API:
40
+ - [REST API](./src/binance_sdk_c2c/rest_api/rest_api.py)
41
+
42
+ ## Table of Contents
43
+
44
+ - [Supported Features](#supported-features)
45
+ - [Installation](#installation)
46
+ - [Documentation](#documentation)
47
+ - [REST APIs](#rest-apis)
48
+ - [Testing](#testing)
49
+ - [Migration Guide](#migration-guide)
50
+ - [Contributing](#contributing)
51
+ - [Licence](#licence)
52
+
53
+ ## Supported Features
54
+
55
+ - REST API Endpoints:
56
+ - `/sapi/v1/c2c/*`
57
+ - Inclusion of test cases and examples for quick onboarding.
58
+
59
+ ## Installation
60
+
61
+ To use this library, ensure your environment is running Python version **3.9** or later.
62
+
63
+ ```bash
64
+ pip install binance-sdk-c2c
65
+ ```
66
+
67
+ ## Documentation
68
+
69
+ For detailed information, refer to the [Binance API Documentation](https://developers.binance.com/docs/c2c/Introduction).
70
+
71
+ ### REST APIs
72
+
73
+ All REST API endpoints are available through the [`rest_api`](./src/binance_sdk_c2c/rest_api/rest_api.py) module. The REST API enables you to fetch market data, manage trades, and access account information. Note that some endpoints require authentication using your Binance API credentials.
74
+
75
+ ```python
76
+ from binance_common.configuration import ConfigurationRestAPI
77
+ from binance_common.constants import C2C_REST_API_PROD_URL
78
+ from binance_sdk_c2c.c2c import C2C
79
+ from binance_sdk_c2c.rest_api.models import GetC2CTradeHistoryResponse
80
+
81
+ logging.basicConfig(level=logging.INFO)
82
+ configuration = ConfigurationRestAPI(api_key="your-api-key", api_secret="your-api-secret", base_path=C2C_REST_API_PROD_URL)
83
+
84
+ client = C2C(config_rest_api=configuration)
85
+
86
+ try:
87
+ response = client.rest_api.get_c2_c_trade_history()
88
+
89
+ data: GetC2CTradeHistoryResponse = response.data()
90
+ logging.info(f"get_c2_c_trade_history() response: {data}")
91
+ except Exception as e:
92
+ logging.error(f"get_c2_c_trade_history() error: {e}")
93
+ ```
94
+
95
+ More examples can be found in the [`examples/rest_api`](./examples/rest_api/) folder.
96
+
97
+ #### Configuration Options
98
+
99
+ The REST API supports the following advanced configuration options:
100
+
101
+ - `timeout`: Timeout for requests in milliseconds (default: 1000 ms).
102
+ - `proxy`: Proxy configuration:
103
+ - `host`: Proxy server hostname.
104
+ - `port`: Proxy server port.
105
+ - `protocol`: Proxy protocol (http or https).
106
+ - `auth`: Proxy authentication credentials:
107
+ - `username`: Proxy username.
108
+ - `password`: Proxy password.
109
+ - `keep_alive`: Enable HTTP keep-alive (default: true).
110
+ - `compression`: Enable response compression (default: true).
111
+ - `retries`: Number of retry attempts for failed requests (default: 3).
112
+ - `backoff`: Delay in milliseconds between retries (default: 1000 ms).
113
+ - `https_agent`: Custom HTTPS agent for advanced TLS configuration.
114
+ - `private_key`: RSA or ED25519 private key for authentication.
115
+ - `private_key_passphrase`: Passphrase for the private key, if encrypted.
116
+
117
+ ##### Timeout
118
+
119
+ You can configure a timeout for requests in milliseconds. If the request exceeds the specified timeout, it will be aborted. See the [Timeout example](./docs/rest_api/timeout.md) for detailed usage.
120
+
121
+ ##### Proxy
122
+
123
+ The REST API supports HTTP/HTTPS proxy configurations. See the [Proxy example](./docs/rest_api/proxy.md) for detailed usage.
124
+
125
+ ##### Keep-Alive
126
+
127
+ Enable HTTP keep-alive for persistent connections. See the [Keep-Alive example](./docs/rest_api/keepAlive.md) for detailed usage.
128
+
129
+ ##### Compression
130
+
131
+ Enable or disable response compression. See the [Compression example](./docs/rest_api/compression.md) for detailed usage.
132
+
133
+ ##### Retries
134
+
135
+ Configure the number of retry attempts and delay in milliseconds between retries for failed requests. See the [Retries example](./docs/rest_api/retries.md) for detailed usage.
136
+
137
+ ##### HTTPS Agent
138
+
139
+ Customize the HTTPS agent for advanced TLS configurations. See the [HTTPS Agent example](./docs/rest_api/httpsAgent.md) for detailed usage.
140
+
141
+ ##### Key Pair Based Authentication
142
+
143
+ The REST API supports key pair-based authentication for secure communication. You can use `RSA` or `ED25519` keys for signing requests. See the [Key Pair Based Authentication example](./docs/rest_api/key-pair-authentication.md) for detailed usage.
144
+
145
+ ##### Certificate Pinning
146
+
147
+ To enhance security, you can use certificate pinning with the `https_agent` option in the configuration. This ensures the client only communicates with servers using specific certificates. See the [Certificate Pinning example](./docs/rest_api/certificate-pinning.md) for detailed usage.
148
+
149
+ #### Error Handling
150
+
151
+ The REST API provides detailed error types to help you handle issues effectively:
152
+
153
+ - `ClientError`: Represents an error that occurred in the SDK client.
154
+ - `RequiredError`: Thrown when a required parameter is missing or undefined.
155
+ - `UnauthorizedError`: Indicates missing or invalid authentication credentials.
156
+ - `ForbiddenError`: Access to the requested resource is forbidden.
157
+ - `TooManyRequestsError`: Rate limit exceeded.
158
+ - `RateLimitBanError`: IP address banned for exceeding rate limits.
159
+ - `ServerError`: Internal server error, optionally includes a status code.
160
+ - `NetworkError`: Issues with network connectivity.
161
+ - `NotFoundError`: Resource not found.
162
+ - `BadRequestError`: Invalid request or one that cannot be served.
163
+
164
+ See the [Error Handling example](./docs/rest_api/error-handling.md) for detailed usage.
165
+
166
+ If `base_path` is not provided, it defaults to `https://api.binance.com`.
167
+
168
+ ## Testing
169
+
170
+ To run the tests, ensure you have [Poetry](https://python-poetry.org/) installed, then execute the following commands:
171
+
172
+ ```bash
173
+ poetry install
174
+ poetry run pytest ./tests
175
+ ```
176
+
177
+ The tests cover:
178
+ * REST API endpoints
179
+ * Error handling
180
+ * Edge cases
181
+
182
+ ## Migration Guide
183
+
184
+ If you are upgrading to the new modularized structure, refer to the [Migration Guide](./docs/migration_guide_c2c_sdk.md) for detailed steps.
185
+
186
+ ## Contributing
187
+
188
+ Contributions are welcome!
189
+
190
+ Since this repository contains auto-generated code, we encourage you to start by opening a GitHub issue to discuss your ideas or suggest improvements. This helps ensure that changes align with the project's goals and auto-generation processes.
191
+
192
+ To contribute:
193
+
194
+ 1. Open a GitHub issue describing your suggestion or the bug you've identified.
195
+ 2. If it's determined that changes are necessary, the maintainers will merge the changes into the main branch.
196
+
197
+ Please ensure that all tests pass if you're making a direct contribution. Submit a pull request only after discussing and confirming the change.
198
+
199
+ Thank you for your contributions!
200
+
201
+ ## Licence
202
+
203
+ This project is licensed under the MIT License. See the [LICENCE](./LICENCE) file for details.
204
+
@@ -0,0 +1,176 @@
1
+ # Binance Python C2C SDK
2
+
3
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/binance/binance-connector-python/ci-c2c.yml)](https://github.com/binance/binance-connector-python/actions)
4
+ [![Open Issues](https://img.shields.io/github/issues/binance/binance-connector-python)](https://github.com/binance/binance-connector-python/issues)
5
+ [![Code Style: Black](https://img.shields.io/badge/code_style-black-black)](https://black.readthedocs.io/en/stable/)
6
+ [![PyPI version](https://img.shields.io/pypi/v/binance-sdk-c2c)](https://pypi.python.org/pypi/binance-sdk-c2c)
7
+ [![PyPI Downloads](https://img.shields.io/pypi/dm/binance-sdk-c2c.svg)](https://pypi.org/project/binance-sdk-c2c/)
8
+ [![Python version](https://img.shields.io/pypi/pyversions/binance-connector)](https://www.python.org/downloads/)
9
+ [![Known Vulnerabilities](https://img.shields.io/badge/security-scanned-brightgreen)](https://github.com/binance/binance-connector-python/security)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
11
+
12
+ This is a client library for the Binance C2C SDK API, enabling developers to interact programmatically with Binance's C2C trading platform. The library provides tools to query Fiat transaction history through the REST API:
13
+ - [REST API](./src/binance_sdk_c2c/rest_api/rest_api.py)
14
+
15
+ ## Table of Contents
16
+
17
+ - [Supported Features](#supported-features)
18
+ - [Installation](#installation)
19
+ - [Documentation](#documentation)
20
+ - [REST APIs](#rest-apis)
21
+ - [Testing](#testing)
22
+ - [Migration Guide](#migration-guide)
23
+ - [Contributing](#contributing)
24
+ - [Licence](#licence)
25
+
26
+ ## Supported Features
27
+
28
+ - REST API Endpoints:
29
+ - `/sapi/v1/c2c/*`
30
+ - Inclusion of test cases and examples for quick onboarding.
31
+
32
+ ## Installation
33
+
34
+ To use this library, ensure your environment is running Python version **3.9** or later.
35
+
36
+ ```bash
37
+ pip install binance-sdk-c2c
38
+ ```
39
+
40
+ ## Documentation
41
+
42
+ For detailed information, refer to the [Binance API Documentation](https://developers.binance.com/docs/c2c/Introduction).
43
+
44
+ ### REST APIs
45
+
46
+ All REST API endpoints are available through the [`rest_api`](./src/binance_sdk_c2c/rest_api/rest_api.py) module. The REST API enables you to fetch market data, manage trades, and access account information. Note that some endpoints require authentication using your Binance API credentials.
47
+
48
+ ```python
49
+ from binance_common.configuration import ConfigurationRestAPI
50
+ from binance_common.constants import C2C_REST_API_PROD_URL
51
+ from binance_sdk_c2c.c2c import C2C
52
+ from binance_sdk_c2c.rest_api.models import GetC2CTradeHistoryResponse
53
+
54
+ logging.basicConfig(level=logging.INFO)
55
+ configuration = ConfigurationRestAPI(api_key="your-api-key", api_secret="your-api-secret", base_path=C2C_REST_API_PROD_URL)
56
+
57
+ client = C2C(config_rest_api=configuration)
58
+
59
+ try:
60
+ response = client.rest_api.get_c2_c_trade_history()
61
+
62
+ data: GetC2CTradeHistoryResponse = response.data()
63
+ logging.info(f"get_c2_c_trade_history() response: {data}")
64
+ except Exception as e:
65
+ logging.error(f"get_c2_c_trade_history() error: {e}")
66
+ ```
67
+
68
+ More examples can be found in the [`examples/rest_api`](./examples/rest_api/) folder.
69
+
70
+ #### Configuration Options
71
+
72
+ The REST API supports the following advanced configuration options:
73
+
74
+ - `timeout`: Timeout for requests in milliseconds (default: 1000 ms).
75
+ - `proxy`: Proxy configuration:
76
+ - `host`: Proxy server hostname.
77
+ - `port`: Proxy server port.
78
+ - `protocol`: Proxy protocol (http or https).
79
+ - `auth`: Proxy authentication credentials:
80
+ - `username`: Proxy username.
81
+ - `password`: Proxy password.
82
+ - `keep_alive`: Enable HTTP keep-alive (default: true).
83
+ - `compression`: Enable response compression (default: true).
84
+ - `retries`: Number of retry attempts for failed requests (default: 3).
85
+ - `backoff`: Delay in milliseconds between retries (default: 1000 ms).
86
+ - `https_agent`: Custom HTTPS agent for advanced TLS configuration.
87
+ - `private_key`: RSA or ED25519 private key for authentication.
88
+ - `private_key_passphrase`: Passphrase for the private key, if encrypted.
89
+
90
+ ##### Timeout
91
+
92
+ You can configure a timeout for requests in milliseconds. If the request exceeds the specified timeout, it will be aborted. See the [Timeout example](./docs/rest_api/timeout.md) for detailed usage.
93
+
94
+ ##### Proxy
95
+
96
+ The REST API supports HTTP/HTTPS proxy configurations. See the [Proxy example](./docs/rest_api/proxy.md) for detailed usage.
97
+
98
+ ##### Keep-Alive
99
+
100
+ Enable HTTP keep-alive for persistent connections. See the [Keep-Alive example](./docs/rest_api/keepAlive.md) for detailed usage.
101
+
102
+ ##### Compression
103
+
104
+ Enable or disable response compression. See the [Compression example](./docs/rest_api/compression.md) for detailed usage.
105
+
106
+ ##### Retries
107
+
108
+ Configure the number of retry attempts and delay in milliseconds between retries for failed requests. See the [Retries example](./docs/rest_api/retries.md) for detailed usage.
109
+
110
+ ##### HTTPS Agent
111
+
112
+ Customize the HTTPS agent for advanced TLS configurations. See the [HTTPS Agent example](./docs/rest_api/httpsAgent.md) for detailed usage.
113
+
114
+ ##### Key Pair Based Authentication
115
+
116
+ The REST API supports key pair-based authentication for secure communication. You can use `RSA` or `ED25519` keys for signing requests. See the [Key Pair Based Authentication example](./docs/rest_api/key-pair-authentication.md) for detailed usage.
117
+
118
+ ##### Certificate Pinning
119
+
120
+ To enhance security, you can use certificate pinning with the `https_agent` option in the configuration. This ensures the client only communicates with servers using specific certificates. See the [Certificate Pinning example](./docs/rest_api/certificate-pinning.md) for detailed usage.
121
+
122
+ #### Error Handling
123
+
124
+ The REST API provides detailed error types to help you handle issues effectively:
125
+
126
+ - `ClientError`: Represents an error that occurred in the SDK client.
127
+ - `RequiredError`: Thrown when a required parameter is missing or undefined.
128
+ - `UnauthorizedError`: Indicates missing or invalid authentication credentials.
129
+ - `ForbiddenError`: Access to the requested resource is forbidden.
130
+ - `TooManyRequestsError`: Rate limit exceeded.
131
+ - `RateLimitBanError`: IP address banned for exceeding rate limits.
132
+ - `ServerError`: Internal server error, optionally includes a status code.
133
+ - `NetworkError`: Issues with network connectivity.
134
+ - `NotFoundError`: Resource not found.
135
+ - `BadRequestError`: Invalid request or one that cannot be served.
136
+
137
+ See the [Error Handling example](./docs/rest_api/error-handling.md) for detailed usage.
138
+
139
+ If `base_path` is not provided, it defaults to `https://api.binance.com`.
140
+
141
+ ## Testing
142
+
143
+ To run the tests, ensure you have [Poetry](https://python-poetry.org/) installed, then execute the following commands:
144
+
145
+ ```bash
146
+ poetry install
147
+ poetry run pytest ./tests
148
+ ```
149
+
150
+ The tests cover:
151
+ * REST API endpoints
152
+ * Error handling
153
+ * Edge cases
154
+
155
+ ## Migration Guide
156
+
157
+ If you are upgrading to the new modularized structure, refer to the [Migration Guide](./docs/migration_guide_c2c_sdk.md) for detailed steps.
158
+
159
+ ## Contributing
160
+
161
+ Contributions are welcome!
162
+
163
+ Since this repository contains auto-generated code, we encourage you to start by opening a GitHub issue to discuss your ideas or suggest improvements. This helps ensure that changes align with the project's goals and auto-generation processes.
164
+
165
+ To contribute:
166
+
167
+ 1. Open a GitHub issue describing your suggestion or the bug you've identified.
168
+ 2. If it's determined that changes are necessary, the maintainers will merge the changes into the main branch.
169
+
170
+ Please ensure that all tests pass if you're making a direct contribution. Submit a pull request only after discussing and confirming the change.
171
+
172
+ Thank you for your contributions!
173
+
174
+ ## Licence
175
+
176
+ This project is licensed under the MIT License. See the [LICENCE](./LICENCE) file for details.
@@ -0,0 +1,40 @@
1
+ [tool.poetry]
2
+ name = "binance-sdk-c2c"
3
+ version = "1.0.0"
4
+ description = "Official Binance C2C SDK - A lightweight library that provides a convenient interface to Binance's C2C REST API"
5
+ authors = ["Binance"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ include = ["CHANGELOG.md", "LICENSE", "README.md"]
9
+ packages = [
10
+ { include = "binance_sdk_c2c", from = "src" }
11
+ ]
12
+
13
+ [tool.poetry.dependencies]
14
+ python = ">=3.9,<=3.13"
15
+ requests = ">=2.31.0"
16
+ pydantic = ">=2.10.0"
17
+ websockets = "^15.0.1"
18
+ websocket-client = ">=1.6.3"
19
+ black = "^25.1.0"
20
+ ruff = "^0.12.0"
21
+ pycryptodome = "^3.17"
22
+ aiohttp = "^3.9"
23
+ binance-common = "1.0.0"
24
+ pytest = { version = ">=6.2.5", optional = true }
25
+
26
+ [tool.poetry.extras]
27
+ dev = ["pytest"]
28
+
29
+ [tool.poetry.group.dev.dependencies]
30
+ tox = "^4.27.0"
31
+ pytest = ">=8.4.1"
32
+ pytest-asyncio = "^1.0.0"
33
+
34
+ [tool.ruff]
35
+ exclude = [".git", ".tox", "build", "dist"]
36
+ lint.ignore = ["E741"]
37
+
38
+ [build-system]
39
+ requires = ["poetry-core>=1.0.0"]
40
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,31 @@
1
+ from binance_sdk_c2c.c2c import C2C
2
+ from binance_common.errors import (
3
+ ClientError,
4
+ RequiredError,
5
+ UnauthorizedError,
6
+ ForbiddenError,
7
+ TooManyRequestsError,
8
+ RateLimitBanError,
9
+ ServerError,
10
+ NetworkError,
11
+ NotFoundError,
12
+ BadRequestError,
13
+ )
14
+ from binance_common.constants import (
15
+ C2C_REST_API_PROD_URL,
16
+ )
17
+
18
+ __all__ = [
19
+ "C2C",
20
+ "C2C_REST_API_PROD_URL",
21
+ "ClientError",
22
+ "RequiredError",
23
+ "UnauthorizedError",
24
+ "ForbiddenError",
25
+ "TooManyRequestsError",
26
+ "RateLimitBanError",
27
+ "ServerError",
28
+ "NetworkError",
29
+ "NotFoundError",
30
+ "BadRequestError",
31
+ ]
@@ -0,0 +1,34 @@
1
+ import platform
2
+ from importlib.metadata import version
3
+
4
+ from binance_common.configuration import ConfigurationRestAPI
5
+ from binance_common.constants import C2C_REST_API_PROD_URL
6
+ from . import metadata
7
+ from .rest_api import C2CRestAPI
8
+
9
+ LIB_NAME = metadata.NAME
10
+ LIB_VERSION = version(LIB_NAME)
11
+
12
+
13
+ class C2C:
14
+ """C2C API that exposes REST APIs in a single interface."""
15
+
16
+ def __init__(self, config_rest_api: ConfigurationRestAPI = None) -> None:
17
+ self._rest_api = None
18
+ self._rest_api_config = (
19
+ ConfigurationRestAPI() if config_rest_api is None else config_rest_api
20
+ )
21
+
22
+ @property
23
+ def rest_api(self) -> C2CRestAPI:
24
+ if self._rest_api is None and self._rest_api_config:
25
+ self._rest_api_config.base_headers["User-Agent"] = (
26
+ f"{LIB_NAME}/{LIB_VERSION} (Python/{platform.python_version()}; {platform.system()}; {platform.machine()})"
27
+ )
28
+ self._rest_api_config.base_path = (
29
+ C2C_REST_API_PROD_URL
30
+ if self._rest_api_config.base_path is None
31
+ else self._rest_api_config.base_path
32
+ )
33
+ self._rest_api = C2CRestAPI(self._rest_api_config)
34
+ return self._rest_api
@@ -0,0 +1 @@
1
+ NAME = "binance-sdk-c2c"
@@ -0,0 +1,13 @@
1
+ """
2
+ Binance C2C REST API
3
+
4
+ OpenAPI Specification for the Binance C2C REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ from .rest_api import C2CRestAPI
12
+
13
+ __all__ = ["C2CRestAPI"]
@@ -0,0 +1,11 @@
1
+ """
2
+ Binance C2C REST API
3
+
4
+ OpenAPI Specification for the Binance C2C REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ from .c2_c_api import C2CApi as C2CApi
@@ -0,0 +1,86 @@
1
+ """
2
+ Binance C2C REST API
3
+
4
+ OpenAPI Specification for the Binance C2C REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ from typing import Optional
12
+ from requests import Session
13
+ from binance_common.configuration import ConfigurationRestAPI
14
+ from binance_common.models import ApiResponse
15
+ from binance_common.signature import Signers
16
+ from binance_common.utils import send_request
17
+
18
+ from ..models import GetC2CTradeHistoryResponse
19
+
20
+
21
+ class C2CApi:
22
+ """API Client for C2CApi endpoints."""
23
+
24
+ def __init__(
25
+ self,
26
+ configuration: ConfigurationRestAPI = None,
27
+ session: Session = None,
28
+ signer: Signers = None,
29
+ ) -> None:
30
+ self._configuration = configuration
31
+ self._session = session
32
+ self._signer = signer
33
+
34
+ def get_c2_c_trade_history(
35
+ self,
36
+ start_time: Optional[int] = None,
37
+ end_time: Optional[int] = None,
38
+ page: Optional[int] = None,
39
+ recv_window: Optional[int] = None,
40
+ ) -> ApiResponse[GetC2CTradeHistoryResponse]:
41
+ """
42
+ Get C2C Trade History (USER_DATA)
43
+ GET /sapi/v1/c2c/orderMatch/listUserOrderHistory
44
+ https://developers.binance.com/docs/c2c/rest-api/Get-C2C-Trade-History
45
+
46
+ Get C2C Trade History
47
+
48
+ * The max interval between startTime and endTime is 30 days.
49
+ * If startTime and endTime are not sent, the recent 7 days' data will be returned.
50
+ * The earliest startTime is supported on June 10, 2020
51
+ * Return up to 200 records per request.
52
+
53
+ Weight: 1
54
+
55
+ Args:
56
+ start_time (Optional[int]):
57
+ end_time (Optional[int]):
58
+ page (Optional[int]): Default 1
59
+ recv_window (Optional[int]):
60
+
61
+ Returns:
62
+ ApiResponse[GetC2CTradeHistoryResponse]
63
+
64
+ Raises:
65
+ RequiredError: If a required parameter is missing.
66
+
67
+ """
68
+
69
+ payload = {
70
+ "start_time": start_time,
71
+ "end_time": end_time,
72
+ "page": page,
73
+ "recv_window": recv_window,
74
+ }
75
+
76
+ return send_request(
77
+ self._session,
78
+ self._configuration,
79
+ method="GET",
80
+ path="/sapi/v1/c2c/orderMatch/listUserOrderHistory",
81
+ payload=payload,
82
+ time_unit=self._configuration.time_unit,
83
+ response_model=GetC2CTradeHistoryResponse,
84
+ is_signed=True,
85
+ signer=self._signer,
86
+ )
@@ -0,0 +1,16 @@
1
+ """
2
+ Binance C2C REST API
3
+
4
+ OpenAPI Specification for the Binance C2C REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ from .get_c2_c_trade_history_response import (
12
+ GetC2CTradeHistoryResponse as GetC2CTradeHistoryResponse,
13
+ )
14
+ from .get_c2_c_trade_history_response_data_inner import (
15
+ GetC2CTradeHistoryResponseDataInner as GetC2CTradeHistoryResponseDataInner,
16
+ )
@@ -0,0 +1,9 @@
1
+ """
2
+ Binance C2C REST API
3
+
4
+ OpenAPI Specification for the Binance C2C REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
@@ -0,0 +1,131 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Binance C2C REST API
5
+
6
+ OpenAPI Specification for the Binance C2C REST API
7
+ The version of the OpenAPI document: 1.0.0
8
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
9
+
10
+ Do not edit the class manually.
11
+ """
12
+
13
+
14
+ from __future__ import annotations
15
+ import pprint
16
+ import re # noqa: F401
17
+ import json
18
+
19
+ from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr
20
+ from typing import Any, ClassVar, Dict, List, Optional
21
+ from binance_sdk_c2c.rest_api.models.get_c2_c_trade_history_response_data_inner import (
22
+ GetC2CTradeHistoryResponseDataInner,
23
+ )
24
+ from typing import Set
25
+ from typing_extensions import Self
26
+
27
+
28
+ class GetC2CTradeHistoryResponse(BaseModel):
29
+ """
30
+ GetC2CTradeHistoryResponse
31
+ """ # noqa: E501
32
+
33
+ code: Optional[StrictStr] = None
34
+ message: Optional[StrictStr] = None
35
+ data: Optional[List[GetC2CTradeHistoryResponseDataInner]] = None
36
+ total: Optional[StrictInt] = None
37
+ success: Optional[StrictBool] = None
38
+ additional_properties: Dict[str, Any] = {}
39
+ __properties: ClassVar[List[str]] = ["code", "message", "data", "total", "success"]
40
+
41
+ model_config = ConfigDict(
42
+ populate_by_name=True,
43
+ validate_assignment=True,
44
+ protected_namespaces=(),
45
+ )
46
+
47
+ def to_str(self) -> str:
48
+ """Returns the string representation of the model using alias"""
49
+ return pprint.pformat(self.model_dump(by_alias=True))
50
+
51
+ def to_json(self) -> str:
52
+ """Returns the JSON representation of the model using alias"""
53
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
54
+ return json.dumps(self.to_dict())
55
+
56
+ @classmethod
57
+ def is_array(cls) -> bool:
58
+ return False
59
+
60
+ @classmethod
61
+ def from_json(cls, json_str: str) -> Optional[Self]:
62
+ """Create an instance of GetC2CTradeHistoryResponse from a JSON string"""
63
+ return cls.from_dict(json.loads(json_str))
64
+
65
+ def to_dict(self) -> Dict[str, Any]:
66
+ """Return the dictionary representation of the model using alias.
67
+
68
+ This has the following differences from calling pydantic's
69
+ `self.model_dump(by_alias=True)`:
70
+
71
+ * `None` is only added to the output dict for nullable fields that
72
+ were set at model initialization. Other fields with value `None`
73
+ are ignored.
74
+ * Fields in `self.additional_properties` are added to the output dict.
75
+ """
76
+ excluded_fields: Set[str] = set(
77
+ [
78
+ "additional_properties",
79
+ ]
80
+ )
81
+
82
+ _dict = self.model_dump(
83
+ by_alias=True,
84
+ exclude=excluded_fields,
85
+ exclude_none=True,
86
+ )
87
+ # override the default output from pydantic by calling `to_dict()` of each item in data (list)
88
+ _items = []
89
+ if self.data:
90
+ for _item_data in self.data:
91
+ if _item_data:
92
+ _items.append(_item_data.to_dict())
93
+ _dict["data"] = _items
94
+ # puts key-value pairs in additional_properties in the top level
95
+ if self.additional_properties is not None:
96
+ for _key, _value in self.additional_properties.items():
97
+ _dict[_key] = _value
98
+
99
+ return _dict
100
+
101
+ @classmethod
102
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
103
+ """Create an instance of GetC2CTradeHistoryResponse from a dict"""
104
+ if obj is None:
105
+ return None
106
+
107
+ if not isinstance(obj, dict):
108
+ return cls.model_validate(obj)
109
+
110
+ _obj = cls.model_validate(
111
+ {
112
+ "code": obj.get("code"),
113
+ "message": obj.get("message"),
114
+ "data": (
115
+ [
116
+ GetC2CTradeHistoryResponseDataInner.from_dict(_item)
117
+ for _item in obj["data"]
118
+ ]
119
+ if obj.get("data") is not None
120
+ else None
121
+ ),
122
+ "total": obj.get("total"),
123
+ "success": obj.get("success"),
124
+ }
125
+ )
126
+ # store additional fields in additional_properties
127
+ for _key in obj.keys():
128
+ if _key not in cls.__properties:
129
+ _obj.additional_properties[_key] = obj.get(_key)
130
+
131
+ return _obj
@@ -0,0 +1,151 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Binance C2C REST API
5
+
6
+ OpenAPI Specification for the Binance C2C REST API
7
+ The version of the OpenAPI document: 1.0.0
8
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
9
+
10
+ Do not edit the class manually.
11
+ """
12
+
13
+
14
+ from __future__ import annotations
15
+ import pprint
16
+ import re # noqa: F401
17
+ import json
18
+
19
+ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
20
+ from typing import Any, ClassVar, Dict, List, Optional
21
+ from typing import Set
22
+ from typing_extensions import Self
23
+
24
+
25
+ class GetC2CTradeHistoryResponseDataInner(BaseModel):
26
+ """
27
+ GetC2CTradeHistoryResponseDataInner
28
+ """ # noqa: E501
29
+
30
+ order_number: Optional[StrictStr] = Field(default=None, alias="orderNumber")
31
+ adv_no: Optional[StrictStr] = Field(default=None, alias="advNo")
32
+ trade_type: Optional[StrictStr] = Field(default=None, alias="tradeType")
33
+ asset: Optional[StrictStr] = None
34
+ fiat: Optional[StrictStr] = None
35
+ fiat_symbol: Optional[StrictStr] = Field(default=None, alias="fiatSymbol")
36
+ amount: Optional[StrictStr] = None
37
+ total_price: Optional[StrictStr] = Field(default=None, alias="totalPrice")
38
+ unit_price: Optional[StrictStr] = Field(default=None, alias="unitPrice")
39
+ order_status: Optional[StrictStr] = Field(default=None, alias="orderStatus")
40
+ create_time: Optional[StrictInt] = Field(default=None, alias="createTime")
41
+ commission: Optional[StrictStr] = None
42
+ counter_part_nick_name: Optional[StrictStr] = Field(
43
+ default=None, alias="counterPartNickName"
44
+ )
45
+ advertisement_role: Optional[StrictStr] = Field(
46
+ default=None, alias="advertisementRole"
47
+ )
48
+ additional_properties: Dict[str, Any] = {}
49
+ __properties: ClassVar[List[str]] = [
50
+ "orderNumber",
51
+ "advNo",
52
+ "tradeType",
53
+ "asset",
54
+ "fiat",
55
+ "fiatSymbol",
56
+ "amount",
57
+ "totalPrice",
58
+ "unitPrice",
59
+ "orderStatus",
60
+ "createTime",
61
+ "commission",
62
+ "counterPartNickName",
63
+ "advertisementRole",
64
+ ]
65
+
66
+ model_config = ConfigDict(
67
+ populate_by_name=True,
68
+ validate_assignment=True,
69
+ protected_namespaces=(),
70
+ )
71
+
72
+ def to_str(self) -> str:
73
+ """Returns the string representation of the model using alias"""
74
+ return pprint.pformat(self.model_dump(by_alias=True))
75
+
76
+ def to_json(self) -> str:
77
+ """Returns the JSON representation of the model using alias"""
78
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
79
+ return json.dumps(self.to_dict())
80
+
81
+ @classmethod
82
+ def is_array(cls) -> bool:
83
+ return False
84
+
85
+ @classmethod
86
+ def from_json(cls, json_str: str) -> Optional[Self]:
87
+ """Create an instance of GetC2CTradeHistoryResponseDataInner from a JSON string"""
88
+ return cls.from_dict(json.loads(json_str))
89
+
90
+ def to_dict(self) -> Dict[str, Any]:
91
+ """Return the dictionary representation of the model using alias.
92
+
93
+ This has the following differences from calling pydantic's
94
+ `self.model_dump(by_alias=True)`:
95
+
96
+ * `None` is only added to the output dict for nullable fields that
97
+ were set at model initialization. Other fields with value `None`
98
+ are ignored.
99
+ * Fields in `self.additional_properties` are added to the output dict.
100
+ """
101
+ excluded_fields: Set[str] = set(
102
+ [
103
+ "additional_properties",
104
+ ]
105
+ )
106
+
107
+ _dict = self.model_dump(
108
+ by_alias=True,
109
+ exclude=excluded_fields,
110
+ exclude_none=True,
111
+ )
112
+ # puts key-value pairs in additional_properties in the top level
113
+ if self.additional_properties is not None:
114
+ for _key, _value in self.additional_properties.items():
115
+ _dict[_key] = _value
116
+
117
+ return _dict
118
+
119
+ @classmethod
120
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
121
+ """Create an instance of GetC2CTradeHistoryResponseDataInner from a dict"""
122
+ if obj is None:
123
+ return None
124
+
125
+ if not isinstance(obj, dict):
126
+ return cls.model_validate(obj)
127
+
128
+ _obj = cls.model_validate(
129
+ {
130
+ "orderNumber": obj.get("orderNumber"),
131
+ "advNo": obj.get("advNo"),
132
+ "tradeType": obj.get("tradeType"),
133
+ "asset": obj.get("asset"),
134
+ "fiat": obj.get("fiat"),
135
+ "fiatSymbol": obj.get("fiatSymbol"),
136
+ "amount": obj.get("amount"),
137
+ "totalPrice": obj.get("totalPrice"),
138
+ "unitPrice": obj.get("unitPrice"),
139
+ "orderStatus": obj.get("orderStatus"),
140
+ "createTime": obj.get("createTime"),
141
+ "commission": obj.get("commission"),
142
+ "counterPartNickName": obj.get("counterPartNickName"),
143
+ "advertisementRole": obj.get("advertisementRole"),
144
+ }
145
+ )
146
+ # store additional fields in additional_properties
147
+ for _key in obj.keys():
148
+ if _key not in cls.__properties:
149
+ _obj.additional_properties[_key] = obj.get(_key)
150
+
151
+ return _obj
@@ -0,0 +1,119 @@
1
+ """
2
+ Binance C2C REST API
3
+
4
+ OpenAPI Specification for the Binance C2C REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ import requests
12
+ from typing import Optional, TypeVar
13
+ from binance_common.configuration import ConfigurationRestAPI
14
+ from binance_common.models import ApiResponse
15
+ from binance_common.signature import Signers
16
+ from binance_common.utils import send_request
17
+ from .api.c2_c_api import C2CApi
18
+
19
+ from .models import GetC2CTradeHistoryResponse
20
+
21
+
22
+ T = TypeVar("T")
23
+
24
+
25
+ class C2CRestAPI:
26
+ def __init__(
27
+ self,
28
+ configuration: ConfigurationRestAPI,
29
+ ) -> None:
30
+ self.configuration = configuration
31
+ self._session = requests.Session()
32
+ self._signer = (
33
+ Signers.get_signer(
34
+ configuration.private_key, configuration.private_key_passphrase
35
+ )
36
+ if configuration.private_key is not None
37
+ else None
38
+ )
39
+
40
+ self._c2CApi = C2CApi(self.configuration, self._session, self._signer)
41
+
42
+ def send_request(
43
+ self, endpoint: str, method: str, params: Optional[dict] = None
44
+ ) -> ApiResponse[T]:
45
+ """
46
+ Sends an request to the Binance REST API.
47
+
48
+ Args:
49
+ endpoint (str): The API endpoint path to send the request to.
50
+ method (str): The HTTP method to use for the request (e.g. "GET", "POST", "PUT", "DELETE").
51
+ params (Optional[dict]): The request payload as a dictionary, or None if no payload is required.
52
+
53
+ Returns:
54
+ ApiResponse[T]: The API response, where T is the expected response type.
55
+ """
56
+ return send_request[T](
57
+ self._session, self.configuration, method, endpoint, params
58
+ )
59
+
60
+ def send_signed_request(
61
+ self, endpoint: str, method: str, params: Optional[dict] = None
62
+ ) -> ApiResponse[T]:
63
+ """
64
+ Sends a signed request to the Binance REST API.
65
+
66
+ Args:
67
+ endpoint (str): The API endpoint path to send the request to.
68
+ method (str): The HTTP method to use for the request (e.g. "GET", "POST", "PUT", "DELETE").
69
+ params (Optional[dict]): The request payload as a dictionary, or None if no payload is required.
70
+
71
+ Returns:
72
+ ApiResponse[T]: The API response, where T is the expected response type.
73
+ """
74
+ return send_request[T](
75
+ self._session,
76
+ self.configuration,
77
+ method,
78
+ endpoint,
79
+ params,
80
+ is_signed=True,
81
+ signer=self._signer,
82
+ )
83
+
84
+ def get_c2_c_trade_history(
85
+ self,
86
+ start_time: Optional[int] = None,
87
+ end_time: Optional[int] = None,
88
+ page: Optional[int] = None,
89
+ recv_window: Optional[int] = None,
90
+ ) -> ApiResponse[GetC2CTradeHistoryResponse]:
91
+ """
92
+ Get C2C Trade History (USER_DATA)
93
+
94
+ Get C2C Trade History
95
+
96
+ * The max interval between startTime and endTime is 30 days.
97
+ * If startTime and endTime are not sent, the recent 7 days' data will be returned.
98
+ * The earliest startTime is supported on June 10, 2020
99
+ * Return up to 200 records per request.
100
+
101
+ Weight: 1
102
+
103
+ Args:
104
+ start_time (Optional[int]):
105
+ end_time (Optional[int]):
106
+ page (Optional[int]): Default 1
107
+ recv_window (Optional[int]):
108
+
109
+ Returns:
110
+ ApiResponse[GetC2CTradeHistoryResponse]
111
+
112
+ Raises:
113
+ RequiredError: If a required parameter is missing.
114
+
115
+ """
116
+
117
+ return self._c2CApi.get_c2_c_trade_history(
118
+ start_time, end_time, page, recv_window
119
+ )