Skip to content

clients

Bitpin Client.

Client for Bitpin API.

See API Reference for more information.

Client Submodule contains the synchronous client. AsyncClient Submodule contains the asynchronous client. Core Submodule contains the core client.

AsyncClient

Bases: CoreClient

Async Client.

Methods:

Name Description
login

Login and set (refresh_token/access_token)

refresh_access_token

Refresh token.

get_user_info

Get user info.

get_currencies_info

Get currencies info.

get_markets_info

Get markets info.

get_wallets

Get wallets.

get_orderbook

Get orderbook.

get_recent_trades

Get recent trades.

get_user_orders

Get user orders.

create_order

Create order.

cancel_order

Cancel order.

get_user_trades

Get user trades.

close_connection

Close connection.

Attributes:

Name Type Description
session ClientSession

Session.

loop AbstractEventLoop

Event Loop

api_key str

API key.

api_secret str

API secret.

refresh_token str

Refresh token.

access_token str

Access token.

Source code in src/bitpin/clients/async_client.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
class AsyncClient(CoreClient):
    """
    Async Client.

    Methods:
        login: Login and set (refresh_token/access_token)
        refresh_access_token: Refresh token.
        get_user_info: Get user info.
        get_currencies_info: Get currencies info.
        get_markets_info: Get markets info.
        get_wallets: Get wallets.
        get_orderbook: Get orderbook.
        get_recent_trades: Get recent trades.
        get_user_orders: Get user orders.
        create_order: Create order.
        cancel_order: Cancel order.
        get_user_trades: Get user trades.
        close_connection: Close connection.

    Attributes:
        session (aiohttp.ClientSession): Session.
        loop (asyncio.AbstractEventLoop): Event Loop
        api_key (str): API key.
        api_secret (str): API secret.
        refresh_token (str): Refresh token.
        access_token (str): Access token.
    """

    def __init__(  # type: ignore[no-untyped-def]
        self,
        api_key: t.OptionalStr = None,
        api_secret: t.OptionalStr = None,
        access_token: t.OptionalStr = None,
        refresh_token: t.OptionalStr = None,
        requests_params: t.OptionalDictStrAny = None,
        session_params: t.OptionalDictStrAny = None,
        loop: t.OptionalEventLoop = None,
        background_relogin: bool = False,
        background_relogin_interval: int = 60 * 60 * 24 * 6,
        background_refresh_token: bool = False,
        background_refresh_token_interval: int = 60 * 13,
    ):
        """
        Constructor.

        Args:
            api_key (str): API key.
            api_secret (str): API secret.
            access_token (str): Access token.
            refresh_token (str): Refresh token.
            requests_params (dict): Requests params.
            session_params (dict): Session params.
            loop (asyncio.AbstractEventLoop): Event loop.
            background_relogin (bool): Background refresh.
            background_relogin_interval (int): Background refresh interval.
            background_refresh_token (bool): Background refresh token.
            background_refresh_token_interval (int): Background refresh token interval.

        Notes:
            If `api_key` and `api_secret` are not provided, they will be read from the environment variables
            `BITPIN_API_KEY` and `BITPIN_API_SECRET` respectively.

            If `access_token` and `refresh_token` are not provided, they will be read from the environment variables
            `BITPIN_ACCESS_TOKEN` and `BITPIN_REFRESH_TOKEN` respectively.

            If `requests_params` are provided, they will be used as default for every request.

            If `requests_params` are provided in `kwargs`, they will override existing `requests_params`.

            If `background_relogin` is enabled, access token will be refreshed in background every
            `background_relogin_interval` seconds.

            If `background_refresh_token` is enabled, refresh token will be refreshed in background every
            `background_refresh_token_interval` seconds.
        """

        self.loop = loop or get_loop()
        self._session_params = session_params or {}

        super().__init__(
            api_key,
            api_secret,
            access_token,
            refresh_token,
            requests_params,
            background_relogin,
            background_relogin_interval,
            background_refresh_token,
            background_refresh_token_interval,
        )

    @classmethod
    async def create(  # type: ignore[no-untyped-def]
        cls,
        api_key: t.OptionalStr = None,
        api_secret: t.OptionalStr = None,
        access_token: t.OptionalStr = None,
        refresh_token: t.OptionalStr = None,
        requests_params: t.OptionalDictStrAny = None,
        session_params: t.OptionalDictStrAny = None,
        loop: t.OptionalEventLoop = None,
        background_relogin: bool = False,
        background_relogin_interval: int = 60 * 60 * 24 * 6,
        background_refresh_token: bool = False,
        background_refresh_token_interval: int = 60 * 13,
    ) -> "AsyncClient":
        """
        Create AsyncClient.

        Args:
            api_key (str): API key.
            api_secret (str): API secret.
            access_token (str): Access token.
            refresh_token (str): Refresh token.
            requests_params (dict): Requests params.
            session_params (dict): Session params.
            loop (asyncio.AbstractEventLoop): Event loop.
            background_relogin (bool): Background refresh.
            background_relogin_interval (int): Background refresh interval.
            background_refresh_token (bool): Background refresh token.
            background_refresh_token_interval (int): Background refresh token interval.

        Returns:
            AsyncClient: AsyncClient.
        """

        self = cls(
            api_key,
            api_secret,
            access_token,
            refresh_token,
            requests_params,
            session_params,
            loop,
            background_relogin,
            background_relogin_interval,
            background_refresh_token,
            background_refresh_token_interval,
        )

        await self._handle_login()
        return self

    def _init_session(self) -> aiohttp.ClientSession:
        """
        Initialize session.

        Returns:
            session (aiohttp.ClientSession): Session.

        """

        session = aiohttp.ClientSession(
            loop=self.loop,
            headers={
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            **self._session_params,
        )
        return session

    async def _get(  # type: ignore[no-untyped-def, override]
        self,
        path: str,
        signed: bool = False,
        version: str = CoreClient.PUBLIC_API_VERSION_1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Make a GET request.

        Args:
            path (str): Path.
            signed (bool): Signed.
            version (str): Version.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        return await self._request_api(enums.RequestMethod.GET, path, signed, version, **kwargs)

    async def _post(  # type: ignore[no-untyped-def, override]
        self,
        path: str,
        signed: bool = False,
        version: str = CoreClient.PUBLIC_API_VERSION_1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Make a POST request.

        Args:
            path (str): Path.
            signed (bool): Signed.
            version (str): Version.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        return await self._request_api(enums.RequestMethod.POST, path, signed, version, **kwargs)

    async def _delete(  # type: ignore[no-untyped-def, override]
        self,
        path: str,
        signed: bool = False,
        version: str = CoreClient.PUBLIC_API_VERSION_1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Make a DELETE request.

        Args:
            path (str): Path.
            signed (bool): Signed.
            version (str): Version.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        return await self._request_api(enums.RequestMethod.DELETE, path, signed, version, **kwargs)

    async def _request_api(  # type: ignore[no-untyped-def, override]
        self,
        method: t.RequestMethods,
        path: str,
        signed: bool = False,
        version: str = CoreClient.PUBLIC_API_VERSION_1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Request API.

        Args:
            method (RequestMethod): Method.
            path (str): Path.
            signed (bool): Signed.
            version (str): Version.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        uri = self._create_api_uri(path, version)
        return await self._request(method, uri, signed, **kwargs)

    async def _request(  # type: ignore[no-untyped-def, override]
        self, method: t.RequestMethods, uri: str, signed: bool, **kwargs
    ) -> t.DictStrAny:
        """
        Request.

        Args:
            method (RequestMethod): Method.
            uri (str): URI.
            signed (bool): Signed.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        kwargs = self._get_request_kwargs(method, signed, **kwargs)

        async with getattr(self.session, method)(uri, **kwargs) as response:
            self.response = response  # pylint: disable=attribute-defined-outside-init
            return await self._handle_response(response)

    @staticmethod
    async def _handle_response(response: aiohttp.ClientResponse) -> t.DictStrAny:  # type: ignore[override]
        """
        Handle response.

        Args:
            response (aiohttp.ClientResponse): Response.

        Returns:
            dict: Response.

        Raises:
            APIException: API Exception.
            RequestException: Request Exception.
        """

        if not str(response.status).startswith("2"):
            raise APIException(response, response.status, await response.text())
        try:
            if response.method.lower() == enums.RequestMethod.DELETE:
                return {"status": "success", "id": response.request_info.url.parts[-2]}
            return await response.json()  # type: ignore[no-any-return]
        except ValueError as exc:
            raise RequestException(f"Invalid Response: {await response.text()}") from exc

    async def _background_relogin_task(self) -> None:  # type: ignore[override]
        """Background relogin task."""

        while True:
            try:
                await self.login()
                await asyncio.sleep(self._background_relogin_interval)
            except Exception:  # pylint: disable=broad-except
                continue

    async def _background_refresh_token_task(self) -> None:  # type: ignore[override]
        """Background refresh token task."""

        while True:
            try:
                await self.refresh_access_token()
                await asyncio.sleep(self._background_refresh_token_interval)
            except Exception:  # pylint: disable=broad-except
                continue

    async def _handle_login(self) -> None:  # type: ignore[override]
        """Handle login."""

        if self.api_key and self.api_secret:
            await self.login()

        if self._background_relogin:
            self.loop.create_task(self._background_relogin_task())  # noqa

        if self._background_refresh_token:
            self.loop.create_task(self._background_refresh_token_task())  # noqa

    async def login(self, **kwargs) -> t.LoginResponse:  # type: ignore[no-untyped-def, override]
        """
        Login and set (refresh_token/access_token).

        Args:
            **kwargs: Kwargs.

        Returns:
            Response (LoginResponse): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#02c24a5326)
        """

        kwargs["json"] = {"api_key": self.api_key, "secret_key": self.api_secret}
        _: t.LoginResponse = await self._post(self.LOGIN_URL, **kwargs)  # type: ignore[assignment]

        self.refresh_token = _["refresh"]
        self.access_token = _["access"]

        return _

    async def refresh_access_token(  # type: ignore[no-untyped-def, override]
        self, refresh_token: t.OptionalStr = None, **kwargs
    ) -> t.RefreshTokenResponse:
        """
        Refresh token.

        Args:
            refresh_token (str): Refresh token.
            **kwargs: Kwargs.

        Returns:
            Response (RefreshTokenResponse): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#9b81094f74)
        """

        kwargs["json"] = {"refresh": refresh_token or self.refresh_token}
        _: t.RefreshTokenResponse = await self._post(self.REFRESH_TOKEN_URL, **kwargs)  # type: ignore[assignment]

        self.access_token = _["access"]

        return _

    async def get_user_info(self, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def, override]
        """
        Get user info.

        Args:
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#5b3c85d79e)
        """

        return await self._get(self.USER_INFO_URL, signed=True, **kwargs)

    async def get_currencies_info(  # type: ignore[no-untyped-def, override]
        self, page: int = 1, **kwargs
    ) -> t.DictStrAny:
        """
        Get currencies info.

        Args:
            page (int): Page.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#7e59da3d0d)

        Notes:
            Rate limit: 10000/day or 200/minute if you are authenticated.
        """

        return await self._get(self.CURRENCIES_LIST_URL.format(page), **kwargs)

    async def get_markets_info(self, page: int = 1, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def, override]
        """
        Get markets info.

        Args:
            page (int): Page.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#334792bb2b)

        Notes:
            Rate limit: 10000/day or 200/minute if you are authenticated.
        """

        return await self._get(self.MARKETS_LIST_URL.format(page), **kwargs)

    async def get_wallets(self, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def, override]
        """
        Get wallets.

        Args:
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#9b93495188)

        Notes:
            Rate limit: 10000/day.
        """

        return await self._get(self.WALLETS_URL, signed=True, **kwargs)

    async def get_orderbook(  # type: ignore[no-untyped-def, override]
        self,
        market_id: int,
        type: t.OrderTypes,
        **kwargs,  # pylint: disable=redefined-builtin
    ) -> t.OrderbookResponse:
        """
        Get orderbook.

        Args:
            market_id (int): Market ID.
            type (OrderTypes): Type.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#ec7180fc0e)
        """
        return await self._get(  # type: ignore[return-value]
            self.ORDERBOOK_URL.format(market_id, str(type)), version=self.PUBLIC_API_VERSION_2, **kwargs
        )

    async def get_recent_trades(  # type: ignore[no-untyped-def, override]
        self, market_id: int, **kwargs
    ) -> t.TradeResponse:
        """
        Get recent trades.

        Args:
            market_id (int): Market ID.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#1dd63530b5)
        """

        return await self._get(self.RECENT_TRADES_URL.format(market_id), **kwargs)  # type: ignore[return-value]

    async def get_user_orders(  # type: ignore[no-untyped-def, override]
        self,
        market_id: t.OptionalInt = None,
        type: t.OptionalOrderTypes = None,  # pylint: disable=redefined-builtin
        state: t.OptionalStr = None,
        mode: t.OptionalStr = None,
        identifier: t.OptionalStr = None,
        page: int = 1,
        **kwargs,
    ) -> t.OpenOrdersResponse:
        """
        Get user orders.

        Args:
            market_id (int): Market ID.
            type (OrderTypes): Type.
            state (str): State.
            mode (str): Mode.
            identifier (str): Identifier.
            page (int): Page.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#8a7c2a2af5)
        """

        kwargs["params"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
        return await self._get(self.ORDERS_URL, signed=True, **kwargs)  # type: ignore[return-value]

    async def create_order(  # type: ignore[no-untyped-def, override]
        self,
        market: int,
        amount1: float,
        price: float,
        mode: t.OrderModes,
        type: t.OrderTypes,  # pylint: disable=redefined-builtin
        identifier: t.OptionalStr = None,
        price_limit: t.OptionalFloat = None,
        price_stop: t.OptionalFloat = None,
        price_limit_oco: t.OptionalFloat = None,
        amount2: t.OptionalFloat = None,
        **kwargs,
    ) -> t.CreateOrderResponse:
        """
        Create order.

        Args:
            market (int): Market.
            amount1 (float): Amount1.
            price (float): Price.
            mode (OrderModes): Mode.
            type (OrderTypes): Type.
            identifier (str): Identifier.
            price_limit (float): Price limit.
            price_stop (float): Price stop.
            price_limit_oco (float): Price limit oco.
            amount2 (float): Amount2.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#34b353d77b)
        """

        kwargs["json"] = {k: v for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
        return await self._post(self.ORDERS_URL, signed=True, **kwargs)  # type: ignore[return-value]

    async def cancel_order(  # type: ignore[no-untyped-def, override]
        self, order_id: str, **kwargs
    ) -> t.CancelOrderResponse:
        """
        Cancel order.

        Args:
            order_id (str): Order ID.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#3fe8d57657)
        """

        return await self._delete(self.ORDERS_URL + f"{order_id}/", signed=True, **kwargs)  # type: ignore[return-value]

    async def get_user_trades(  # type: ignore[no-untyped-def, override]
        self,
        market_id: t.OptionalInt = None,
        type: t.OptionalOrderTypes = None,  # pylint: disable=redefined-builtin
        page: int = 1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Get user trades.

        Args:
            market_id (int): Market ID.
            type (OrderTypes): Type.
            page (int): Page.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#3fe8d57657)
        """

        kwargs["params"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
        return await self._get(self.USER_TRADES_URL, signed=True, **kwargs)

    async def close_connection(self) -> None:  # type: ignore[override]
        """Close connection."""

        await self.session.close()  # type: ignore[misc]

__init__(api_key=None, api_secret=None, access_token=None, refresh_token=None, requests_params=None, session_params=None, loop=None, background_relogin=False, background_relogin_interval=60 * 60 * 24 * 6, background_refresh_token=False, background_refresh_token_interval=60 * 13)

Constructor.

Parameters:

Name Type Description Default
api_key str

API key.

None
api_secret str

API secret.

None
access_token str

Access token.

None
refresh_token str

Refresh token.

None
requests_params dict

Requests params.

None
session_params dict

Session params.

None
loop AbstractEventLoop

Event loop.

None
background_relogin bool

Background refresh.

False
background_relogin_interval int

Background refresh interval.

60 * 60 * 24 * 6
background_refresh_token bool

Background refresh token.

False
background_refresh_token_interval int

Background refresh token interval.

60 * 13
Notes

If api_key and api_secret are not provided, they will be read from the environment variables BITPIN_API_KEY and BITPIN_API_SECRET respectively.

If access_token and refresh_token are not provided, they will be read from the environment variables BITPIN_ACCESS_TOKEN and BITPIN_REFRESH_TOKEN respectively.

If requests_params are provided, they will be used as default for every request.

If requests_params are provided in kwargs, they will override existing requests_params.

If background_relogin is enabled, access token will be refreshed in background every background_relogin_interval seconds.

If background_refresh_token is enabled, refresh token will be refreshed in background every background_refresh_token_interval seconds.

Source code in src/bitpin/clients/async_client.py
def __init__(  # type: ignore[no-untyped-def]
    self,
    api_key: t.OptionalStr = None,
    api_secret: t.OptionalStr = None,
    access_token: t.OptionalStr = None,
    refresh_token: t.OptionalStr = None,
    requests_params: t.OptionalDictStrAny = None,
    session_params: t.OptionalDictStrAny = None,
    loop: t.OptionalEventLoop = None,
    background_relogin: bool = False,
    background_relogin_interval: int = 60 * 60 * 24 * 6,
    background_refresh_token: bool = False,
    background_refresh_token_interval: int = 60 * 13,
):
    """
    Constructor.

    Args:
        api_key (str): API key.
        api_secret (str): API secret.
        access_token (str): Access token.
        refresh_token (str): Refresh token.
        requests_params (dict): Requests params.
        session_params (dict): Session params.
        loop (asyncio.AbstractEventLoop): Event loop.
        background_relogin (bool): Background refresh.
        background_relogin_interval (int): Background refresh interval.
        background_refresh_token (bool): Background refresh token.
        background_refresh_token_interval (int): Background refresh token interval.

    Notes:
        If `api_key` and `api_secret` are not provided, they will be read from the environment variables
        `BITPIN_API_KEY` and `BITPIN_API_SECRET` respectively.

        If `access_token` and `refresh_token` are not provided, they will be read from the environment variables
        `BITPIN_ACCESS_TOKEN` and `BITPIN_REFRESH_TOKEN` respectively.

        If `requests_params` are provided, they will be used as default for every request.

        If `requests_params` are provided in `kwargs`, they will override existing `requests_params`.

        If `background_relogin` is enabled, access token will be refreshed in background every
        `background_relogin_interval` seconds.

        If `background_refresh_token` is enabled, refresh token will be refreshed in background every
        `background_refresh_token_interval` seconds.
    """

    self.loop = loop or get_loop()
    self._session_params = session_params or {}

    super().__init__(
        api_key,
        api_secret,
        access_token,
        refresh_token,
        requests_params,
        background_relogin,
        background_relogin_interval,
        background_refresh_token,
        background_refresh_token_interval,
    )

cancel_order(order_id, **kwargs) async

Cancel order.

Parameters:

Name Type Description Default
order_id str

Order ID.

required
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def cancel_order(  # type: ignore[no-untyped-def, override]
    self, order_id: str, **kwargs
) -> t.CancelOrderResponse:
    """
    Cancel order.

    Args:
        order_id (str): Order ID.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#3fe8d57657)
    """

    return await self._delete(self.ORDERS_URL + f"{order_id}/", signed=True, **kwargs)  # type: ignore[return-value]

close_connection() async

Close connection.

Source code in src/bitpin/clients/async_client.py
async def close_connection(self) -> None:  # type: ignore[override]
    """Close connection."""

    await self.session.close()  # type: ignore[misc]

create(api_key=None, api_secret=None, access_token=None, refresh_token=None, requests_params=None, session_params=None, loop=None, background_relogin=False, background_relogin_interval=60 * 60 * 24 * 6, background_refresh_token=False, background_refresh_token_interval=60 * 13) async classmethod

Create AsyncClient.

Parameters:

Name Type Description Default
api_key str

API key.

None
api_secret str

API secret.

None
access_token str

Access token.

None
refresh_token str

Refresh token.

None
requests_params dict

Requests params.

None
session_params dict

Session params.

None
loop AbstractEventLoop

Event loop.

None
background_relogin bool

Background refresh.

False
background_relogin_interval int

Background refresh interval.

60 * 60 * 24 * 6
background_refresh_token bool

Background refresh token.

False
background_refresh_token_interval int

Background refresh token interval.

60 * 13

Returns:

Name Type Description
AsyncClient AsyncClient

AsyncClient.

Source code in src/bitpin/clients/async_client.py
@classmethod
async def create(  # type: ignore[no-untyped-def]
    cls,
    api_key: t.OptionalStr = None,
    api_secret: t.OptionalStr = None,
    access_token: t.OptionalStr = None,
    refresh_token: t.OptionalStr = None,
    requests_params: t.OptionalDictStrAny = None,
    session_params: t.OptionalDictStrAny = None,
    loop: t.OptionalEventLoop = None,
    background_relogin: bool = False,
    background_relogin_interval: int = 60 * 60 * 24 * 6,
    background_refresh_token: bool = False,
    background_refresh_token_interval: int = 60 * 13,
) -> "AsyncClient":
    """
    Create AsyncClient.

    Args:
        api_key (str): API key.
        api_secret (str): API secret.
        access_token (str): Access token.
        refresh_token (str): Refresh token.
        requests_params (dict): Requests params.
        session_params (dict): Session params.
        loop (asyncio.AbstractEventLoop): Event loop.
        background_relogin (bool): Background refresh.
        background_relogin_interval (int): Background refresh interval.
        background_refresh_token (bool): Background refresh token.
        background_refresh_token_interval (int): Background refresh token interval.

    Returns:
        AsyncClient: AsyncClient.
    """

    self = cls(
        api_key,
        api_secret,
        access_token,
        refresh_token,
        requests_params,
        session_params,
        loop,
        background_relogin,
        background_relogin_interval,
        background_refresh_token,
        background_refresh_token_interval,
    )

    await self._handle_login()
    return self

create_order(market, amount1, price, mode, type, identifier=None, price_limit=None, price_stop=None, price_limit_oco=None, amount2=None, **kwargs) async

Create order.

Parameters:

Name Type Description Default
market int

Market.

required
amount1 float

Amount1.

required
price float

Price.

required
mode OrderModes

Mode.

required
type OrderTypes

Type.

required
identifier str

Identifier.

None
price_limit float

Price limit.

None
price_stop float

Price stop.

None
price_limit_oco float

Price limit oco.

None
amount2 float

Amount2.

None
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def create_order(  # type: ignore[no-untyped-def, override]
    self,
    market: int,
    amount1: float,
    price: float,
    mode: t.OrderModes,
    type: t.OrderTypes,  # pylint: disable=redefined-builtin
    identifier: t.OptionalStr = None,
    price_limit: t.OptionalFloat = None,
    price_stop: t.OptionalFloat = None,
    price_limit_oco: t.OptionalFloat = None,
    amount2: t.OptionalFloat = None,
    **kwargs,
) -> t.CreateOrderResponse:
    """
    Create order.

    Args:
        market (int): Market.
        amount1 (float): Amount1.
        price (float): Price.
        mode (OrderModes): Mode.
        type (OrderTypes): Type.
        identifier (str): Identifier.
        price_limit (float): Price limit.
        price_stop (float): Price stop.
        price_limit_oco (float): Price limit oco.
        amount2 (float): Amount2.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#34b353d77b)
    """

    kwargs["json"] = {k: v for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
    return await self._post(self.ORDERS_URL, signed=True, **kwargs)  # type: ignore[return-value]

get_currencies_info(page=1, **kwargs) async

Get currencies info.

Parameters:

Name Type Description Default
page int

Page.

1
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Notes

Rate limit: 10000/day or 200/minute if you are authenticated.

Source code in src/bitpin/clients/async_client.py
async def get_currencies_info(  # type: ignore[no-untyped-def, override]
    self, page: int = 1, **kwargs
) -> t.DictStrAny:
    """
    Get currencies info.

    Args:
        page (int): Page.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#7e59da3d0d)

    Notes:
        Rate limit: 10000/day or 200/minute if you are authenticated.
    """

    return await self._get(self.CURRENCIES_LIST_URL.format(page), **kwargs)

get_markets_info(page=1, **kwargs) async

Get markets info.

Parameters:

Name Type Description Default
page int

Page.

1
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Notes

Rate limit: 10000/day or 200/minute if you are authenticated.

Source code in src/bitpin/clients/async_client.py
async def get_markets_info(self, page: int = 1, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def, override]
    """
    Get markets info.

    Args:
        page (int): Page.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#334792bb2b)

    Notes:
        Rate limit: 10000/day or 200/minute if you are authenticated.
    """

    return await self._get(self.MARKETS_LIST_URL.format(page), **kwargs)

get_orderbook(market_id, type, **kwargs) async

Get orderbook.

Parameters:

Name Type Description Default
market_id int

Market ID.

required
type OrderTypes

Type.

required
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def get_orderbook(  # type: ignore[no-untyped-def, override]
    self,
    market_id: int,
    type: t.OrderTypes,
    **kwargs,  # pylint: disable=redefined-builtin
) -> t.OrderbookResponse:
    """
    Get orderbook.

    Args:
        market_id (int): Market ID.
        type (OrderTypes): Type.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#ec7180fc0e)
    """
    return await self._get(  # type: ignore[return-value]
        self.ORDERBOOK_URL.format(market_id, str(type)), version=self.PUBLIC_API_VERSION_2, **kwargs
    )

get_recent_trades(market_id, **kwargs) async

Get recent trades.

Parameters:

Name Type Description Default
market_id int

Market ID.

required
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def get_recent_trades(  # type: ignore[no-untyped-def, override]
    self, market_id: int, **kwargs
) -> t.TradeResponse:
    """
    Get recent trades.

    Args:
        market_id (int): Market ID.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#1dd63530b5)
    """

    return await self._get(self.RECENT_TRADES_URL.format(market_id), **kwargs)  # type: ignore[return-value]

get_user_info(**kwargs) async

Get user info.

Parameters:

Name Type Description Default
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def get_user_info(self, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def, override]
    """
    Get user info.

    Args:
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#5b3c85d79e)
    """

    return await self._get(self.USER_INFO_URL, signed=True, **kwargs)

get_user_orders(market_id=None, type=None, state=None, mode=None, identifier=None, page=1, **kwargs) async

Get user orders.

Parameters:

Name Type Description Default
market_id int

Market ID.

None
type OrderTypes

Type.

None
state str

State.

None
mode str

Mode.

None
identifier str

Identifier.

None
page int

Page.

1
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def get_user_orders(  # type: ignore[no-untyped-def, override]
    self,
    market_id: t.OptionalInt = None,
    type: t.OptionalOrderTypes = None,  # pylint: disable=redefined-builtin
    state: t.OptionalStr = None,
    mode: t.OptionalStr = None,
    identifier: t.OptionalStr = None,
    page: int = 1,
    **kwargs,
) -> t.OpenOrdersResponse:
    """
    Get user orders.

    Args:
        market_id (int): Market ID.
        type (OrderTypes): Type.
        state (str): State.
        mode (str): Mode.
        identifier (str): Identifier.
        page (int): Page.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#8a7c2a2af5)
    """

    kwargs["params"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
    return await self._get(self.ORDERS_URL, signed=True, **kwargs)  # type: ignore[return-value]

get_user_trades(market_id=None, type=None, page=1, **kwargs) async

Get user trades.

Parameters:

Name Type Description Default
market_id int

Market ID.

None
type OrderTypes

Type.

None
page int

Page.

1
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def get_user_trades(  # type: ignore[no-untyped-def, override]
    self,
    market_id: t.OptionalInt = None,
    type: t.OptionalOrderTypes = None,  # pylint: disable=redefined-builtin
    page: int = 1,
    **kwargs,
) -> t.DictStrAny:
    """
    Get user trades.

    Args:
        market_id (int): Market ID.
        type (OrderTypes): Type.
        page (int): Page.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#3fe8d57657)
    """

    kwargs["params"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
    return await self._get(self.USER_TRADES_URL, signed=True, **kwargs)

get_wallets(**kwargs) async

Get wallets.

Parameters:

Name Type Description Default
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Notes

Rate limit: 10000/day.

Source code in src/bitpin/clients/async_client.py
async def get_wallets(self, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def, override]
    """
    Get wallets.

    Args:
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#9b93495188)

    Notes:
        Rate limit: 10000/day.
    """

    return await self._get(self.WALLETS_URL, signed=True, **kwargs)

login(**kwargs) async

Login and set (refresh_token/access_token).

Parameters:

Name Type Description Default
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response LoginResponse

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def login(self, **kwargs) -> t.LoginResponse:  # type: ignore[no-untyped-def, override]
    """
    Login and set (refresh_token/access_token).

    Args:
        **kwargs: Kwargs.

    Returns:
        Response (LoginResponse): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#02c24a5326)
    """

    kwargs["json"] = {"api_key": self.api_key, "secret_key": self.api_secret}
    _: t.LoginResponse = await self._post(self.LOGIN_URL, **kwargs)  # type: ignore[assignment]

    self.refresh_token = _["refresh"]
    self.access_token = _["access"]

    return _

refresh_access_token(refresh_token=None, **kwargs) async

Refresh token.

Parameters:

Name Type Description Default
refresh_token str

Refresh token.

None
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response RefreshTokenResponse

Response.

References

API Docs

Source code in src/bitpin/clients/async_client.py
async def refresh_access_token(  # type: ignore[no-untyped-def, override]
    self, refresh_token: t.OptionalStr = None, **kwargs
) -> t.RefreshTokenResponse:
    """
    Refresh token.

    Args:
        refresh_token (str): Refresh token.
        **kwargs: Kwargs.

    Returns:
        Response (RefreshTokenResponse): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#9b81094f74)
    """

    kwargs["json"] = {"refresh": refresh_token or self.refresh_token}
    _: t.RefreshTokenResponse = await self._post(self.REFRESH_TOKEN_URL, **kwargs)  # type: ignore[assignment]

    self.access_token = _["access"]

    return _

Client

Bases: CoreClient

Client.

Methods:

Name Description
login

Login and set (refresh_token/access_token)

refresh_access_token

Refresh token.

get_user_info

Get user info.

get_currencies_info

Get currencies info.

get_markets_info

Get markets info.

get_wallets

Get wallets.

get_orderbook

Get orderbook.

get_recent_trades

Get recent trades.

get_user_orders

Get use orders.

create_order

Create order.

cancel_order

Cancel order.

get_user_trades

Get user trades.

close_connection

Close connection.

Attributes:

Name Type Description
session ClientSession

Session.

api_key str

API key.

api_secret str

API secret.

refresh_token str

Refresh token.

access_token str

Access token.

Source code in src/bitpin/clients/client.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
class Client(CoreClient):
    """
    Client.

    Methods:
        login: Login and set (refresh_token/access_token)
        refresh_access_token: Refresh token.
        get_user_info: Get user info.
        get_currencies_info: Get currencies info.
        get_markets_info: Get markets info.
        get_wallets: Get wallets.
        get_orderbook: Get orderbook.
        get_recent_trades: Get recent trades.
        get_user_orders: Get use orders.
        create_order: Create order.
        cancel_order: Cancel order.
        get_user_trades: Get user trades.
        close_connection: Close connection.

    Attributes:
        session (aiohttp.ClientSession): Session.
        api_key (str): API key.
        api_secret (str): API secret.
        refresh_token (str): Refresh token.
        access_token (str): Access token.
    """

    def __init__(  # type: ignore[no-untyped-def]
        self,
        api_key: t.OptionalStr = None,
        api_secret: t.OptionalStr = None,
        access_token: t.OptionalStr = None,
        refresh_token: t.OptionalStr = None,
        requests_params: t.OptionalDictStrAny = None,
        background_relogin: bool = False,
        background_relogin_interval: int = 60 * 60 * 24 * 6,
        background_refresh_token: bool = False,
        background_refresh_token_interval: int = 60 * 13,
    ):
        """
        Constructor.

        Args:
            api_key (str): API key.
            api_secret (str): API secret.
            access_token (str): Access token.
            refresh_token (str): Refresh token.
            requests_params (dict): Requests params.
            background_relogin (bool): Background refresh.
            background_relogin_interval (int): Background refresh interval.
            background_refresh_token (bool): Background refresh token.
            background_refresh_token_interval (int): Background refresh token interval.

        Notes:
            If `api_key` and `api_secret` are not provided, they will be read from the environment variables
            `BITPIN_API_KEY` and `BITPIN_API_SECRET` respectively.

            If `access_token` and `refresh_token` are not provided, they will be read from the environment variables
            `BITPIN_ACCESS_TOKEN` and `BITPIN_REFRESH_TOKEN` respectively.

            If `requests_params` are provided, they will be used as default for every request.

            If `requests_params` are provided in `kwargs`, they will override existing `requests_params`.

            If `background_relogin` is enabled, access token will be refreshed in background every
            `background_relogin_interval` seconds.

            If `background_refresh_token` is enabled, refresh token will be refreshed in background every
            `background_refresh_token_interval` seconds.
        """

        super().__init__(
            api_key,
            api_secret,
            access_token,
            refresh_token,
            requests_params,
            background_relogin,
            background_relogin_interval,
            background_refresh_token,
            background_refresh_token_interval,
        )

        self._handle_login()

    def _init_session(self) -> requests.Session:
        """
        Initialize session.

        Returns:
            session (aiohttp.ClientSession): Session.

        """

        session = requests.Session()
        session.headers["Content-Type"] = "application/json"
        session.headers["Accept"] = "application/json"
        return session

    def _get(  # type: ignore[no-untyped-def]
        self,
        path: str,
        signed: bool = False,
        version: str = CoreClient.PUBLIC_API_VERSION_1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Make a GET request.

        Args:
            path (str): Path.
            signed (bool): Signed.
            version (str): Version.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        return self._request_api(enums.RequestMethod.GET, path, signed, version, **kwargs)

    def _post(  # type: ignore[no-untyped-def]
        self,
        path: str,
        signed: bool = False,
        version: str = CoreClient.PUBLIC_API_VERSION_1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Make a POST request.

        Args:
            path (str): Path.
            signed (bool): Signed.
            version (str): Version.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        return self._request_api(enums.RequestMethod.POST, path, signed, version, **kwargs)

    def _delete(  # type: ignore[no-untyped-def]
        self,
        path: str,
        signed: bool = False,
        version: str = CoreClient.PUBLIC_API_VERSION_1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Make a DELETE request.

        Args:
            path (str): Path.
            signed (bool): Signed.
            version (str): Version.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        return self._request_api(enums.RequestMethod.DELETE, path, signed, version, **kwargs)

    def _request_api(  # type: ignore[no-untyped-def]
        self,
        method: t.RequestMethods,
        path: str,
        signed: bool = False,
        version: str = CoreClient.PUBLIC_API_VERSION_1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Request API.

        Args:
            method (RequestMethod): Method.
            path (str): Path.
            signed (bool): Signed.
            version (str): Version.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        uri = self._create_api_uri(path, version)
        return self._request(method, uri, signed, **kwargs)

    def _request(  # type: ignore[no-untyped-def]
        self, method: t.RequestMethods, uri: str, signed: bool, **kwargs
    ) -> t.DictStrAny:
        """
        Request.

        Args:
            method (RequestMethod): Method.
            uri (str): URI.
            signed (bool): Signed.
            **kwargs: Kwargs.

        Returns:
            dict: Response.
        """

        kwargs = self._get_request_kwargs(method, signed, **kwargs)

        with getattr(self.session, method)(uri, **kwargs) as response:
            self.response = response  # pylint: disable=attribute-defined-outside-init
            return self._handle_response(response)

    @staticmethod
    def _handle_response(response: requests.Response) -> t.DictStrAny:  # type: ignore[override]
        """
        Handle response.

        Args:
            response (aiohttp.ClientResponse): Response.

        Returns:
            dict: Response.

        Raises:
            APIException: API Exception.
            RequestException: Request Exception.
        """

        if not str(response.status_code).startswith("2"):
            if response.request.method.lower() == enums.RequestMethod.DELETE:  # type: ignore[union-attr]
                return {"status": "success", "id": response.request.path_url.split("/")[-2]}
            raise APIException(response, response.status_code, response.text)
        try:
            return response.json()  # type: ignore[no-any-return]
        except ValueError as exc:
            raise RequestException(f"Invalid Response: {response.text}") from exc

    def _handle_login(self) -> None:
        """Handle login."""

        if self.api_key and self.api_secret:
            self.login()

        if self._background_relogin:
            Thread(target=self._background_relogin_task, daemon=True).start()

        if self._background_refresh_token:
            Thread(target=self._background_refresh_token_task, daemon=True).start()

    def _background_relogin_task(self) -> None:
        """Background relogin task."""

        while True:
            try:
                self.login()
                time.sleep(self._background_relogin_interval)
            except Exception:  # pylint: disable=broad-except
                continue

    def _background_refresh_token_task(self) -> None:
        """Background refresh token task."""

        while True:
            try:
                self.refresh_access_token()
                time.sleep(self._background_refresh_token_interval)
            except Exception:  # pylint: disable=broad-except
                continue

    def login(self, **kwargs) -> t.LoginResponse:  # type: ignore[no-untyped-def]
        """
        Login and set (refresh_token/access_token).

        Args:
            **kwargs: Kwargs.

        Returns:
            Response (LoginResponse): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#02c24a5326)
        """

        kwargs["json"] = {"api_key": self.api_key, "secret_key": self.api_secret}
        _: t.LoginResponse = self._post(self.LOGIN_URL, **kwargs)  # type: ignore[assignment]

        self.refresh_token = _["refresh"]
        self.access_token = _["access"]

        return _

    def refresh_access_token(  # type: ignore[no-untyped-def]
        self, refresh_token: t.OptionalStr = None, **kwargs
    ) -> t.RefreshTokenResponse:
        """
        Refresh token.

        Args:
            refresh_token (str): Refresh token.
            **kwargs: Kwargs.

        Returns:
            Response (RefreshTokenResponse): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#9b81094f74)
        """

        kwargs["json"] = {"refresh": refresh_token or self.refresh_token}
        _: t.RefreshTokenResponse = self._post(self.REFRESH_TOKEN_URL, **kwargs)  # type: ignore[assignment]

        self.access_token = _["access"]

        return _

    def get_user_info(self, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def]
        """
        Get user info.

        Args:
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#5b3c85d79e)
        """

        return self._get(self.USER_INFO_URL, signed=True, **kwargs)

    def get_currencies_info(self, page: int = 1, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def]
        """
        Get currencies info.

        Args:
            page (int): Page.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#7e59da3d0d)

        Notes:
            Rate limit: 10000/day or 200/minute if you are authenticated.
        """

        return self._get(self.CURRENCIES_LIST_URL.format(page), **kwargs)

    def get_markets_info(self, page: int = 1, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def]
        """
        Get markets info.

        Args:
            page (int): Page.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#334792bb2b)

        Notes:
            Rate limit: 10000/day or 200/minute if you are authenticated.
        """

        return self._get(self.MARKETS_LIST_URL.format(page), **kwargs)

    def get_wallets(self, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def]
        """
        Get wallets.

        Args:
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#9b93495188)

        Notes:
            Rate limit: 10000/day.
        """

        return self._get(self.WALLETS_URL, signed=True, **kwargs)

    def get_orderbook(  # type: ignore[no-untyped-def]
        self,
        market_id: int,
        type: t.OrderTypes,
        **kwargs,  # pylint: disable=redefined-builtin
    ) -> t.OrderbookResponse:
        """
        Get orderbook.

        Args:
            market_id (int): Market ID.
            type (OrderTypes): Type.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#ec7180fc0e)
        """

        return self._get(self.ORDERBOOK_URL.format(market_id, str(type)), **kwargs)  # type: ignore[return-value]

    def get_recent_trades(self, market_id: int, **kwargs) -> t.TradeResponse:  # type: ignore[no-untyped-def]
        """
        Get recent trades.

        Args:
            market_id (int): Market ID.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#1dd63530b5)
        """

        return self._get(self.RECENT_TRADES_URL.format(market_id), **kwargs)  # type: ignore[return-value]

    def get_user_orders(  # type: ignore[no-untyped-def]
        self,
        market_id: t.OptionalInt = None,
        type: t.OptionalOrderTypes = None,  # pylint: disable=redefined-builtin
        state: t.OptionalStr = None,
        mode: t.OptionalStr = None,
        identifier: t.OptionalStr = None,
        page: int = 1,
        **kwargs,
    ) -> t.OpenOrdersResponse:
        """
        Get user Orders.

        Args:
            market_id (int): Market ID.
            type (OrderTypes): Type.
            state (str): State.
            mode (str): Mode.
            identifier (str): Identifier.
            page (int): Page.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#8a7c2a2af5)
        """

        kwargs["params"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
        return self._get(self.ORDERS_URL, signed=True, **kwargs)  # type: ignore[return-value]

    def create_order(  # type: ignore[no-untyped-def]
        self,
        market: int,
        amount1: float,
        price: float,
        mode: t.OrderModes,
        type: t.OrderTypes,  # pylint: disable=redefined-builtin
        identifier: t.OptionalStr = None,
        price_limit: t.OptionalFloat = None,
        price_stop: t.OptionalFloat = None,
        price_limit_oco: t.OptionalFloat = None,
        amount2: t.OptionalFloat = None,
        **kwargs,
    ) -> t.CreateOrderResponse:
        """
        Create order.

        Args:
            market (int): Market.
            amount1 (float): Amount1.
            price (float): Price.
            mode (OrderModes): Mode.
            type (OrderTypes): Type.
            identifier (str): Identifier.
            price_limit (float): Price limit.
            price_stop (float): Price stop.
            price_limit_oco (float): Price limit oco.
            amount2 (float): Amount2.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#34b353d77b)
        """

        kwargs["json"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
        return self._post(self.ORDERS_URL, signed=True, **kwargs)  # type: ignore[return-value]

    def cancel_order(self, order_id: str, **kwargs) -> t.CancelOrderResponse:  # type: ignore[no-untyped-def]
        """
        Cancel order.

        Args:
            order_id (str): Order ID.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#3fe8d57657)
        """

        return self._delete(self.ORDERS_URL + f"{order_id}/", signed=True, **kwargs)  # type: ignore[return-value]

    def get_user_trades(  # type: ignore[no-untyped-def]
        self,
        market_id: t.OptionalInt = None,
        type: t.OptionalOrderTypes = None,  # pylint: disable=redefined-builtin
        page: int = 1,
        **kwargs,
    ) -> t.DictStrAny:
        """
        Get user trades.

        Args:
            market_id (int): Market ID.
            type (OrderTypes): Type.
            page (int): Page.
            **kwargs: Kwargs.

        Returns:
            Response (dict): Response.

        References:
            [API Docs](https://docs.bitpin.ir/#3fe8d57657)
        """

        kwargs["params"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
        return self._get(self.USER_TRADES_URL, signed=True, **kwargs)

    def close_connection(self) -> None:
        """Close connection."""

        self.session.close()

__init__(api_key=None, api_secret=None, access_token=None, refresh_token=None, requests_params=None, background_relogin=False, background_relogin_interval=60 * 60 * 24 * 6, background_refresh_token=False, background_refresh_token_interval=60 * 13)

Constructor.

Parameters:

Name Type Description Default
api_key str

API key.

None
api_secret str

API secret.

None
access_token str

Access token.

None
refresh_token str

Refresh token.

None
requests_params dict

Requests params.

None
background_relogin bool

Background refresh.

False
background_relogin_interval int

Background refresh interval.

60 * 60 * 24 * 6
background_refresh_token bool

Background refresh token.

False
background_refresh_token_interval int

Background refresh token interval.

60 * 13
Notes

If api_key and api_secret are not provided, they will be read from the environment variables BITPIN_API_KEY and BITPIN_API_SECRET respectively.

If access_token and refresh_token are not provided, they will be read from the environment variables BITPIN_ACCESS_TOKEN and BITPIN_REFRESH_TOKEN respectively.

If requests_params are provided, they will be used as default for every request.

If requests_params are provided in kwargs, they will override existing requests_params.

If background_relogin is enabled, access token will be refreshed in background every background_relogin_interval seconds.

If background_refresh_token is enabled, refresh token will be refreshed in background every background_refresh_token_interval seconds.

Source code in src/bitpin/clients/client.py
def __init__(  # type: ignore[no-untyped-def]
    self,
    api_key: t.OptionalStr = None,
    api_secret: t.OptionalStr = None,
    access_token: t.OptionalStr = None,
    refresh_token: t.OptionalStr = None,
    requests_params: t.OptionalDictStrAny = None,
    background_relogin: bool = False,
    background_relogin_interval: int = 60 * 60 * 24 * 6,
    background_refresh_token: bool = False,
    background_refresh_token_interval: int = 60 * 13,
):
    """
    Constructor.

    Args:
        api_key (str): API key.
        api_secret (str): API secret.
        access_token (str): Access token.
        refresh_token (str): Refresh token.
        requests_params (dict): Requests params.
        background_relogin (bool): Background refresh.
        background_relogin_interval (int): Background refresh interval.
        background_refresh_token (bool): Background refresh token.
        background_refresh_token_interval (int): Background refresh token interval.

    Notes:
        If `api_key` and `api_secret` are not provided, they will be read from the environment variables
        `BITPIN_API_KEY` and `BITPIN_API_SECRET` respectively.

        If `access_token` and `refresh_token` are not provided, they will be read from the environment variables
        `BITPIN_ACCESS_TOKEN` and `BITPIN_REFRESH_TOKEN` respectively.

        If `requests_params` are provided, they will be used as default for every request.

        If `requests_params` are provided in `kwargs`, they will override existing `requests_params`.

        If `background_relogin` is enabled, access token will be refreshed in background every
        `background_relogin_interval` seconds.

        If `background_refresh_token` is enabled, refresh token will be refreshed in background every
        `background_refresh_token_interval` seconds.
    """

    super().__init__(
        api_key,
        api_secret,
        access_token,
        refresh_token,
        requests_params,
        background_relogin,
        background_relogin_interval,
        background_refresh_token,
        background_refresh_token_interval,
    )

    self._handle_login()

cancel_order(order_id, **kwargs)

Cancel order.

Parameters:

Name Type Description Default
order_id str

Order ID.

required
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def cancel_order(self, order_id: str, **kwargs) -> t.CancelOrderResponse:  # type: ignore[no-untyped-def]
    """
    Cancel order.

    Args:
        order_id (str): Order ID.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#3fe8d57657)
    """

    return self._delete(self.ORDERS_URL + f"{order_id}/", signed=True, **kwargs)  # type: ignore[return-value]

close_connection()

Close connection.

Source code in src/bitpin/clients/client.py
def close_connection(self) -> None:
    """Close connection."""

    self.session.close()

create_order(market, amount1, price, mode, type, identifier=None, price_limit=None, price_stop=None, price_limit_oco=None, amount2=None, **kwargs)

Create order.

Parameters:

Name Type Description Default
market int

Market.

required
amount1 float

Amount1.

required
price float

Price.

required
mode OrderModes

Mode.

required
type OrderTypes

Type.

required
identifier str

Identifier.

None
price_limit float

Price limit.

None
price_stop float

Price stop.

None
price_limit_oco float

Price limit oco.

None
amount2 float

Amount2.

None
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def create_order(  # type: ignore[no-untyped-def]
    self,
    market: int,
    amount1: float,
    price: float,
    mode: t.OrderModes,
    type: t.OrderTypes,  # pylint: disable=redefined-builtin
    identifier: t.OptionalStr = None,
    price_limit: t.OptionalFloat = None,
    price_stop: t.OptionalFloat = None,
    price_limit_oco: t.OptionalFloat = None,
    amount2: t.OptionalFloat = None,
    **kwargs,
) -> t.CreateOrderResponse:
    """
    Create order.

    Args:
        market (int): Market.
        amount1 (float): Amount1.
        price (float): Price.
        mode (OrderModes): Mode.
        type (OrderTypes): Type.
        identifier (str): Identifier.
        price_limit (float): Price limit.
        price_stop (float): Price stop.
        price_limit_oco (float): Price limit oco.
        amount2 (float): Amount2.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#34b353d77b)
    """

    kwargs["json"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
    return self._post(self.ORDERS_URL, signed=True, **kwargs)  # type: ignore[return-value]

get_currencies_info(page=1, **kwargs)

Get currencies info.

Parameters:

Name Type Description Default
page int

Page.

1
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Notes

Rate limit: 10000/day or 200/minute if you are authenticated.

Source code in src/bitpin/clients/client.py
def get_currencies_info(self, page: int = 1, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def]
    """
    Get currencies info.

    Args:
        page (int): Page.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#7e59da3d0d)

    Notes:
        Rate limit: 10000/day or 200/minute if you are authenticated.
    """

    return self._get(self.CURRENCIES_LIST_URL.format(page), **kwargs)

get_markets_info(page=1, **kwargs)

Get markets info.

Parameters:

Name Type Description Default
page int

Page.

1
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Notes

Rate limit: 10000/day or 200/minute if you are authenticated.

Source code in src/bitpin/clients/client.py
def get_markets_info(self, page: int = 1, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def]
    """
    Get markets info.

    Args:
        page (int): Page.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#334792bb2b)

    Notes:
        Rate limit: 10000/day or 200/minute if you are authenticated.
    """

    return self._get(self.MARKETS_LIST_URL.format(page), **kwargs)

get_orderbook(market_id, type, **kwargs)

Get orderbook.

Parameters:

Name Type Description Default
market_id int

Market ID.

required
type OrderTypes

Type.

required
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def get_orderbook(  # type: ignore[no-untyped-def]
    self,
    market_id: int,
    type: t.OrderTypes,
    **kwargs,  # pylint: disable=redefined-builtin
) -> t.OrderbookResponse:
    """
    Get orderbook.

    Args:
        market_id (int): Market ID.
        type (OrderTypes): Type.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#ec7180fc0e)
    """

    return self._get(self.ORDERBOOK_URL.format(market_id, str(type)), **kwargs)  # type: ignore[return-value]

get_recent_trades(market_id, **kwargs)

Get recent trades.

Parameters:

Name Type Description Default
market_id int

Market ID.

required
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def get_recent_trades(self, market_id: int, **kwargs) -> t.TradeResponse:  # type: ignore[no-untyped-def]
    """
    Get recent trades.

    Args:
        market_id (int): Market ID.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#1dd63530b5)
    """

    return self._get(self.RECENT_TRADES_URL.format(market_id), **kwargs)  # type: ignore[return-value]

get_user_info(**kwargs)

Get user info.

Parameters:

Name Type Description Default
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def get_user_info(self, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def]
    """
    Get user info.

    Args:
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#5b3c85d79e)
    """

    return self._get(self.USER_INFO_URL, signed=True, **kwargs)

get_user_orders(market_id=None, type=None, state=None, mode=None, identifier=None, page=1, **kwargs)

Get user Orders.

Parameters:

Name Type Description Default
market_id int

Market ID.

None
type OrderTypes

Type.

None
state str

State.

None
mode str

Mode.

None
identifier str

Identifier.

None
page int

Page.

1
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def get_user_orders(  # type: ignore[no-untyped-def]
    self,
    market_id: t.OptionalInt = None,
    type: t.OptionalOrderTypes = None,  # pylint: disable=redefined-builtin
    state: t.OptionalStr = None,
    mode: t.OptionalStr = None,
    identifier: t.OptionalStr = None,
    page: int = 1,
    **kwargs,
) -> t.OpenOrdersResponse:
    """
    Get user Orders.

    Args:
        market_id (int): Market ID.
        type (OrderTypes): Type.
        state (str): State.
        mode (str): Mode.
        identifier (str): Identifier.
        page (int): Page.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#8a7c2a2af5)
    """

    kwargs["params"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
    return self._get(self.ORDERS_URL, signed=True, **kwargs)  # type: ignore[return-value]

get_user_trades(market_id=None, type=None, page=1, **kwargs)

Get user trades.

Parameters:

Name Type Description Default
market_id int

Market ID.

None
type OrderTypes

Type.

None
page int

Page.

1
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def get_user_trades(  # type: ignore[no-untyped-def]
    self,
    market_id: t.OptionalInt = None,
    type: t.OptionalOrderTypes = None,  # pylint: disable=redefined-builtin
    page: int = 1,
    **kwargs,
) -> t.DictStrAny:
    """
    Get user trades.

    Args:
        market_id (int): Market ID.
        type (OrderTypes): Type.
        page (int): Page.
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#3fe8d57657)
    """

    kwargs["params"] = {k: str(v) for k, v in locals().items() if v is not None and k not in ("self", "kwargs")}
    return self._get(self.USER_TRADES_URL, signed=True, **kwargs)

get_wallets(**kwargs)

Get wallets.

Parameters:

Name Type Description Default
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response dict

Response.

References

API Docs

Notes

Rate limit: 10000/day.

Source code in src/bitpin/clients/client.py
def get_wallets(self, **kwargs) -> t.DictStrAny:  # type: ignore[no-untyped-def]
    """
    Get wallets.

    Args:
        **kwargs: Kwargs.

    Returns:
        Response (dict): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#9b93495188)

    Notes:
        Rate limit: 10000/day.
    """

    return self._get(self.WALLETS_URL, signed=True, **kwargs)

login(**kwargs)

Login and set (refresh_token/access_token).

Parameters:

Name Type Description Default
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response LoginResponse

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def login(self, **kwargs) -> t.LoginResponse:  # type: ignore[no-untyped-def]
    """
    Login and set (refresh_token/access_token).

    Args:
        **kwargs: Kwargs.

    Returns:
        Response (LoginResponse): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#02c24a5326)
    """

    kwargs["json"] = {"api_key": self.api_key, "secret_key": self.api_secret}
    _: t.LoginResponse = self._post(self.LOGIN_URL, **kwargs)  # type: ignore[assignment]

    self.refresh_token = _["refresh"]
    self.access_token = _["access"]

    return _

refresh_access_token(refresh_token=None, **kwargs)

Refresh token.

Parameters:

Name Type Description Default
refresh_token str

Refresh token.

None
**kwargs

Kwargs.

{}

Returns:

Name Type Description
Response RefreshTokenResponse

Response.

References

API Docs

Source code in src/bitpin/clients/client.py
def refresh_access_token(  # type: ignore[no-untyped-def]
    self, refresh_token: t.OptionalStr = None, **kwargs
) -> t.RefreshTokenResponse:
    """
    Refresh token.

    Args:
        refresh_token (str): Refresh token.
        **kwargs: Kwargs.

    Returns:
        Response (RefreshTokenResponse): Response.

    References:
        [API Docs](https://docs.bitpin.ir/#9b81094f74)
    """

    kwargs["json"] = {"refresh": refresh_token or self.refresh_token}
    _: t.RefreshTokenResponse = self._post(self.REFRESH_TOKEN_URL, **kwargs)  # type: ignore[assignment]

    self.access_token = _["access"]

    return _