dragonfipy 0.1.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,11 @@
1
+ Metadata-Version: 2.3
2
+ Name: dragonfipy
3
+ Version: 0.1.0
4
+ Summary: DragonFi API wrapper
5
+ Author: Chris Irag
6
+ Author-email: Chris Irag <iragca@pm.me>
7
+ Requires-Dist: httpx>=0.28.1
8
+ Requires-Dist: python-dateutil>=2.9.0.post0
9
+ Requires-Python: >=3.13
10
+ Description-Content-Type: text/markdown
11
+
File without changes
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "dragonfipy"
3
+ version = "0.1.0"
4
+ description = "DragonFi API wrapper"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = [
8
+ "httpx>=0.28.1",
9
+ "python-dateutil>=2.9.0.post0",
10
+ ]
11
+
12
+ [[project.authors]]
13
+ name = "Chris Irag"
14
+ email = "iragca@pm.me"
15
+
16
+ [build-system]
17
+ requires = ["uv_build>=0.13.0,<0.14.0"]
18
+ build-backend = "uv_build"
19
+
20
+ [tool.uv.build-backend]
21
+ module-name = "dragonpy"
22
+ module-root = "src"
23
+
24
+ [tool.ruff]
25
+ line-length = 79
26
+ indent-width = 4
27
+
28
+ [tool.ty.environment]
29
+ python = ".venv"
30
+
31
+ [tool.pytest.ini_options]
32
+ pythonpath = ["src"]
33
+ testpaths = ["tests"]
34
+ addopts = "--cov=src --cov-report=term-missing"
35
+
36
+ [dependency-groups]
37
+ dev = [
38
+ "pre-commit>=4.7.0",
39
+ "pytest>=9.1.1",
40
+ "pytest-cov>=7.1.0",
41
+ "ruff>=0.17.2",
42
+ ]
@@ -0,0 +1,38 @@
1
+ [project]
2
+ name = "dragonfipy"
3
+ version = "0.1.0"
4
+ description = "DragonFi API wrapper"
5
+ readme = "README.md"
6
+ authors = [{ name = "Chris Irag", email = "iragca@pm.me" }]
7
+ requires-python = ">=3.13"
8
+ dependencies = [
9
+ "httpx>=0.28.1",
10
+ "python-dateutil>=2.9.0.post0",
11
+ ]
12
+
13
+ [build-system]
14
+ requires = ["uv_build>=0.13.0,<0.14.0"]
15
+ build-backend = "uv_build"
16
+
17
+ [tool.uv.build-backend]
18
+ module-name = "dragonpy"
19
+ module-root = "src"
20
+
21
+ [tool.ruff]
22
+ line-length = 79
23
+ indent-width = 4
24
+
25
+ [tool.ty.environment]
26
+ python = ".venv"
27
+ [dependency-groups]
28
+ dev = [
29
+ "pre-commit>=4.7.0",
30
+ "pytest>=9.1.1",
31
+ "pytest-cov>=7.1.0",
32
+ "ruff>=0.17.2",
33
+ ]
34
+
35
+ [tool.pytest.ini_options]
36
+ pythonpath = ["src"]
37
+ testpaths = ["tests"]
38
+ addopts = "--cov=src --cov-report=term-missing"
@@ -0,0 +1,3 @@
1
+ from .wrapper import DragonPy
2
+
3
+ __all__ = ["DragonPy"]
@@ -0,0 +1,6 @@
1
+ from http import HTTPStatus
2
+
3
+ from .api import DragonFiAPI
4
+ from .status import WSSStatus
5
+
6
+ __all__ = ["DragonFiAPI", "HTTPStatus", "WSSStatus"]
@@ -0,0 +1,7 @@
1
+ from enum import StrEnum
2
+
3
+
4
+ class DragonFiAPI(StrEnum):
5
+ REST_V1 = "https://api.dragonfi.ph/api/"
6
+ REST_V2 = "https://api.dragonfi.ph/api/v2/"
7
+ WSS = "wss://api.dragonfi.ph/"
@@ -0,0 +1,67 @@
1
+ # ------------------------------------------------------------------------------
2
+ # Attribution
3
+ # ------------------------------------------------------------------------------
4
+ # Portions of this module are derived from:
5
+ # https://github.com/Kludex/starlette/blob/7b2948fe7b7fff28bb018607d54cd4dfa518910e/starlette/status.py,
6
+ # Copyright (c) 2018 Encode OSS Ltd., licensed under the BSD 3-Clause License.
7
+ #
8
+ # The following license text is retained as required by the upstream license:
9
+ #
10
+ # Copyright (c) 2018, Encode OSS Ltd.
11
+ # All rights reserved.
12
+ #
13
+ # Redistribution and use in source and binary forms, with or without
14
+ # modification, are permitted provided that the following conditions are met:
15
+ #
16
+ # * Redistributions of source code must retain the above copyright notice, this
17
+ # list of conditions and the following disclaimer.
18
+ #
19
+ # * Redistributions in binary form must reproduce the above copyright notice,
20
+ # this list of conditions and the following disclaimer in the documentation
21
+ # and/or other materials provided with the distribution.
22
+ #
23
+ # * Neither the name of the copyright holder nor the names of its
24
+ # contributors may be used to endorse or promote products derived from
25
+ # this software without specific prior written permission.
26
+ #
27
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
31
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37
+ # POSSIBILITY OF SUCH DAMAGE.
38
+ # ------------------------------------------------------------------------------
39
+
40
+ from enum import IntEnum
41
+
42
+
43
+ class WSSStatus(IntEnum):
44
+ """
45
+ WebSocket status codes.
46
+
47
+ WebSocket codes
48
+ ---------------
49
+ https://www.iana.org/assignments/websocket/websocket.xml#close-code-number
50
+ https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
51
+ """
52
+
53
+ WS_1000_NORMAL_CLOSURE = 1000
54
+ WS_1001_GOING_AWAY = 1001
55
+ WS_1002_PROTOCOL_ERROR = 1002
56
+ WS_1003_UNSUPPORTED_DATA = 1003
57
+ WS_1005_NO_STATUS_RCVD = 1005
58
+ WS_1006_ABNORMAL_CLOSURE = 1006
59
+ WS_1007_INVALID_FRAME_PAYLOAD_DATA = 1007
60
+ WS_1008_POLICY_VIOLATION = 1008
61
+ WS_1009_MESSAGE_TOO_BIG = 1009
62
+ WS_1010_MANDATORY_EXT = 1010
63
+ WS_1011_INTERNAL_ERROR = 1011
64
+ WS_1012_SERVICE_RESTART = 1012
65
+ WS_1013_TRY_AGAIN_LATER = 1013
66
+ WS_1014_BAD_GATEWAY = 1014
67
+ WS_1015_TLS_HANDSHAKE = 1015
@@ -0,0 +1,132 @@
1
+ # ------------------------------------------------------------------------------
2
+ # Attribution
3
+ # ------------------------------------------------------------------------------
4
+ # Portions of this module are derived from:
5
+ # https://github.com/Kludex/starlette/blob/7b2948fe7b7fff28bb018607d54cd4dfa518910e/starlette/exceptions.py,
6
+ # Copyright (c) 2018 Encode OSS Ltd., licensed under the BSD 3-Clause License.
7
+ #
8
+ # The following license text is retained as required by the upstream license:
9
+ #
10
+ # Copyright (c) 2018, Encode OSS Ltd.
11
+ # All rights reserved.
12
+ #
13
+ # Redistribution and use in source and binary forms, with or without
14
+ # modification, are permitted provided that the following conditions are met:
15
+ #
16
+ # * Redistributions of source code must retain the above copyright notice, this
17
+ # list of conditions and the following disclaimer.
18
+ #
19
+ # * Redistributions in binary form must reproduce the above copyright notice,
20
+ # this list of conditions and the following disclaimer in the documentation
21
+ # and/or other materials provided with the distribution.
22
+ #
23
+ # * Neither the name of the copyright holder nor the names of its
24
+ # contributors may be used to endorse or promote products derived from
25
+ # this software without specific prior written permission.
26
+ #
27
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
31
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37
+ # POSSIBILITY OF SUCH DAMAGE.
38
+ # ------------------------------------------------------------------------------
39
+
40
+ import http.client
41
+
42
+
43
+ class HTTPException(Exception):
44
+ def __init__(
45
+ self,
46
+ status_code: int,
47
+ detail: str | None = None,
48
+ headers: dict[str, str] | None = None,
49
+ ) -> None:
50
+ if detail is None:
51
+ detail = http.client.responses.get(status_code, "")
52
+ self.status_code = status_code
53
+ self.detail = detail
54
+ self.headers = headers
55
+
56
+ def __str__(self) -> str:
57
+ return f"{self.status_code}: {self.detail}"
58
+
59
+ def __repr__(self) -> str:
60
+ class_name = self.__class__.__name__
61
+ return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
62
+
63
+
64
+ class WebSocketException(Exception):
65
+ def __init__(self, code: int, reason: str | None = None) -> None:
66
+ self.code = code
67
+ self.reason = reason or ""
68
+
69
+ def __str__(self) -> str:
70
+ return f"{self.code}: {self.reason}"
71
+
72
+ def __repr__(self) -> str:
73
+ class_name = self.__class__.__name__
74
+ return f"{class_name}(code={self.code!r}, reason={self.reason!r})"
75
+
76
+
77
+ # ---------------------------------------------------------------------
78
+ # Attribution
79
+ # ---------------------------------------------------------------------
80
+ # Portions of this module are derived from:
81
+ # https://github.com/fastapi/fastapi/blob/f5c6e9b4f9cadc1bf0f9a1fd672e621206b63007/fastapi/exceptions.py
82
+ # Copyright (c) 2018 Sebastián Ramírez, licensed under the MIT License.
83
+ #
84
+ # The following license text is retained as required by the upstream license:
85
+
86
+ # The MIT License (MIT)
87
+
88
+ # Copyright (c) 2018 Sebastián Ramírez
89
+
90
+ # Permission is hereby granted, free of charge, to any person obtaining
91
+ # a copy of this software and associated documentation files
92
+ # (the "Software"), to deal in the Software without restriction,
93
+ # including without limitation the rights to use, copy, modify, merge,
94
+ # publish, distribute, sublicense, and/or sell copies of the Software,
95
+ # and to permit persons to whom the Software is furnished to do so,
96
+ # subject to the following conditions:
97
+
98
+ # The above copyright notice and this permission notice shall be
99
+ # included in all copies or substantial portions of the Software.
100
+
101
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
102
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
103
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
104
+ # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
105
+ # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
106
+ # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
107
+ # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
108
+
109
+
110
+ class DragonPyError(RuntimeError):
111
+ """
112
+ A generic, DragonPy-specific error.
113
+ """
114
+
115
+ def __init__(self, message: str = ""):
116
+ self.message = message
117
+
118
+ def __str__(self) -> str:
119
+ if self.message == "":
120
+ return "DragonPy: Something unexpected happened"
121
+ return f"DragonPy: {self.message}"
122
+
123
+ def __repr__(self) -> str:
124
+ class_name = self.__class__.__name__
125
+ return f"{class_name}(message={self.message!r})"
126
+
127
+
128
+ class DragonPyDeprecationWarning(UserWarning):
129
+ """
130
+ A custom deprecation warning as DeprecationWarning is ignored
131
+ Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
132
+ """
File without changes
@@ -0,0 +1,18 @@
1
+ from typing import TypedDict
2
+
3
+
4
+ class Event(TypedDict):
5
+ type: str
6
+ symbol: str
7
+ candleType: str
8
+ open: float
9
+ high: float
10
+ low: float
11
+ volume: int
12
+ time: str
13
+ localtime: str
14
+ timeinSeconds: int
15
+
16
+
17
+ class Events(TypedDict):
18
+ events: Event
@@ -0,0 +1,70 @@
1
+ from typing import TypedDict
2
+
3
+
4
+ class RelatedStock(TypedDict):
5
+ stockCode: str
6
+ logoPath: str | None
7
+ change: float
8
+ changePercent: float
9
+ price: float
10
+
11
+
12
+ class GetStockProfile(TypedDict):
13
+ description: str
14
+ symbol: str
15
+ full_name: str
16
+ type: str
17
+ exchange: str
18
+ codeAndName: str
19
+ price: float
20
+ prevDayClosePrice: float
21
+ dayOpenPrice: float
22
+ bidPrice: float | None
23
+ askPrice: float | None
24
+ change: float
25
+ changePercent: float
26
+ lastTradeTime: str
27
+ isMarketOpen: bool
28
+ relatedStocks: list[RelatedStock]
29
+ dayChangePricePercent: float
30
+ averageVolume10: float
31
+ averageVolume20: float
32
+ dayVolume: float
33
+ dayLowPrice: float
34
+ dayHighPrice: float
35
+ weekHigh52: float
36
+ weekLow52: float
37
+ companyName: str
38
+ companyShortName: str
39
+ stockCode: str
40
+ website: str
41
+ logoPath: str
42
+ productCode: str
43
+ shariahIndicator: str
44
+ industryId: int
45
+ industryCode: str
46
+ industryName: str
47
+ sectorId: int
48
+ sectorCode: str
49
+ sectorName: str
50
+ listingDate: str | None
51
+ parValue: float
52
+ lacp: float
53
+ shortSellingEligible: bool
54
+ isREIT: bool
55
+ isPreferredStock: bool | None
56
+ preferredParentStockCode: str | None
57
+ isPERA: bool
58
+ floatLevel: float
59
+ sharesOutstanding: int
60
+ sharesFloat: int
61
+ isin: str
62
+ isDDS: bool | None
63
+ isDelisted: bool | None
64
+ isOldSymbol: bool
65
+ isIndices: bool
66
+ dateDelisted: str | None
67
+ oldStockCode: str | None
68
+ oldCompanyName: str | None
69
+ dividendYield: float
70
+ id: int
@@ -0,0 +1,6 @@
1
+ from .dashboard import DashboardService
2
+ from .funds import FundsService
3
+ from .securities import SecuritiesService
4
+ from .service import Service
5
+
6
+ __all__ = ["DashboardService", "FundsService", "SecuritiesService", "Service"]
@@ -0,0 +1,75 @@
1
+ from datetime import datetime
2
+ from typing import Literal, cast
3
+
4
+ from dateutil.relativedelta import relativedelta
5
+ from httpx import Client
6
+
7
+ from dragonpy.responses.dashboard import Events
8
+ from dragonpy.services.service import Service
9
+
10
+
11
+ class DashboardService(Service):
12
+ def __init__(self, client: Client, path: str = "Dashboard"):
13
+ super().__init__(client, path)
14
+
15
+ def get_delayed_bars(
16
+ self,
17
+ symbol: str,
18
+ candleType: Literal["1", "5", "15", "30", "1D", "1W", "1M"] = "1D",
19
+ count: int = 301,
20
+ delayInMinutes: int = 15,
21
+ time_range: tuple[datetime, datetime] | None = None,
22
+ ) -> Events:
23
+ """Get price action data for a specified symbol.
24
+
25
+ Parameters
26
+ ----------
27
+ symbol : str
28
+ Ticker symbol of the security or fund to fetch
29
+ candleType : str
30
+ 1: 1 minute
31
+ 5: 5 minutes
32
+ 15: 15 minutes
33
+ 30: 30 minutes
34
+ 1D: 1 day
35
+ 1W: 1 week
36
+ 1M: 1 month
37
+ time_range : tuple[datetime, datetime] | None
38
+ The pair of datetimes for the time range. (startDate, endDate)
39
+ """
40
+ if symbol == "":
41
+ raise ValueError("Symbol must not be empty.")
42
+
43
+ params = {
44
+ "symbol": symbol.upper().strip(),
45
+ "candleType": candleType,
46
+ "count": count,
47
+ "delayInMinutes": delayInMinutes,
48
+ }
49
+
50
+ if time_range is None:
51
+ now = datetime.now()
52
+ params["fromTime"] = int(
53
+ (now - relativedelta(years=1)).timestamp()
54
+ )
55
+ params["toTime"] = int(now.timestamp())
56
+ else:
57
+ if len(time_range) != 2:
58
+ raise ValueError(
59
+ "Time range must contain a start date and an end date."
60
+ )
61
+
62
+ start, end = time_range
63
+
64
+ if not isinstance(start, datetime) or not isinstance(
65
+ end, datetime
66
+ ):
67
+ raise TypeError("Time range values must be datetime objects.")
68
+
69
+ if start >= end:
70
+ raise ValueError("Start date must be earlier than end date.")
71
+
72
+ params["fromTime"] = int(time_range[0].timestamp())
73
+ params["toTime"] = int(time_range[1].timestamp())
74
+
75
+ return cast(Events, self._get("GetDelayedBars", params))
@@ -0,0 +1,8 @@
1
+ from httpx import Client
2
+
3
+ from .service import Service
4
+
5
+
6
+ class FundsService(Service):
7
+ def __init__(self, client: Client, path: str = "Funds"):
8
+ super().__init__(client, path)
File without changes
@@ -0,0 +1,18 @@
1
+ from typing import cast
2
+
3
+ from httpx import Client
4
+
5
+ from dragonpy.responses.securities import GetStockProfile
6
+
7
+ from .service import Service
8
+
9
+
10
+ class SecuritiesService(Service):
11
+ def __init__(self, client: Client, path: str = "Securities"):
12
+ super().__init__(client, path)
13
+
14
+ def get_stock_profile(self, stockCode: str) -> GetStockProfile:
15
+ return cast(
16
+ GetStockProfile,
17
+ self._get("GetStockProfile", {"stockCode": stockCode}),
18
+ )
@@ -0,0 +1,28 @@
1
+ from json import loads
2
+ from urllib.parse import urlencode
3
+
4
+ from httpx import Client
5
+
6
+ from dragonpy.enums import HTTPStatus
7
+ from dragonpy.exceptions import HTTPException
8
+ from dragonpy.utils import merge_url
9
+
10
+
11
+ class Service:
12
+ def __init__(self, client: Client, path: str):
13
+ self.client: Client = client
14
+ self.service_url: str = merge_url(str(client.base_url), path)
15
+
16
+ def _get(self, function: str, params: dict[str, str | int]) -> dict:
17
+ base_url = merge_url(self.service_url, function)
18
+ queries = urlencode(params)
19
+ req_url = f"{base_url}?{queries}"
20
+ response = self.client.get(req_url)
21
+ status = HTTPStatus(response.status_code)
22
+ if status.is_success:
23
+ if response.content == b"":
24
+ return {}
25
+
26
+ return loads(response.content)
27
+
28
+ raise HTTPException(response.status_code, detail=req_url)
@@ -0,0 +1,20 @@
1
+ from urllib.parse import urljoin
2
+
3
+
4
+ def _join_two(left: str, right: str) -> str:
5
+ base = left if left.endswith("/") else left + "/"
6
+ return urljoin(base, right)
7
+
8
+
9
+ def merge_url(*paths: str) -> str:
10
+ """Join paths regardless of the ending slash existing or not."""
11
+ if not paths:
12
+ raise ValueError("At least one path is required")
13
+
14
+ remaining = list(paths)
15
+ url = remaining.pop(0)
16
+
17
+ while remaining:
18
+ url = _join_two(url, remaining.pop(0))
19
+
20
+ return url
@@ -0,0 +1,13 @@
1
+ from httpx import Client
2
+
3
+ from dragonpy.enums import DragonFiAPI
4
+ from dragonpy.services import DashboardService, FundsService, SecuritiesService
5
+
6
+
7
+ class DragonPy:
8
+ def __init__(self, url: str | DragonFiAPI = DragonFiAPI.REST_V2):
9
+ self.api = url
10
+ self._client = Client(base_url=url, headers={"UserAgent": "dragonpy"})
11
+ self.dashboard = DashboardService(self._client, url)
12
+ self.funds = FundsService(self._client, url)
13
+ self.securities = SecuritiesService(self._client, url)