├── .github └── dependabot.yml ├── .gitignore ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── pytvlwcharts.ipynb ├── pytvlwcharts ├── __init__.py ├── __version__.py ├── generatedModels.py └── tvlwcharts.py └── setup.py /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "pip" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Techfane Technologies 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Tradingview's Lightweight-Charts (pytvlwcharts) 2 | An Experimental Python Wrapper For [Tradingview's Lightweight-Charts](https://tradingview.github.io/lightweight-charts/) To Be Used In Notebook Environments _(Google Colab etc.)_. [Example Lightweight-Charts](https://codesandbox.io/examples/package/lightweight-charts) 3 | 4 | #### _If You have liked the library, Do Star This Repository and Stay-Up-To-Date_ 5 |

6 | How To Star A Repository 7 |

8 | 9 | ## Instructions on running the program for the first time 10 | Install The `pytvlwcharts` Library Via `pip install -U git+https://github.com/TechfaneTechnologies/pytvlwcharts.git` And Then Open A Jupyter Notebook Locally _(With Voila)_ or On [Google Colab](https://colab.research.google.com/) or On Flask Mode. 11 | 12 | Please Refer [pytvlwcharts.ipynb](https://github.com/TechfaneTechnologies/pytvlwcharts/blob/main/pytvlwcharts.ipynb) for usage details. 13 | 14 | ## Screen Shots 15 | https://youtu.be/zQKB9_bMkfM 16 | 17 | https://youtu.be/BIu8I8hC2xI 18 | 19 | https://youtu.be/3ncFk_KdZzs 20 | 21 | ![image](https://user-images.githubusercontent.com/96371033/188302874-25dea27f-07c5-4723-810a-65d51e8b70fd.png) 22 | 23 | ![image](https://user-images.githubusercontent.com/96371033/188294528-73ddaf9e-55b2-491e-bfba-2733a9361994.png) 24 | 25 | ![image](https://user-images.githubusercontent.com/96371033/188294553-ac8ec934-251e-4fe9-a30c-d40f63d5f9f6.png) 26 | 27 | ![image](https://user-images.githubusercontent.com/68828793/188259987-b5976ef1-5c83-4f2f-a937-c83c53fec791.png) 28 | 29 | ![image](https://user-images.githubusercontent.com/96371033/188273414-83a7ea6a-90ad-4f6a-90da-07c277abf2ff.png) 30 | 31 | ![image](https://user-images.githubusercontent.com/96371033/188295701-e48861e7-68d3-47ad-ad7a-f0f4f4f49e11.png) 32 | 33 | ![image](https://user-images.githubusercontent.com/96371033/188295727-98a79ce0-7d3a-4608-96cf-d4551aca3ef6.png) 34 | 35 | ![image](https://user-images.githubusercontent.com/96371033/188295706-dc566287-b651-4bf9-a37f-37682828259e.png) 36 | 37 | ![image](https://user-images.githubusercontent.com/96371033/188295711-3b29da01-65ba-45c4-a05e-b1d0fbe0eef8.png) 38 | 39 | ![image](https://user-images.githubusercontent.com/96371033/188297491-44960067-22ab-42cf-948b-51fcaf3310ef.png) 40 | 41 | ![image](https://user-images.githubusercontent.com/96371033/216821065-644a1eb4-ca7b-40f7-966e-ead78aa08939.png) 42 | 43 | Anchored VWAP [Notebook](https://colab.research.google.com/drive/1ApN2CHWNUZsKNxiqYjpT9glQdwt1c6qN?usp=sharing), [Flask App](https://colab.research.google.com/drive/1w1T2erRjyz3xLkentuIffI75z9kUkN6_?usp=sharing) 44 | 45 | ![image](https://user-images.githubusercontent.com/96371033/220196000-65690a23-4321-4c9c-9bf5-1426b1ac6b7f.png) 46 | 47 | ![image](https://user-images.githubusercontent.com/96371033/220196166-afcb9fe2-9e7f-4867-9f22-f42834eb27da.png) 48 | 49 | ![image](https://user-images.githubusercontent.com/96371033/221234325-ef7d00de-4c38-4918-9d1d-8426e383302c.png) 50 | 51 | 52 | ## License 53 | 54 | Licensed under either of 55 | 56 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://apache.org/licenses/LICENSE-2.0) 57 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 58 | 59 | ### Contribution 60 | 61 | Unless you explicitly state otherwise, any contribution intentionally submitted 62 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall 63 | be dual licensed as above, without any additional terms or conditions. 64 | -------------------------------------------------------------------------------- /pytvlwcharts/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | __init__.py 4 | An Experimental Python Wrapper For Tradingview's Lightweight-Charts To Be Used In Notebook Environments. 5 | :url: https://tradingview.github.io/lightweight-charts/ 6 | :copyright: (c) 2021 by Techfane Technologies Pvt. Ltd. 7 | :license: see LICENSE for details. 8 | :author: Dr June Moone 9 | :created: On Friday September 02, 2022 19:47:13 GMT+05:30 10 | """ 11 | __author__ = "Dr June Moone" 12 | __webpage__ = "https://github.com/MooneDrJune" 13 | __github__ = "https://github.com/TechfaneTechnologies/PyTvLwCharts" 14 | __license__ = "MIT" 15 | 16 | from .tvlwcharts import Chart 17 | from .generatedModels import * 18 | -------------------------------------------------------------------------------- /pytvlwcharts/__version__.py: -------------------------------------------------------------------------------- 1 | __title__ = "pytvlwcharts" 2 | __description__ = "An Experimental Python Wrapper For Tradingview's Lightweight-Charts To Be Used In Notebook Environments." 3 | __url__ = "https://github.com/TechfaneTechnologies" 4 | __download_url__ = "https://github.com/TechfaneTechnologies/pytvlwcharts" 5 | __version__ = "0.0.3" 6 | __author__ = "Techfane Technology Pvt. Ltd. (India)" 7 | __author_email__ = "moonedrjune@gmail.com" 8 | __license__ = ("MIT", "Apache-2.0") 9 | -------------------------------------------------------------------------------- /pytvlwcharts/generatedModels.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | generatedModels.py 4 | An Experimental Python Wrapper For Tradingview's Lightweight-Charts To Be Used In Notebook Environments. 5 | Generated With generateTypes.py. DO NOT MODIFY 6 | :url: https://tradingview.github.io/lightweight-charts/ 7 | :copyright: (c) 2021 by Techfane Technologies Pvt. Ltd. 8 | :license: see LICENSE for details. 9 | :author: Dr June Moone 10 | :created: On Friday September 02, 2022 19:47:13 GMT+05:30 11 | """ 12 | __author__ = "Dr June Moone" 13 | __webpage__ = "https://github.com/MooneDrJune" 14 | __github__ = "https://github.com/TechfaneTechnologies/PyTvLwCharts" 15 | __license__ = "MIT" 16 | 17 | from apischema import alias 18 | from apischema import serialize 19 | from dataclasses import field 20 | from dataclasses import dataclass 21 | import enum 22 | import json 23 | from typing import Any, Optional, Union 24 | 25 | class JsonOptions: 26 | def to_json(self): 27 | return json.dumps(serialize(self, exclude_none=True), indent=2) 28 | 29 | @dataclass 30 | class AxisPressedMouseMoveOptions(JsonOptions): 31 | """Represents options for how the time and price axes react to mouse movements. 32 | 33 | Attributes: 34 | price: Enable scaling the price axis by holding down the left mouse button and moving the mouse. 35 | time: Enable scaling the time axis by holding down the left mouse button and moving the mouse. 36 | """ 37 | price: Optional[bool] = None 38 | time: Optional[bool] = None 39 | 40 | 41 | class ColorType(enum.Enum): 42 | """ColorType""" 43 | 44 | # Solid color 45 | solid = 'solid' 46 | 47 | # Vertical gradient color 48 | vertical_gradient = 'gradient' 49 | 50 | 51 | @dataclass 52 | class SolidColor(JsonOptions): 53 | """Represents a solid color. 54 | 55 | Attributes: 56 | color: Color. 57 | type: Type of color. 58 | """ 59 | color: Optional[str] = None 60 | type: ColorType = ColorType.solid 61 | 62 | 63 | @dataclass 64 | class VerticalGradientColor(JsonOptions): 65 | """Represents a vertical gradient of two colors. 66 | 67 | Attributes: 68 | bottom_color: Bottom color 69 | top_color: Top color 70 | type: Type of color. 71 | """ 72 | bottom_color: Optional[str] = field(default=None, metadata=alias('bottomColor')) 73 | top_color: Optional[str] = field(default=None, metadata=alias('topColor')) 74 | type: ColorType = ColorType.vertical_gradient 75 | 76 | 77 | # Represents the background color of the chart. 78 | Background = Union[SolidColor, VerticalGradientColor] 79 | 80 | 81 | class LineStyle(enum.IntEnum): 82 | """Represents the possible line styles.""" 83 | 84 | LINESTYLE_0 = 0 85 | LINESTYLE_1 = 1 86 | LINESTYLE_2 = 2 87 | LINESTYLE_3 = 3 88 | LINESTYLE_4 = 4 89 | 90 | 91 | class LineWidth(enum.IntEnum): 92 | """Represents the width of a line.""" 93 | 94 | LINEWIDTH_1 = 1 95 | LINEWIDTH_2 = 2 96 | LINEWIDTH_3 = 3 97 | LINEWIDTH_4 = 4 98 | 99 | 100 | @dataclass 101 | class CrosshairLineOptions(JsonOptions): 102 | """Structure describing a crosshair line (vertical or horizontal) 103 | 104 | Attributes: 105 | color: Crosshair line color. 106 | label_background_color: Crosshair label background color. 107 | label_visible: Display the crosshair label on the relevant scale. 108 | style: Crosshair line style. 109 | visible: Display the crosshair line. 110 | width: Crosshair line width. 111 | """ 112 | color: Optional[str] = None 113 | label_background_color: Optional[str] = field(default=None, metadata=alias('labelBackgroundColor')) 114 | label_visible: Optional[bool] = field(default=None, metadata=alias('labelVisible')) 115 | style: Optional[LineStyle] = None 116 | visible: Optional[bool] = None 117 | width: Optional[LineWidth] = None 118 | 119 | 120 | class CrosshairMode(enum.IntEnum): 121 | """Represents the crosshair mode.""" 122 | 123 | CROSSHAIRMODE_0 = 0 124 | CROSSHAIRMODE_1 = 1 125 | 126 | 127 | @dataclass 128 | class CrosshairOptions(JsonOptions): 129 | """Structure describing crosshair options 130 | 131 | Attributes: 132 | horz_line: Horizontal line options. 133 | mode: Crosshair mode 134 | vert_line: Vertical line options. 135 | """ 136 | horz_line: Optional[CrosshairLineOptions] = field(default=None, metadata=alias('horzLine')) 137 | mode: Optional[CrosshairMode] = None 138 | vert_line: Optional[CrosshairLineOptions] = field(default=None, metadata=alias('vertLine')) 139 | 140 | 141 | @dataclass 142 | class GridLineOptions(JsonOptions): 143 | """Grid line options. 144 | 145 | Attributes: 146 | color: Line color. 147 | style: Line style. 148 | visible: Display the lines. 149 | """ 150 | color: Optional[str] = None 151 | style: Optional[LineStyle] = None 152 | visible: Optional[bool] = None 153 | 154 | 155 | @dataclass 156 | class GridOptions(JsonOptions): 157 | """Structure describing grid options. 158 | 159 | Attributes: 160 | horz_lines: Horizontal grid line options. 161 | vert_lines: Vertical grid line options. 162 | """ 163 | horz_lines: Optional[GridLineOptions] = field(default=None, metadata=alias('horzLines')) 164 | vert_lines: Optional[GridLineOptions] = field(default=None, metadata=alias('vertLines')) 165 | 166 | 167 | @dataclass 168 | class HandleScaleOptions(JsonOptions): 169 | """Represents options for how the chart is scaled by the mouse and touch gestures. 170 | 171 | Attributes: 172 | axis_double_click_reset: Enable resetting scaling by double-clicking the left mouse button. 173 | axis_pressed_mouse_move: Enable scaling the price and/or time scales by holding down the left mouse button and moving the mouse. 174 | mouse_wheel: Enable scaling with the mouse wheel. 175 | pinch: Enable scaling with pinch/zoom gestures. 176 | """ 177 | axis_double_click_reset: Optional[bool] = field(default=None, metadata=alias('axisDoubleClickReset')) 178 | axis_pressed_mouse_move: Optional[Union[AxisPressedMouseMoveOptions, bool]] = field(default=None, metadata=alias('axisPressedMouseMove')) 179 | mouse_wheel: Optional[bool] = field(default=None, metadata=alias('mouseWheel')) 180 | pinch: Optional[bool] = None 181 | 182 | 183 | @dataclass 184 | class HandleScrollOptions(JsonOptions): 185 | """Represents options for how the chart is scrolled by the mouse and touch gestures. 186 | 187 | Attributes: 188 | horz_touch_drag: Enable horizontal touch scrolling. When enabled the chart handles touch gestures that would normally scroll the webpage horizontally. 189 | mouse_wheel: Enable scrolling with the mouse wheel. 190 | pressed_mouse_move: Enable scrolling by holding down the left mouse button and moving the mouse. 191 | vert_touch_drag: Enable vertical touch scrolling. When enabled the chart handles touch gestures that would normally scroll the webpage vertically. 192 | """ 193 | horz_touch_drag: Optional[bool] = field(default=None, metadata=alias('horzTouchDrag')) 194 | mouse_wheel: Optional[bool] = field(default=None, metadata=alias('mouseWheel')) 195 | pressed_mouse_move: Optional[bool] = field(default=None, metadata=alias('pressedMouseMove')) 196 | vert_touch_drag: Optional[bool] = field(default=None, metadata=alias('vertTouchDrag')) 197 | 198 | 199 | class HorzAlign(enum.Enum): 200 | """Represents a horizontal alignment.""" 201 | 202 | center = 'center' 203 | left = 'left' 204 | right = 'right' 205 | 206 | 207 | @dataclass 208 | class KineticScrollOptions(JsonOptions): 209 | """Represents options for enabling or disabling kinetic scrolling with mouse and touch gestures. 210 | 211 | Attributes: 212 | mouse: Enable kinetic scroll with the mouse. 213 | touch: Enable kinetic scroll with touch gestures. 214 | """ 215 | mouse: Optional[bool] = None 216 | touch: Optional[bool] = None 217 | 218 | 219 | @dataclass 220 | class LayoutOptions(JsonOptions): 221 | """Represents layout options 222 | 223 | Attributes: 224 | background: Chart and scales background color. 225 | background_color: 226 | font_family: Font family of text on the scales. 227 | font_size: Font size of text on scales in pixels. 228 | text_color: Color of text on the scales. 229 | """ 230 | background: Optional[Background] = None 231 | background_color: Optional[str] = field(default=None, metadata=alias('backgroundColor')) 232 | font_family: Optional[str] = field(default=None, metadata=alias('fontFamily')) 233 | font_size: Optional[int] = field(default=None, metadata=alias('fontSize')) 234 | text_color: Optional[str] = field(default=None, metadata=alias('textColor')) 235 | 236 | 237 | # A function used to format a{@linkBarPrice}as a string. 238 | __type_2 = Any 239 | 240 | 241 | # PriceFormatterFn 242 | PriceFormatterFn = __type_2 243 | 244 | 245 | # A custom function used to override formatting of a time to a string. 246 | __type_3 = Any 247 | 248 | 249 | # TimeFormatterFn 250 | TimeFormatterFn = __type_3 251 | 252 | 253 | @dataclass 254 | class LocalizationOptions(JsonOptions): 255 | """Represents options for formatting dates, times, and prices according to a locale. 256 | 257 | Attributes: 258 | date_format: Date formatting string. Can contain `yyyy`, `yy`, `MMMM`, `MMM`, `MM` and `dd` literals which will be replaced with corresponding date's value. Ignored if timeFormatter has been specified. 259 | locale: Current locale used to format dates. Uses the browser's language settings by default. 260 | price_formatter: Override formatting of the price scale crosshair label. Can be used for cases that can't be covered with built-in price formats. 261 | time_formatter: Override formatting of the time scale crosshair label. 262 | """ 263 | date_format: Optional[str] = field(default=None, metadata=alias('dateFormat')) 264 | locale: Optional[str] = None 265 | price_formatter: Optional[PriceFormatterFn] = field(default=None, metadata=alias('priceFormatter')) 266 | time_formatter: Optional[TimeFormatterFn] = field(default=None, metadata=alias('timeFormatter')) 267 | 268 | 269 | class PriceScaleMode(enum.IntEnum): 270 | """Represents the price scale mode.""" 271 | 272 | PRICESCALEMODE_0 = 0 273 | PRICESCALEMODE_1 = 1 274 | PRICESCALEMODE_2 = 2 275 | PRICESCALEMODE_3 = 3 276 | 277 | 278 | class PriceAxisPosition(enum.Enum): 279 | """Represents the position of a price axis relative to the chart.""" 280 | 281 | left = 'left' 282 | none = 'none' 283 | right = 'right' 284 | 285 | 286 | @dataclass 287 | class PriceScaleMargins(JsonOptions): 288 | """Defines margins of the price scale. 289 | 290 | Attributes: 291 | bottom: Bottom margin in percentages. Must be greater or equal to 0 and less than 1. 292 | top: Top margin in percentages. Must be greater or equal to 0 and less than 1. 293 | """ 294 | bottom: Optional[int] = None 295 | top: Optional[int] = None 296 | 297 | 298 | @dataclass 299 | class __type(JsonOptions): 300 | """Represents overlay price scale options. 301 | 302 | Attributes: 303 | align_labels: Align price scale labels to prevent them from overlapping. 304 | border_color: Price scale border color. 305 | border_visible: Set true to draw a border between the price scale and the chart area. 306 | draw_ticks: Draw small horizontal line on price axis labels. 307 | entire_text_only: Show top and bottom corner labels only if entire text is visible. 308 | invert_scale: Invert the price scale, so that a upwards trend is shown as a downwards trend and vice versa. Affects both the price scale and the data on the chart. 309 | mode: Price scale mode. 310 | position: Price scale's position on the chart. 311 | scale_margins: Price scale margins. 312 | """ 313 | align_labels: Optional[bool] = field(default=None, metadata=alias('alignLabels')) 314 | border_color: Optional[str] = field(default=None, metadata=alias('borderColor')) 315 | border_visible: Optional[bool] = field(default=None, metadata=alias('borderVisible')) 316 | draw_ticks: Optional[bool] = field(default=None, metadata=alias('drawTicks')) 317 | entire_text_only: Optional[bool] = field(default=None, metadata=alias('entireTextOnly')) 318 | invert_scale: Optional[bool] = field(default=None, metadata=alias('invertScale')) 319 | mode: Optional[PriceScaleMode] = None 320 | position: Optional[PriceAxisPosition] = None 321 | scale_margins: Optional[PriceScaleMargins] = field(default=None, metadata=alias('scaleMargins')) 322 | 323 | 324 | # OverlayPriceScaleOptions 325 | OverlayPriceScaleOptions = __type 326 | 327 | 328 | @dataclass 329 | class PriceScaleOptions(JsonOptions): 330 | """Structure that describes price scale options 331 | 332 | Attributes: 333 | align_labels: Align price scale labels to prevent them from overlapping. 334 | auto_scale: Automatically set price range based on visible data range. 335 | border_color: Price scale border color. 336 | border_visible: Set true to draw a border between the price scale and the chart area. 337 | draw_ticks: Draw small horizontal line on price axis labels. 338 | entire_text_only: Show top and bottom corner labels only if entire text is visible. 339 | invert_scale: Invert the price scale, so that a upwards trend is shown as a downwards trend and vice versa. Affects both the price scale and the data on the chart. 340 | mode: Price scale mode. 341 | position: Price scale's position on the chart. 342 | scale_margins: Price scale margins. 343 | visible: Indicates if this price scale visible. Ignored by overlay price scales. 344 | """ 345 | align_labels: Optional[bool] = field(default=None, metadata=alias('alignLabels')) 346 | auto_scale: Optional[bool] = field(default=None, metadata=alias('autoScale')) 347 | border_color: Optional[str] = field(default=None, metadata=alias('borderColor')) 348 | border_visible: Optional[bool] = field(default=None, metadata=alias('borderVisible')) 349 | draw_ticks: Optional[bool] = field(default=None, metadata=alias('drawTicks')) 350 | entire_text_only: Optional[bool] = field(default=None, metadata=alias('entireTextOnly')) 351 | invert_scale: Optional[bool] = field(default=None, metadata=alias('invertScale')) 352 | mode: Optional[PriceScaleMode] = None 353 | position: Optional[PriceAxisPosition] = None 354 | scale_margins: Optional[PriceScaleMargins] = field(default=None, metadata=alias('scaleMargins')) 355 | visible: Optional[bool] = None 356 | 357 | 358 | # The `TickMarkFormatter` is used to customize tick mark labels on the time scale. This function should return `time` as a string formatted according to `tickMarkType` type (year, month, etc) and `locale`. Note that the returned string should be the shortest possible value and should have no more than 8 characters. Otherwise, the tick marks will overlap each other. 359 | __type_1 = Any 360 | 361 | 362 | # TickMarkFormatter 363 | TickMarkFormatter = __type_1 364 | 365 | 366 | @dataclass 367 | class TimeScaleOptions(JsonOptions): 368 | """Options for the time scale; the horizontal scale at the bottom of the chart that displays the time of data. 369 | 370 | Attributes: 371 | bar_spacing: The space between bars in pixels. 372 | border_color: The time scale border color. 373 | border_visible: Show the time scale border. 374 | fix_left_edge: Prevent scrolling to the left of the first bar. 375 | fix_right_edge: Prevent scrolling to the right of the most recent bar. 376 | lock_visible_time_range_on_resize: Prevent changing the visible time range during chart resizing. 377 | min_bar_spacing: The minimum space between bars in pixels. 378 | right_bar_stays_on_scroll: Prevent the hovered bar from moving when scrolling. 379 | right_offset: The margin space in bars from the right side of the chart. 380 | seconds_visible: Show seconds in the time scale and vertical crosshair label in `hh:mm:ss` format for intraday data. 381 | shift_visible_range_on_new_bar: Shift the visible range to the right (into the future) by the number of new bars when new data is added. Note that this only applies when the last bar is visible. 382 | tick_mark_formatter: Override the default tick marks formatter. 383 | time_visible: Show the time, not just the date, in the time scale and vertical crosshair label. 384 | visible: Show the time scale. 385 | """ 386 | bar_spacing: Optional[int] = field(default=None, metadata=alias('barSpacing')) 387 | border_color: Optional[str] = field(default=None, metadata=alias('borderColor')) 388 | border_visible: Optional[bool] = field(default=None, metadata=alias('borderVisible')) 389 | fix_left_edge: Optional[bool] = field(default=None, metadata=alias('fixLeftEdge')) 390 | fix_right_edge: Optional[bool] = field(default=None, metadata=alias('fixRightEdge')) 391 | lock_visible_time_range_on_resize: Optional[bool] = field(default=None, metadata=alias('lockVisibleTimeRangeOnResize')) 392 | min_bar_spacing: Optional[int] = field(default=None, metadata=alias('minBarSpacing')) 393 | right_bar_stays_on_scroll: Optional[bool] = field(default=None, metadata=alias('rightBarStaysOnScroll')) 394 | right_offset: Optional[int] = field(default=None, metadata=alias('rightOffset')) 395 | seconds_visible: Optional[bool] = field(default=None, metadata=alias('secondsVisible')) 396 | shift_visible_range_on_new_bar: Optional[bool] = field(default=None, metadata=alias('shiftVisibleRangeOnNewBar')) 397 | tick_mark_formatter: Optional[TickMarkFormatter] = field(default=None, metadata=alias('tickMarkFormatter')) 398 | time_visible: Optional[bool] = field(default=None, metadata=alias('timeVisible')) 399 | visible: Optional[bool] = None 400 | 401 | 402 | class VertAlign(enum.Enum): 403 | """Represents a vertical alignment.""" 404 | 405 | bottom = 'bottom' 406 | center = 'center' 407 | top = 'top' 408 | 409 | 410 | # Structure that describes price scale options 411 | VisiblePriceScaleOptions = PriceScaleOptions 412 | 413 | 414 | @dataclass 415 | class WatermarkOptions(JsonOptions): 416 | """Watermark options. 417 | 418 | Attributes: 419 | color: Watermark color. 420 | font_family: Font family. 421 | font_size: Font size in pixels. 422 | font_style: Font style. 423 | horz_align: Horizontal alignment inside the chart area. 424 | text: Text of the watermark. Word wrapping is not supported. 425 | vert_align: Vertical alignment inside the chart area. 426 | visible: Display the watermark. 427 | """ 428 | color: Optional[str] = None 429 | font_family: Optional[str] = field(default=None, metadata=alias('fontFamily')) 430 | font_size: Optional[int] = field(default=None, metadata=alias('fontSize')) 431 | font_style: Optional[str] = field(default=None, metadata=alias('fontStyle')) 432 | horz_align: Optional[HorzAlign] = field(default=None, metadata=alias('horzAlign')) 433 | text: Optional[str] = None 434 | vert_align: Optional[VertAlign] = field(default=None, metadata=alias('vertAlign')) 435 | visible: Optional[bool] = None 436 | 437 | 438 | @dataclass 439 | class ChartOptions(JsonOptions): 440 | """Structure describing options of the chart. Series options are to be set separately 441 | 442 | Attributes: 443 | crosshair: Crosshair options 444 | grid: Grid options. 445 | handle_scale: Scale options, or a boolean flag that enables/disables scaling 446 | handle_scroll: Scroll options, or a boolean flag that enables/disables scrolling 447 | height: Height of the chart in pixels 448 | kinetic_scroll: Kinetic scroll options 449 | layout: Layout options 450 | left_price_scale: Left price scale options 451 | localization: Localization options. 452 | overlay_price_scales: Overlay price scale options 453 | price_scale: Price scale options. 454 | right_price_scale: Right price scale options 455 | time_scale: Time scale options 456 | watermark: Watermark options. A watermark is a background label that includes a brief description of the drawn data. Any text can be added to it. Please make sure you enable it and set an appropriate font color and size to make your watermark visible in the background of the chart. We recommend a semi-transparent color and a large font. Also note that watermark position can be aligned vertically and horizontally. 457 | width: Width of the chart in pixels 458 | """ 459 | crosshair: Optional[CrosshairOptions] = None 460 | grid: Optional[GridOptions] = None 461 | handle_scale: Optional[Union[HandleScaleOptions, bool]] = field(default=None, metadata=alias('handleScale')) 462 | handle_scroll: Optional[Union[HandleScrollOptions, bool]] = field(default=None, metadata=alias('handleScroll')) 463 | height: Optional[Union[int,float,str]] = None 464 | kinetic_scroll: Optional[KineticScrollOptions] = field(default=None, metadata=alias('kineticScroll')) 465 | layout: Optional[LayoutOptions] = None 466 | left_price_scale: Optional[VisiblePriceScaleOptions] = field(default=None, metadata=alias('leftPriceScale')) 467 | localization: Optional[LocalizationOptions] = None 468 | overlay_price_scales: Optional[OverlayPriceScaleOptions] = field(default=None, metadata=alias('overlayPriceScales')) 469 | price_scale: Optional[PriceScaleOptions] = field(default=None, metadata=alias('priceScale')) 470 | right_price_scale: Optional[VisiblePriceScaleOptions] = field(default=None, metadata=alias('rightPriceScale')) 471 | time_scale: Optional[TimeScaleOptions] = field(default=None, metadata=alias('timeScale')) 472 | watermark: Optional[WatermarkOptions] = None 473 | width: Optional[Union[int,float,str]] = None 474 | -------------------------------------------------------------------------------- /pytvlwcharts/tvlwcharts.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | tvlwcharts.py 4 | An Experimental Python Wrapper For Tradingview's Lightweight-Charts To Be Used In Notebook Environments. 5 | :url: https://tradingview.github.io/lightweight-charts/ 6 | :copyright: (c) 2021 by Techfane Technologies Pvt. Ltd. 7 | :license: see LICENSE for details. 8 | :author: Dr June Moone 9 | :created: On Friday September 02, 2022 19:47:13 GMT+05:30 10 | """ 11 | __author__ = "Dr June Moone" 12 | __webpage__ = "https://github.com/MooneDrJune" 13 | __github__ = "https://github.com/TechfaneTechnologies/PyTvLwCharts" 14 | __license__ = "MIT" 15 | 16 | from .generatedModels import * 17 | 18 | import copy 19 | import dataclasses 20 | import itertools 21 | import jinja2 22 | import json 23 | import pandas as pd 24 | import uuid 25 | 26 | from typing import Dict, Optional, List 27 | 28 | _TEMPLATE = jinja2.Template(""" 29 | 30 | 31 | 32 | 33 | 34 | Lightweight Charts Customization Tutorial 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 50 | 51 | 52 |
53 | 152 | 153 | 154 | """) 155 | 156 | _TEMPLATES = jinja2.Template(""" 157 | 158 | 159 |
160 | 255 | """) 256 | 257 | # Initiate Model Specification. 258 | @dataclasses.dataclass 259 | class _SeriesSpec: 260 | series_name: str 261 | series_type: str 262 | data: str 263 | options: str 264 | price_lines: List[Dict] 265 | markers: str 266 | 267 | 268 | @dataclasses.dataclass 269 | class _ChartSpec: 270 | options: str 271 | series: List[_SeriesSpec] 272 | 273 | 274 | def _render(notebook_mode: bool, 275 | chart: _ChartSpec, 276 | data_url: str = "http://127.0.0.1:5000/data", 277 | base_url: str = "https://unpkg.com/lightweight-charts/dist/", 278 | output_div: str = "vis") -> str: 279 | """Render a model as html for viewing.""" 280 | return ( 281 | _TEMPLATES.render(chart=chart, data_url=data_url, base_url=base_url, output_div=output_div) 282 | if notebook_mode 283 | else _TEMPLATE.render(chart=chart, data_url=data_url, base_url=base_url, output_div=output_div) 284 | ) 285 | 286 | 287 | def _encode(data: pd.DataFrame, **kwargs) -> pd.DataFrame: 288 | """Rename and select columns from a data frame.""" 289 | return data.rename(columns={value: key for key, value in kwargs.items()})[[ 290 | *kwargs.keys() 291 | ]] 292 | 293 | 294 | class _Markers: 295 | """Series Markers.""" 296 | 297 | def __init__(self, chart, data: pd.DataFrame, **kwargs): 298 | self._chart = chart 299 | self._data = data 300 | self.options = kwargs 301 | 302 | def encode(self, **kwargs): 303 | self._data = _encode(self._data, **kwargs) 304 | 305 | def _spec(self): 306 | return [{ 307 | **self.options, 308 | **marker 309 | } for marker in self._data.to_dict(orient='records')] 310 | 311 | def _repr_html_(self): 312 | return self._chart._repr_html_() 313 | 314 | 315 | class Series: 316 | 317 | def __init__(self, chart, data: pd.DataFrame, series_name: str, series_type: str, **kwargs): 318 | self._chart = chart 319 | self.series_name = series_name 320 | self.series_type = series_type 321 | self._data = data 322 | self.options = kwargs 323 | self._price_lines = [] 324 | self._single_markers = [] 325 | self._markers = [] 326 | 327 | def encode(self, **kwargs): 328 | self._data = _encode(self._data, **kwargs) 329 | return self 330 | 331 | def price_line(self, **kwargs): 332 | self._price_lines.append(kwargs) 333 | return self 334 | 335 | def annotation(self, **kwargs): 336 | self._single_markers.append(kwargs) 337 | return self 338 | 339 | def mark_annotation(self, data: pd.DataFrame = None, **kwargs) -> _Markers: 340 | markers = _Markers(chart=self._chart, 341 | data=data if data is not None else self._data, 342 | **kwargs) 343 | self._markers.append(markers) 344 | return markers 345 | 346 | def _spec(self) -> _SeriesSpec: 347 | return _SeriesSpec( 348 | series_name=self.series_name, 349 | series_type=self.series_type, 350 | data=self._data.to_json(orient='records', date_format='iso'), 351 | options=json.dumps(self.options), 352 | price_lines=self._price_lines, 353 | markers=json.dumps(self._single_markers + list( 354 | itertools.chain(*[marker._spec() for marker in self._markers])))) 355 | 356 | def _repr_html_(self): 357 | return self._chart._repr_html_() 358 | 359 | 360 | class Chart: 361 | """A Lightweight Chart.""" 362 | 363 | def __init__(self, 364 | notebook_mode: bool = True, 365 | data_url: str = "http://127.0.0.1:5000/data", 366 | base_url: str = "https://unpkg.com/lightweight-charts/dist/", 367 | data: pd.DataFrame = None, 368 | width: int = 400, 369 | height: int = 300, 370 | crosshair: Optional[CrosshairOptions] = None, 371 | grid: Optional[GridOptions] = None, 372 | handle_scale: Optional[Union[HandleScaleOptions, bool]] = None, 373 | handle_scroll: Optional[Union[HandleScrollOptions, bool]] = None, 374 | kinetic_scroll: Optional[KineticScrollOptions] = None, 375 | layout: Optional[LayoutOptions] = None, 376 | left_price_scale: Optional[VisiblePriceScaleOptions] = None, 377 | localization: Optional[LocalizationOptions] = None, 378 | overlay_price_scales: Optional[OverlayPriceScaleOptions] = None, 379 | price_scale: Optional[PriceScaleOptions] = None, 380 | right_price_scale: Optional[VisiblePriceScaleOptions] = None, 381 | time_scale: Optional[TimeScaleOptions] = None, 382 | watermark: Optional[WatermarkOptions] = None, 383 | options: Optional[ChartOptions] = None): 384 | self.options = copy.deepcopy(options) if options else ChartOptions() 385 | self.series = [] 386 | self._data = data.drop_duplicates(subset=['time']) if data is not None else data 387 | self.notebook_mode = notebook_mode 388 | self.data_url = data_url 389 | self.base_url = base_url 390 | # Set Options Overrides. 391 | self.options.width = width 392 | self.options.height = height 393 | if crosshair: 394 | self.options.crosshair = copy.deepcopy(crosshair) 395 | if grid: 396 | self.options.grid = copy.deepcopy(grid) 397 | if handle_scale: 398 | self.options.handle_scale = copy.deepcopy(handle_scale) 399 | if handle_scroll: 400 | self.options.handle_scale = copy.deepcopy(handle_scroll) 401 | if kinetic_scroll: 402 | self.options.kinetic_scroll = copy.deepcopy(kinetic_scroll) 403 | if layout: 404 | self.options.layout = copy.deepcopy(layout) 405 | if left_price_scale: 406 | self.options.left_price_scale = copy.deepcopy(left_price_scale) 407 | if localization: 408 | self.options.localization = copy.deepcopy(localization) 409 | if overlay_price_scales: 410 | self.options.overlay_price_scales = copy.deepcopy(overlay_price_scales) 411 | if price_scale: 412 | self.options.price_scale = copy.deepcopy(price_scale) 413 | if right_price_scale: 414 | self.options.right_price_scale = copy.deepcopy(right_price_scale) 415 | if time_scale: 416 | self.options.time_scale = copy.deepcopy(time_scale) 417 | if watermark: 418 | self.options.watermark = copy.deepcopy(watermark) 419 | 420 | def add(self, series: Series): 421 | self.series.append(series) 422 | return series 423 | 424 | def mark_line(self, series_name:str = None, data: pd.DataFrame = None, **kwargs) -> Series: 425 | """Add A Line Series.""" 426 | return self.add( 427 | Series(chart=self, 428 | series_name=series_name, 429 | series_type='Line', 430 | data=data.drop_duplicates(subset=['time']) if data is not None else self._data, 431 | **kwargs)) 432 | 433 | def mark_area(self, series_name:str = None, data: pd.DataFrame = None, **kwargs) -> Series: 434 | """Add An Area Series.""" 435 | return self.add( 436 | Series(chart=self, 437 | series_name=series_name, 438 | series_type='Area', 439 | data=data.drop_duplicates(subset=['time']) if data is not None else self._data, 440 | **kwargs)) 441 | 442 | def mark_bar(self, series_name:str = None, data: pd.DataFrame = None, **kwargs) -> Series: 443 | """Add A Bar Series.""" 444 | return self.add( 445 | Series(chart=self, 446 | series_name=series_name, 447 | series_type='Bar', 448 | data=data.drop_duplicates(subset=['time']) if data is not None else self._data, 449 | **kwargs)) 450 | 451 | def mark_candlestick(self, series_name:str = None, data: pd.DataFrame = None, **kwargs) -> Series: 452 | """Add A Candlestick series.""" 453 | return self.add( 454 | Series(chart=self, 455 | series_name=series_name, 456 | series_type='Candlestick', 457 | data=data.drop_duplicates(subset=['time']) if data is not None else self._data, 458 | **kwargs)) 459 | 460 | def mark_histogram(self, series_name:str = None, data: pd.DataFrame = None, **kwargs) -> Series: 461 | """Add A Histogram Series.""" 462 | return self.add( 463 | Series(chart=self, 464 | series_name=series_name, 465 | series_type='Histogram', 466 | data=data.drop_duplicates(subset=['time']) if data is not None else self._data, 467 | **kwargs)) 468 | 469 | def _spec(self) -> _ChartSpec: 470 | return _ChartSpec(options=self.options.to_json(), 471 | series=[series._spec() for series in self.series]) 472 | 473 | def _repr_html_(self): 474 | return _render( 475 | notebook_mode=self.notebook_mode, 476 | chart=self._spec(), 477 | data_url=self.data_url, 478 | base_url=self.base_url, 479 | output_div=f'vis-{uuid.uuid4().hex}' 480 | ) 481 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os 3 | from codecs import open 4 | from setuptools import setup 5 | 6 | current_dir = os.path.abspath(os.path.dirname(__file__)) 7 | 8 | about = {} 9 | with open(os.path.join(current_dir, "pytvlwcharts", "__version__.py"), "r", "utf-8") as f: 10 | exec(f.read(), about) 11 | 12 | with io.open('README.md', 'rt', encoding='utf8') as f: 13 | readme = f.read() 14 | 15 | setup( 16 | name=about["__title__"], 17 | version=about["__version__"], 18 | description=about["__description__"], 19 | long_description=readme, 20 | long_description_content_type='text/markdown', 21 | author=about["__author__"], 22 | author_email=about["__author_email__"], 23 | url=about["__url__"], 24 | download_url=about["__download_url__"], 25 | license=f'{about["__license__"][0]}, {about["__license__"][-1]}', 26 | packages=["pytvlwcharts"], 27 | classifiers=[ 28 | "Development Status :: 1 - Development/Alpha", 29 | "Intended Audience :: Developers", 30 | "Intended Audience :: Financial and Insurance Industry", 31 | "Programming Language :: Python", 32 | "Natural Language :: English", 33 | "License :: OSI Approved :: MIT License", 34 | "Programming Language :: Python :: 3.5", 35 | "Programming Language :: Python :: 3.6", 36 | "Programming Language :: Python :: 3.7", 37 | "Programming Language :: Python :: 3.8", 38 | "Programming Language :: Python :: 3.9", 39 | "Programming Language :: Python :: 3.10", 40 | "Programming Language :: Python :: 3.11", 41 | "Programming Language :: Python :: 3.12", 42 | "Topic :: Office/Business :: Financial :: Investment", 43 | "Topic :: Software Development :: Libraries :: Python Modules", 44 | "Topic :: Software Development :: Libraries" 45 | ], 46 | install_requires=[ 47 | 'apischema', 48 | 'jinja2', 49 | 'absl-py', 50 | 'pandas', 51 | 'numpy' 52 | ], 53 | extras_require={ 54 | "doc": ["pdoc"], 55 | ':sys_platform=="win32"': ["pywin32"] 56 | } 57 | ) 58 | --------------------------------------------------------------------------------