Repository: sharebook-kr/book-cryptocurrency
Branch: master
Commit: 847ba97ba096
Files: 199
Total size: 153.5 KB
Directory structure:
gitextract__f95lk4z/
├── LICENSE
├── README.md
├── ch03/
│ ├── 03_01.py
│ ├── 03_02.py
│ ├── 03_03.py
│ ├── 03_04.py
│ ├── 03_05.py
│ ├── 03_06.py
│ ├── 03_07.py
│ ├── 03_08.py
│ ├── 03_09.py
│ ├── 03_10.py
│ ├── 03_11.py
│ ├── 03_12.py
│ ├── 03_13.py
│ ├── 03_14.py
│ ├── 03_15.py
│ ├── 03_16.py
│ ├── 03_17.py
│ ├── 03_18.py
│ ├── 03_19.py
│ ├── 03_20.py
│ ├── 03_21.py
│ ├── 03_22.py
│ ├── 03_23.py
│ ├── 03_24.py
│ ├── 03_25.py
│ ├── 03_26.py
│ ├── 03_27.py
│ ├── 03_28.py
│ ├── mywindow.ui
│ └── window.ui
├── ch04/
│ ├── 04_01.py
│ ├── 04_02.py
│ ├── 04_03.py
│ ├── 04_04.py
│ ├── 04_05.py
│ ├── 04_06.py
│ ├── 04_07.py
│ ├── 04_08.py
│ ├── 04_09.py
│ ├── 04_10.py
│ ├── 04_11.py
│ ├── 04_12.py
│ ├── 04_13.py
│ ├── 04_14.py
│ ├── 04_15.py
│ ├── 04_16.py
│ ├── 04_17.py
│ ├── 04_18.py
│ ├── 04_19.py
│ ├── 04_20.py
│ ├── 04_21.py
│ ├── 04_22.py
│ ├── 04_23.py
│ ├── 04_24.py
│ ├── 04_25.py
│ └── ohlc.xlsx
├── ch05/
│ ├── 05_01.py
│ ├── 05_02.py
│ ├── 05_03.py
│ ├── 05_04.py
│ ├── 05_05.py
│ ├── 05_06.py
│ ├── 05_07.py
│ ├── 05_08.py
│ ├── 05_09.py
│ ├── 05_10.py
│ ├── 05_11.py
│ ├── 05_12.py
│ ├── 05_13.py
│ ├── 05_14.py
│ ├── 05_15.py
│ ├── 05_16.py
│ ├── 05_17.py
│ ├── 05_18.py
│ ├── 05_19.py
│ ├── 05_20.py
│ ├── 05_21.py
│ ├── 05_22.py
│ ├── 05_23.py
│ ├── 05_24.py
│ ├── 05_25.py
│ ├── 05_26.py
│ ├── 05_27.py
│ ├── 05_ex_01.py
│ └── bull.ui
├── ch06/
│ ├── 06_01.py
│ ├── 06_02.py
│ ├── 06_03.py
│ ├── 06_04.py
│ ├── 06_05.py
│ ├── 06_06.py
│ ├── 06_07.py
│ ├── 06_08.py
│ ├── 06_09.py
│ ├── 06_10.py
│ ├── 06_11.py
│ ├── 06_12.py
│ ├── 06_13.py
│ ├── 06_14.py
│ ├── 06_15.py
│ ├── 06_16.py
│ ├── 06_17.py
│ ├── 06_18.py
│ ├── 06_19.py
│ └── 06_20.py
├── ch07/
│ ├── 07_01.py
│ ├── 07_02.py
│ ├── 07_03.py
│ ├── 07_04.py
│ ├── 07_05.py
│ ├── 07_06.py
│ ├── 07_07.py
│ ├── 07_08.py
│ ├── 07_09.py
│ ├── 07_10.py
│ ├── 07_11.py
│ ├── 07_12.py
│ ├── 07_13.py
│ ├── 07_14.py
│ ├── 07_15.py
│ ├── btc.xlsx
│ └── run.py
├── ch08/
│ ├── 08_01.py
│ ├── 08_02.py
│ ├── 08_03.py
│ ├── 08_04.py
│ ├── 08_05.py
│ ├── 08_06.py
│ ├── 08_07.py
│ ├── 08_08.py
│ ├── 08_09.py
│ ├── 08_10.py
│ ├── 08_11.py
│ ├── 08_12.py
│ ├── 08_13.py
│ ├── 08_14.py
│ ├── 08_15.py
│ ├── 08_16.py
│ ├── 08_17.py
│ ├── 08_18.py
│ ├── 08_19.py
│ ├── 08_20.py
│ ├── 08_21.py
│ ├── 08_22.py
│ ├── 08_23.py
│ ├── 08_24.py
│ ├── 08_25.py
│ └── 08_26.py
├── ch09/
│ ├── 09_01.py
│ ├── 09_02.py
│ ├── 09_03.py
│ ├── 09_04.py
│ ├── 09_05.py
│ ├── 09_06.py
│ ├── 09_07.py
│ ├── 09_08.py
│ ├── 09_09.py
│ ├── 09_10.py
│ ├── 09_11.py
│ ├── 09_12.py
│ ├── 09_13.py
│ ├── 09_14.py
│ ├── 09_15.py
│ ├── 09_16.py
│ └── 09_17.py
└── ch10/
├── chart.py
├── chart_0.py
├── chart_1.py
├── chart_2.py
├── chart_3.py
├── chart_4.py
├── chart_5.py
├── main.py
├── main_0.py
├── main_1.py
├── main_2.py
├── main_3.py
├── main_4.py
├── main_5.py
├── main_6.py
├── orderbook.py
├── orderbook_0.py
├── orderbook_1.py
├── orderbook_2.py
├── orderbook_3.py
├── orderbook_4.py
├── overview.py
├── overview_0.py
├── overview_1.py
├── overview_2.py
├── overview_3.py
├── overview_4.py
├── resource/
│ ├── chart.ui
│ ├── main.ui
│ ├── orderbook.ui
│ └── overview.ui
└── volatility.py
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# 파이썬을 이용한 비트코인 자동매매
<div>
<img src="http://image.yes24.com/goods/69773561/800x0" width=300>
</div>
================================================
FILE: ch03/03_01.py
================================================
pos = 0
def forward(pos):
return pos + 20
pos = forward(pos)
print(pos)
================================================
FILE: ch03/03_02.py
================================================
class SuperMario:
def __init__(self):
self.pos = 0
def forward(self):
self.pos = self.pos + 20
mario = SuperMario()
mario.forward()
print(mario.pos)
================================================
FILE: ch03/03_03.py
================================================
p1_pos = 0
p2_pos = 0
def forward(pos):
return pos + 20
p1_pos = forward(p1_pos)
p2_pos = forward(p2_pos)
================================================
FILE: ch03/03_04.py
================================================
class SuperMario:
def __init__(self):
self.pos = 0
def forward(self):
self.pos = self.pos + 20
mario_p1 = SuperMario()
mario_p2 = SuperMario()
mario_p1.forward()
mario_p2.forward()
================================================
FILE: ch03/03_05.py
================================================
class MyClass:
def method(self):
print("method")
obj = MyClass()
obj.method()
================================================
FILE: ch03/03_06.py
================================================
class MyClass:
def add(self, a, b):
return a + b
obj = MyClass()
ret = obj.add(3, 4)
print(ret)
================================================
FILE: ch03/03_07.py
================================================
class Customer:
def __init__(self, id, name):
self.id = id
self.name = name
================================================
FILE: ch03/03_08.py
================================================
class Parent:
def sing(self):
print("sing a song")
father = Parent()
father.sing()
================================================
FILE: ch03/03_09.py
================================================
class Parent:
def sing(self):
print("sing a song")
class LuckyChild(Parent):
pass
luckyboy = LuckyChild()
luckyboy.sing()
================================================
FILE: ch03/03_10.py
================================================
class Parent:
def sing(self):
print("sing a song")
class LuckyChild(Parent):
def dance(self):
print("shuffle dance")
luckyboy = LuckyChild()
luckyboy.sing()
luckyboy.dance()
================================================
FILE: ch03/03_11.py
================================================
class Car:
def __init__(self, model, year):
self.model = model
self.year = year
sonata = Car("SONATA", 2017)
g80 = Car("G80", 2018)
print(sonata.model, sonata.year)
print(g80.model, g80.year)
================================================
FILE: ch03/03_12.py
================================================
import sys
from PyQt5.QtWidgets import *
app = QApplication(sys.argv)
label = QLabel("Hello")
label.show()
app.exec_()
================================================
FILE: ch03/03_13.py
================================================
import sys
from PyQt5.QtWidgets import *
app = QApplication(sys.argv)
btn = QPushButton("Hello") # 버튼 객체 생성
btn.show()
app.exec_() # 이벤트 루프 생성
================================================
FILE: ch03/03_14.py
================================================
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_15.py
================================================
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 200, 300, 400)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_16.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 200, 300, 200)
self.setWindowTitle("PyQt")
self.setWindowIcon(QIcon("icon.png"))
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_17.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 200, 300, 200)
self.setWindowTitle("PyQt")
self.setWindowIcon(QIcon("icon.png"))
btn = QPushButton("버튼1", self)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_18.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 200, 300, 200)
self.setWindowTitle("PyQt")
self.setWindowIcon(QIcon("icon.png"))
btn = QPushButton("버튼1", self)
btn.move(10, 10)
btn2 = QPushButton("버튼2", self)
btn2.move(10, 40)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_19.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 200, 300, 200)
self.setWindowTitle("PyQt")
self.setWindowIcon(QIcon("icon.png"))
btn = QPushButton("버튼1", self)
btn.move(10, 10)
btn.clicked.connect(self.btn_clicked)
def btn_clicked(self):
print("버튼 클릭")
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_20.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
form_class = uic.loadUiType("mywindow.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_21.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
form_class = uic.loadUiType("mywindow.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.btn_clicked)
def btn_clicked(self):
print("버튼 클릭")
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_22.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
form_class = uic.loadUiType("mywindow.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.inquiry)
def inquiry(self):
print("조회 버튼 클릭")
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_23.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
import pykorbit
form_class = uic.loadUiType("window.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.inquiry)
def inquiry(self):
price = pykorbit.get_current_price("BTC")
print(price)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_24.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
import pykorbit
form_class = uic.loadUiType("window.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.inquiry)
def inquiry(self):
price = pykorbit.get_current_price("BTC")
self.lineEdit.setText(str(price))
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_25.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.timer = QTimer(self)
self.timer.start(1000)
self.timer.timeout.connect(self.timeout)
def timeout(self):
cur_time = QTime.currentTime()
str_time = cur_time.toString("hh:mm:ss")
self.statusBar().showMessage(str_time)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_26.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
import pykorbit
form_class = uic.loadUiType("window.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.timer = QTimer(self)
self.timer.start(1000)
self.timer.timeout.connect(self.inquiry)
def inquiry(self):
cur_time = QTime.currentTime()
str_time = cur_time.toString("hh:mm:ss")
self.statusBar().showMessage(str_time)
price = pykorbit.get_current_price("BTC")
self.lineEdit.setText(str(price))
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_27.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MySignal(QObject):
signal1 = pyqtSignal()
def run(self):
self.signal1.emit()
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
mysignal = MySignal()
mysignal.signal1.connect(self.signal1_emitted)
mysignal.run()
@pyqtSlot()
def signal1_emitted(self):
print("signal1 emitted")
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/03_28.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MySignal(QObject):
signal1 = pyqtSignal()
signal2 = pyqtSignal(int, int)
def run(self):
self.signal1.emit()
self.signal2.emit(1, 2)
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
mysignal = MySignal()
mysignal.signal1.connect(self.signal1_emitted)
mysignal.signal2.connect(self.signal2_emitted)
mysignal.run()
@pyqtSlot()
def signal1_emitted(self):
print("signal1 emitted")
@pyqtSlot(int, int)
def signal2_emitted(self, arg1, arg2):
print("signal2 emitted", arg1, arg2)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch03/mywindow.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>367</width>
<height>271</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>20</x>
<y>20</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>클릭</string>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>367</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
================================================
FILE: ch03/window.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>398</width>
<height>226</height>
</rect>
</property>
<property name="windowTitle">
<string>코빗 시세 조회기</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QLabel" name="label">
<property name="geometry">
<rect>
<x>10</x>
<y>30</y>
<width>101</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>비트코인 현재가:</string>
</property>
</widget>
<widget class="QLineEdit" name="lineEdit">
<property name="geometry">
<rect>
<x>110</x>
<y>30</y>
<width>161</width>
<height>20</height>
</rect>
</property>
</widget>
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>310</x>
<y>30</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>조회</string>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>398</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
================================================
FILE: ch04/04_01.py
================================================
import requests
url = "https://finance.naver.com/item/main.nhn?code=000660"
html = requests.get(url).text
print(html)
================================================
FILE: ch04/04_02.py
================================================
import requests
from bs4 import BeautifulSoup
url = "http://finance.naver.com/item/main.nhn?code=000660"
html = requests.get(url).text
soup = BeautifulSoup(html, "html5lib")
tags = soup.select("#_per")
tag = tags[0]
print(tag.text)
================================================
FILE: ch04/04_03.py
================================================
import requests
from bs4 import BeautifulSoup
url = "http://finance.naver.com/item/main.nhn?code=000660"
html = requests.get(url).text
soup = BeautifulSoup(html, "html5lib")
tags = soup.select("#_dvr")
tag = tags[0]
print(tag.text)
================================================
FILE: ch04/04_04.py
================================================
import requests
from bs4 import BeautifulSoup
def get_per(code):
url = "http://finance.naver.com/item/main.nhn?code=" + code
html = requests.get(url).text
soup = BeautifulSoup(html, "html5lib")
tags = soup.select("#_per")
tag = tags[0]
return float(tag.text)
def get_dividend(code):
url = "http://finance.naver.com/item/main.nhn?code=" + code
html = requests.get(url).text
soup = BeautifulSoup(html, "html5lib")
tags = soup.select("#_dvr")
tag = tags[0]
return float(tag.text)
print(get_per("000660"))
print(get_dividend("000660"))
================================================
FILE: ch04/04_05.py
================================================
import requests
from bs4 import BeautifulSoup
url = "http://finance.naver.com/item/main.nhn?code=000660"
html = requests.get(url).text
soup = BeautifulSoup(html, "html5lib")
tags = soup.select("table tbody tr td em")
for tag in tags:
print(tag.text)
================================================
FILE: ch04/04_06.py
================================================
import requests
from bs4 import BeautifulSoup
url = "http://finance.naver.com/item/main.nhn?code=000660"
html = requests.get(url).text
soup = BeautifulSoup(html, "html5lib")
tags = soup.select(".lwidth tbody .strong td em")
for tag in tags:
print(tag.text)
================================================
FILE: ch04/04_07.py
================================================
import requests
from bs4 import BeautifulSoup
url = "http://finance.naver.com/item/main.nhn?code=000660"
html = requests.get(url).text
soup = BeautifulSoup(html, "html5lib")
tags = soup.select("#tab_con1 > div:nth-of-type(2) > table > tbody > tr.strong > td > em")
for tag in tags:
print(tag.text)
================================================
FILE: ch04/04_08.py
================================================
import requests
r = requests.get("https://api.korbit.co.kr/v1/ticker/detailed?currency_pair=btc_krw")
bitcoin = r.json()
print(bitcoin)
print(type(bitcoin))
================================================
FILE: ch04/04_09.py
================================================
import requests
import datetime
r = requests.get("https://api.korbit.co.kr/v1/ticker/detailed?currency_pair=btc_krw")
bitcoin = r.json()
timestamp = bitcoin['timestamp']
date = datetime.datetime.fromtimestamp(timestamp/1000)
print(date)
================================================
FILE: ch04/04_10.py
================================================
from pandas import Series
date = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05']
xrp_close = [512, 508, 512, 507, 500]
s = Series(xrp_close, index=date)
print(s)
================================================
FILE: ch04/04_11.py
================================================
from pandas import Series
date = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05']
xrp_close = [512, 508, 512, 507, 500]
s = Series(xrp_close, index=date)
print(s.index)
print(s.values)
================================================
FILE: ch04/04_12.py
================================================
from pandas import Series
date = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05']
xrp_close = [512, 508, 512, 507, 500]
s = Series(xrp_close, index=date)
print(s.index)
print(s.values)
print(s[['2018-08-02', '2018-08-04']])
================================================
FILE: ch04/04_13.py
================================================
from pandas import Series
date = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05']
xrp_close = [512, 508, 512, 507, 500]
s = Series(xrp_close, index=date)
print(s['2018-08-01': '2018-08-03'])
================================================
FILE: ch04/04_14.py
================================================
from pandas import Series
date = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05']
xrp_close = [512, 508, 512, 507, 500]
s = Series(xrp_close, index=date)
s['2018-08-06'] = 490
print(s.drop('2018-08-01'))
print(s)
================================================
FILE: ch04/04_15.py
================================================
from pandas import Series
s = Series([100, 200, 300, 400])
print(s /10)
================================================
FILE: ch04/04_16.py
================================================
from pandas import DataFrame
data = {'open': [100, 200], "high": [110, 210]}
df = DataFrame(data )
print(df)
================================================
FILE: ch04/04_17.py
================================================
from pandas import DataFrame
data = {"open": [737, 750], "high": [755, 780], "low": [700, 710], "close": [750, 770]}
df = DataFrame(data , index=["2018-01-01", "2018-01-02"])
print(df)
================================================
FILE: ch04/04_18.py
================================================
import pandas as pd
df = pd.read_excel("ohlc.xlsx")
print(df)
================================================
FILE: ch04/04_19.py
================================================
import pandas as pd
df = pd.read_excel("ohlc.xlsx")
df = df.set_index('date')
print(df)
df.to_excel("ohlc-2.xlsx")
================================================
FILE: ch04/04_20.py
================================================
import pandas as pd
url = "https://finance.naver.com/item/sise_day.nhn?code=066570"
df = pd.read_html(url)
print(df[0])
================================================
FILE: ch04/04_21.py
================================================
from pandas import DataFrame
data = {"open": [730, 750], "high": [755, 780], "low": [700, 710], "close": [750, 770]}
df = DataFrame(data, index=["2018-01-01", "2018-01-02"])
print(df['open'])
================================================
FILE: ch04/04_22.py
================================================
from pandas import DataFrame
data = {"open": [730, 750], "high": [755, 780], "low": [700, 710], "close": [750, 770]}
df = DataFrame(data, index=["2018-01-01", "2018-01-02"])
print(df.loc["2018-01-01"])
================================================
FILE: ch04/04_23.py
================================================
from pandas import Series, DataFrame
data = {"open": [737, 750], "high": [755, 780], "low": [700, 710], "close": [750, 770]}
df = DataFrame(data)
s = Series([300, 400])
df["volume"] = s
print(df)
================================================
FILE: ch04/04_24.py
================================================
from pandas import Series, DataFrame
data = {"open": [737, 750], "high": [755, 780], "low": [700, 710], "close": [750, 770]}
df = DataFrame(data)
s = Series([300, 400])
df["volume"] = s
upper = df["open"] * 1.3
df["upper"] = upper
print(df)
================================================
FILE: ch04/04_25.py
================================================
from pandas import Series
s = Series([100, 200, 300])
s2 = s.shift(1)
print(s)
print(s2)
================================================
FILE: ch05/05_01.py
================================================
import pybithumb
tickers = pybithumb.get_tickers()
print(tickers)
print(len(tickers))
print(type(tickers))
================================================
FILE: ch05/05_02.py
================================================
import pybithumb
price = pybithumb.get_current_price("BTC")
print(price)
================================================
FILE: ch05/05_03.py
================================================
import pybithumb
import time
while True:
price = pybithumb.get_current_price("BTC")
print(price)
time.sleep(1)
================================================
FILE: ch05/05_04.py
================================================
import pybithumb
import time
tickers = pybithumb.get_tickers()
for ticker in tickers:
price = pybithumb.get_current_price(ticker)
print(ticker, price)
time.sleep(0.1)
================================================
FILE: ch05/05_05.py
================================================
import pybithumb
detail = pybithumb.get_market_detail("BTC")
print(detail)
print(type(detail))
================================================
FILE: ch05/05_06.py
================================================
import pybithumb
orderbook = pybithumb.get_orderbook("BTC")
print(orderbook)
for k in orderbook:
print(k)
================================================
FILE: ch05/05_07.py
================================================
import pybithumb
import datetime
orderbook = pybithumb.get_orderbook("BTC")
ms = int(orderbook['timestamp'])
dt = datetime.datetime.fromtimestamp(ms/1000)
print(dt)
================================================
FILE: ch05/05_08.py
================================================
import pybithumb
orderbook = pybithumb.get_orderbook("BTC")
bids = orderbook['bids']
asks = orderbook['asks']
print(bids)
print(asks)
# for bid in bids:
# price = bid['price']
# quant = bid['quantity']
# print("매수호가: ", price, "매수잔량: ", quant)
# for ask in asks:
# price = ask['price']
# quant = ask['quantity']
# print("매도호가: ", price, "매도잔량: ", quant)
================================================
FILE: ch05/05_09.py
================================================
import pybithumb
orderbook = pybithumb.get_orderbook("BTC")
bids = orderbook['bids']
asks = orderbook['asks']
for bid in bids:
price = bid['price']
quant = bid['quantity']
print("매수호가: ", price, "매수잔량: ", quant)
for ask in asks:
price = ask['price']
quant = ask['quantity']
print("매도호가: ", price, "매도잔량: ", quant)
================================================
FILE: ch05/05_10.py
================================================
import pybithumb
all = pybithumb.get_current_price("ALL")
for k, v in all.items():
print(k, v)
================================================
FILE: ch05/05_11.py
================================================
import pybithumb
tickers = pybithumb.get_tickers()
all = pybithumb.get_current_price("ALL")
for ticker in tickers:
print(ticker, all[ticker]['closing_price'])
================================================
FILE: ch05/05_12.py
================================================
price = {"open": 100, "high": 150, "low": 90, "close": 130}
print("point-1")
open = price["open1"]
print("point-2")
================================================
FILE: ch05/05_13.py
================================================
import pybithumb
import time
while True:
price = pybithumb.get_current_price("BTC")
print(price/10)
time.sleep(0.2)
================================================
FILE: ch05/05_14.py
================================================
import pybithumb
btc = pybithumb.get_ohlcv("BTC")
print(btc)
close = btc['close']
print(close)
================================================
FILE: ch05/05_15.py
================================================
import pybithumb
btc = pybithumb.get_ohlcv("BTC")
close = btc['close']
print((close[0] + close[1] + close[2] + close[3] + close[4])/5)
print((close[1] + close[2] + close[3] + close[4] + close[5])/5)
print((close[2] + close[3] + close[4] + close[5] + close[6])/5)
================================================
FILE: ch05/05_16.py
================================================
import pybithumb
btc = pybithumb.get_ohlcv("BTC")
close = btc['close']
window = close.rolling(5)
ma5 = window.mean()
print(ma5)
================================================
FILE: ch05/05_17.py
================================================
import pybithumb
df = pybithumb.get_ohlcv("BTC")
ma5 = df['close'].rolling(window=5).mean()
last_ma5 = ma5[-2]
cur_price = pybithumb.get_current_price('BTC')
if cur_price > last_ma5:
print("상승장")
else:
print("하락장")
================================================
FILE: ch05/05_18.py
================================================
import pybithumb
def bull_market(ticker):
df = pybithumb.get_ohlcv(ticker)
ma5 = df['close'].rolling(5).mean()
last_ma5 = ma5[-2]
cur_price = pybithumb.get_current_price(ticker)
if cur_price > last_ma5:
return True
else:
return False
is_bull = bull_market("BTC")
if is_bull:
print("비트코인 상승장")
================================================
FILE: ch05/05_19.py
================================================
import pybithumb
def bull_market(ticker):
df = pybithumb.get_ohlcv(ticker)
ma5 = df['close'].rolling(5).mean()
last_ma5 = ma5[-2]
cur_price = pybithumb.get_current_price(ticker)
if cur_price > last_ma5:
return True
else:
return False
tickers = pybithumb.get_tickers()
for ticker in tickers:
is_bull = bull_market(ticker)
if is_bull:
print(ticker, " 상승장")
else:
print(ticker, " 하락장")
================================================
FILE: ch05/05_20.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
form_class = uic.loadUiType("bull.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch05/05_21.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
form_class = uic.loadUiType("bull.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
timer = QTimer(self)
timer.start(5000)
timer.timeout.connect(self.timeout)
def timeout(self):
print("5초에요")
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch05/05_22.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
tickers = ["BTC", "ETH", "BCH", "ETC"]
form_class = uic.loadUiType("bull.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
timer = QTimer(self)
timer.start(5000)
timer.timeout.connect(self.timeout)
def timeout(self):
for i, ticker in enumerate(tickers):
item = QTableWidgetItem(ticker)
self.tableWidget.setItem(i, 0, item)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch05/05_23.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
import pybithumb
tickers = ["BTC", "ETH", "BCH", "ETC"]
form_class = uic.loadUiType("bull.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
timer = QTimer(self)
timer.start(5000)
timer.timeout.connect(self.timeout)
def get_market_infos(self, ticker):
df = pybithumb.get_ohlcv(ticker)
ma5 = df['close'].rolling(window=5).mean()
last_ma5 = ma5[-2]
price = pybithumb.get_current_price(ticker)
state = None
if price > last_ma5:
state = "상승장"
else:
state = "하락장"
return price, last_ma5, state
def timeout(self):
for i, ticker in enumerate(tickers):
item = QTableWidgetItem(ticker)
self.tableWidget.setItem(i, 0, item)
price, last_ma5, state = self.get_market_infos(ticker)
self.tableWidget.setItem(i, 1, QTableWidgetItem(str(price)))
self.tableWidget.setItem(i, 2, QTableWidgetItem(str(last_ma5)))
self.tableWidget.setItem(i, 3, QTableWidgetItem(state))
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch05/05_24.py
================================================
from PyQt5.QtCore import *
class Worker(QThread):
def run(self):
while True:
print("안녕하세요")
self.sleep(1)
================================================
FILE: ch05/05_25.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Worker(QThread):
def run(self):
while True:
print("안녕하세요")
self.sleep(1)
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.worker = Worker()
self.worker.start()
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
================================================
FILE: ch05/05_26.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
import pybithumb
import time
tickers = ["BTC", "ETH", "BCH", "ETC"]
form_class = uic.loadUiType("bull.ui")[0]
class Worker(QThread):
def run(self):
while True:
data = {}
for ticker in tickers:
data[ticker] = self.get_market_infos(ticker)
print(data)
time.sleep(5)
def get_market_infos(self, ticker):
try:
df = pybithumb.get_ohlcv(ticker)
ma5 = df['close'].rolling(window=5).mean()
last_ma5 = ma5[-2]
price = pybithumb.get_current_price(ticker)
state = None
if price > last_ma5:
state = "상승장"
else:
state = "하락장"
return price, last_ma5, state
except:
return None, None, None
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.worker = Worker()
self.worker.start()
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch05/05_27.py
================================================
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
import pybithumb
import time
tickers = ["BTC", "ETH", "BCH", "ETC"]
form_class = uic.loadUiType("bull.ui")[0]
class Worker(QThread):
finished = pyqtSignal(dict)
def run(self):
while True:
data = {}
for ticker in tickers:
data[ticker] = self.get_market_infos(ticker)
self.finished.emit(data)
time.sleep(2)
def get_market_infos(self, ticker):
try:
df = pybithumb.get_ohlcv(ticker)
ma5 = df['close'].rolling(window=5).mean()
last_ma5 = ma5[-2]
price = pybithumb.get_current_price(ticker)
state = None
if price > last_ma5:
state = "상승장"
else:
state = "하락장"
return price, last_ma5, state
except:
return None, None, None
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.worker = Worker()
self.worker.finished.connect(self.update_table_widget)
self.worker.start()
@pyqtSlot(dict)
def update_table_widget(self, data):
try:
for ticker, infos in data.items():
index = tickers.index(ticker)
self.tableWidget.setItem(index, 0, QTableWidgetItem(ticker))
self.tableWidget.setItem(index, 1, QTableWidgetItem(str(infos[0])))
self.tableWidget.setItem(index, 2, QTableWidgetItem(str(infos[1])))
self.tableWidget.setItem(index, 3, QTableWidgetItem(str(infos[2])))
except:
pass
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()
================================================
FILE: ch05/05_ex_01.py
================================================
import pybithumb
all = pybithumb.get_current_price("ALL")
tickers = pybithumb.get_tickers()
for ticker in tickers:
prices = all[ticker]
rate24 = prices['fluctate_rate_24H']
print(ticker, rate24)
================================================
FILE: ch05/bull.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>457</width>
<height>211</height>
</rect>
</property>
<property name="windowTitle">
<string>가상화폐 상승장/하락장 알리미</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QTableWidget" name="tableWidget">
<property name="geometry">
<rect>
<x>20</x>
<y>20</y>
<width>421</width>
<height>151</height>
</rect>
</property>
<property name="rowCount">
<number>4</number>
</property>
<row/>
<row/>
<row/>
<row/>
<column>
<property name="text">
<string>가상화폐</string>
</property>
</column>
<column>
<property name="text">
<string>현재가</string>
</property>
</column>
<column>
<property name="text">
<string>5일 이동평균</string>
</property>
</column>
<column>
<property name="text">
<string>상승장/하락장</string>
</property>
</column>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>457</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
================================================
FILE: ch06/06_01.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
================================================
FILE: ch06/06_02.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
balance = bithumb.get_balance("BTC")
print(balance)
================================================
FILE: ch06/06_03.py
================================================
import pybithumb
import time
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
for ticker in pybithumb.get_tickers() :
balance = bithumb.get_balance(ticker)
print(ticker, ":", balance)
time.sleep(0.1)
================================================
FILE: ch06/06_04.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
order = bithumb.buy_limit_order("BTC", 3900000, 0.001)
print(order)
================================================
FILE: ch06/06_05.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
order = bithumb.buy_market_order("BTC", 1)
print(order)
================================================
FILE: ch06/06_06.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
krw = bithumb.get_balance("BTC")[2]
orderbook = pybithumb.get_orderbook("BTC")
asks = orderbook['asks']
sell_price = asks[0]['price']
unit = krw/sell_price
print(unit)
================================================
FILE: ch06/06_07.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
krw = bithumb.get_balance("BTC")[2]
orderbook = pybithumb.get_orderbook("BTC")
asks = orderbook['asks']
sell_price = asks[0]['price']
unit = krw/float(sell_price)
order = bithumb.buy_market_order("BTC", unit)
print(order)
================================================
FILE: ch06/06_08.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
order = bithumb.sell_limit_order("BTC", 4000000, 1)
print(order)
================================================
FILE: ch06/06_09.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
unit = bithumb.get_balance("BTC")[0]
print(unit)
order = bithumb.sell_limit_order("BTC", 4000000, unit)
print(order)
================================================
FILE: ch06/06_10.py
================================================
import pybithumb
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
unit = bithumb.get_balance("BTC")[0]
order = bithumb.sell_market_order("BTC", unit)
print(order)
================================================
FILE: ch06/06_11.py
================================================
import pybithumb
import time
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
order = bithumb.buy_limit_order("BTC", 3000000, 0.001 )
print(order)
time.sleep(10)
cancel = bithumb.cancel_order(order)
print(cancel)
================================================
FILE: ch06/06_12.py
================================================
import pybithumb
import time
while True:
price = pybithumb.get_current_price("BTC")
print(price)
time.sleep(0.2)
================================================
FILE: ch06/06_13.py
================================================
import pybithumb
df = pybithumb.get_ohlcv("BTC")
yesterday = df.iloc[-2]
today_open = yesterday['close']
yesterday_high = yesterday['high']
yesterday_low = yesterday['low']
target = today_open + (yesterday_high - yesterday_low) * 0.5
print(target)
================================================
FILE: ch06/06_14.py
================================================
import time
import datetime
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
while True:
now = datetime.datetime.now()
if now == mid :
print("정각입니다")
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
print(now, "vs", mid)
time.sleep(1)
================================================
FILE: ch06/06_15.py
================================================
import time
import datetime
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
while True:
now = datetime.datetime.now()
if mid < now < mid + datetime.timedelta(seconds=10) :
print("정각입니다")
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
time.sleep(1)
================================================
FILE: ch06/06_16.py
================================================
import time
import pybithumb
import datetime
def get_target_price(ticker):
df = pybithumb.get_ohlcv("BTC")
yesterday = df.iloc[-2]
today_open = yesterday['close']
yesterday_high = yesterday['high']
yesterday_low = yesterday['low']
target = today_open + (yesterday_high - yesterday_low) * 0.5
return target
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
target_price = get_target_price("BTC")
while True:
now = datetime.datetime.now()
if mid < now < mid + datetime.delta(seconds=10) :
target_price = get_target_price("BTC")
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
current_price = pybithumb.get_current_price("BTC")
print(current_price)
time.sleep(1)
================================================
FILE: ch06/06_17.py
================================================
import time
import pybithumb
import datetime
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
def get_target_price(ticker):
df = pybithumb.get_ohlcv(ticker)
yesterday = df.iloc[-2]
today_open = yesterday['close']
yesterday_high = yesterday['high']
yesterday_low = yesterday['low']
target = today_open + (yesterday_high - yesterday_low) * 0.5
return target
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
target_price = get_target_price("BTC")
while True:
now = datetime.datetime.now()
if mid < now < mid + datetime.delta(seconds=10):
target_price = get_target_price("BTC")
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
current_price = pybithumb.get_current_price("BTC")
if current_price > target_price:
krw = bithumb.get_balance("BTC")[2]
orderbook = pybithumb.get_orderbook("BTC")
sell_price = orderbook['asks'][0]['price']
unit = krw/float(sell_price)
bithumb.buy_market_order("BTC", unit)
time.sleep(1)
================================================
FILE: ch06/06_18.py
================================================
import time
import pybithumb
import datetime
con_key = "81dd5f25e5daa70b2fff603901d2c09c"
sec_key = "82333efegeg9eg3e77c573weg34af17a"
bithumb = pybithumb.Bithumb(con_key, sec_key)
def get_target_price(ticker):
df = pybithumb.get_ohlcv(ticker)
yesterday = df.iloc[-2]
today_open = yesterday['close']
yesterday_high = yesterday['high']
yesterday_low = yesterday['low']
target = today_open + (yesterday_high - yesterday_low) * 0.5
return target
def buy_crypto_currency(ticker):
krw = bithumb.get_balance(ticker)[2]
orderbook = pybithumb.get_orderbook(ticker)
sell_price = orderbook['asks'][0]['price']
unit = krw/float(sell_price)
bithumb.buy_market_order(ticker, unit)
def sell_crypto_currency(ticker):
unit = bithumb.get_balance(ticker)[0]
bithumb.sell_market_order(ticker, unit)
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
target_price = get_target_price("BTC")
while True:
now = datetime.datetime.now()
if mid < now < mid + datetime.delta(seconds=10):
target_price = get_target_price("BTC")
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
sell_crypto_currency("BTC")
current_price = pybithumb.get_current_price("BTC")
if current_price > target_price:
buy_crypto_currency("BTC")
time.sleep(1)
================================================
FILE: ch06/06_19.py
================================================
import time
import pybithumb
import datetime
with open("bithumb.txt") as f:
lines = f.readlines()
key = lines[0].strip()
secret = lines[1].strip()
bithumb = pybithumb.Bithumb(key, secret)
def get_target_price(ticker):
df = pybithumb.get_ohlcv(ticker)
yesterday = df.iloc[-2]
today_open = yesterday['close']
yesterday_high = yesterday['high']
yesterday_low = yesterday['low']
target = today_open + (yesterday_high - yesterday_low) * 0.5
return target
def buy_crypto_currency(ticker):
krw = bithumb.get_balance(ticker)[2]
orderbook = pybithumb.get_orderbook(ticker)
sell_price = orderbook['asks'][0]['price']
unit = krw/float(sell_price)
bithumb.buy_market_order(ticker, unit)
def sell_crypto_currency(ticker):
unit = bithumb.get_balance(ticker)[0]
bithumb.sell_market_order(ticker, unit)
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
target_price = get_target_price("BTC")
while True:
try:
now = datetime.datetime.now()
if mid < now < mid + datetime.delta(seconds=10):
target_price = get_target_price("BTC")
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
sell_crypto_currency("BTC")
current_price = pybithumb.get_current_price("BTC")
if current_price > target_price:
buy_crypto_currency("BTC")
except:
print("에러 발생")
time.sleep(1)
================================================
FILE: ch06/06_20.py
================================================
import time
import pybithumb
import datetime
with open("bithumb.txt") as f:
lines = f.readlines()
key = lines[0].strip()
secret = lines[1].strip()
bithumb = pybithumb.Bithumb(key, secret)
def get_target_price(ticker):
df = pybithumb.get_ohlcv(ticker)
yesterday = df.iloc[-2]
today_open = yesterday['close']
yesterday_high = yesterday['high']
yesterday_low = yesterday['low']
target = today_open + (yesterday_high - yesterday_low) * 0.5
return target
def buy_crypto_currency(ticker):
krw = bithumb.get_balance(ticker)[2]
orderbook = pybithumb.get_orderbook(ticker)
sell_price = orderbook['asks'][0]['price']
unit = krw/float(sell_price)
bithumb.buy_market_order(ticker, unit)
def sell_crypto_currency(ticker):
unit = bithumb.get_balance(ticker)[0]
bithumb.sell_market_order(ticker, unit)
def get_yesterday_ma5(ticker):
df = pybithumb.get_ohlcv(ticker)
close = df['close']
ma = close.rolling(5).mean()
return ma[-2]
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
ma5 = get_yesterday_ma5("BTC")
target_price = get_target_price("BTC")
while True:
try:
now = datetime.datetime.now()
if mid < now < mid + datetime.delta(seconds=10):
target_price = get_target_price("BTC")
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
ma5 = get_yesterday_ma5("BTC")
sell_crypto_currency("BTC")
current_price = pybithumb.get_current_price("BTC")
if (current_price > target_price) and (current_price > ma5):
buy_crypto_currency("BTC")
except:
print("에러 발생")
time.sleep(1)
================================================
FILE: ch07/07_01.py
================================================
import pybithumb
df = pybithumb.get_ohlcv("BTC")
print(df.tail())
================================================
FILE: ch07/07_02.py
================================================
import pybithumb
df = pybithumb.get_ohlcv("BTC")
df.to_excel("btc.xlsx")
================================================
FILE: ch07/07_03.py
================================================
import pybithumb
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * 0.5
df.to_excel("btc.xlsx")
================================================
FILE: ch07/07_04.py
================================================
import pybithumb
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
df.to_excel("btc.xlsx")
================================================
FILE: ch07/07_05.py
================================================
import pybithumb
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * 0.5
df['range_shift1'] = df['range'].shift(1)
df['target'] = df['open'] + df['range'].shift(1)
df.to_excel("btc.xlsx")
================================================
FILE: ch07/07_06.py
================================================
import numpy as np
from pandas import DataFrame
data = {'빗썸': [100, 100, 100],
'코빗': [90, 110, 120]}
df = DataFrame(data)
df['최저가'] = np.where(df['빗썸'] < df['코빗'], '빗썸', '코빗')
df.to_excel("거래소.xlsx")
================================================
FILE: ch07/07_07.py
================================================
import pybithumb
import numpy as np
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
df['ror'] = np.where(df['high'] > df['target'],
df['close'] / df['target'],
1)
df.to_excel("trade.xlsx")
================================================
FILE: ch07/07_08.py
================================================
import pybithumb
import numpy as np
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
df['ror'] = np.where(df['high'] > df['target'],
df['close'] / df['target'],
1)
ror = df['ror'].cumprod()[-2]
print(ror)
================================================
FILE: ch07/07_09.py
================================================
import pybithumb
import numpy as np
df = pybithumb.get_ohlcv("BTC")
df = df['2018']
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
df['ror'] = np.where(df['high'] > df['target'],
df['close'] / df['target'],
1)
ror = df['ror'].cumprod()[-2]
print(ror)
================================================
FILE: ch07/07_10.py
================================================
import pybithumb
import numpy as np
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
fee = 0.0032
df['ror'] = np.where(df['high'] > df['target'],
df['close'] / df['target'] - fee,
1)
ror = df['ror'].cumprod()[-2]
print(ror)
================================================
FILE: ch07/07_11.py
================================================
import pybithumb
import numpy as np
def get_ror(k=0.5):
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * k
df['target'] = df['open'] + df['range'].shift(1)
fee = 0.0032
df['ror'] = np.where(df['high'] > df['target'],
df['close'] / df['target'] - fee,
1)
ror = df['ror'].cumprod()[-2]
return ror
for k in np.arange(0.1, 1.0, 0.1):
ror = get_ror(k)
print("%.1f %f" % (k, ror))
================================================
FILE: ch07/07_12.py
================================================
import pybithumb
import numpy as np
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
fee = 0.0032
df['ror'] = np.where(df['high'] > df['target'],
df['close'] / df['target'] - fee,
1)
df['hpr'] = df['ror'].cumprod()
df.to_excel("btc.xlsx")
================================================
FILE: ch07/07_13.py
================================================
import pybithumb
import numpy as np
df = pybithumb.get_ohlcv("BTC")
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
fee = 0.0032
df['ror'] = np.where(df['high'] > df['target'],
df['close'] / df['target'] - fee,
1)
df['hpr'] = df['ror'].cumprod()
df['dd'] = (df['hpr'].cummax() - df['hpr']) / df['hpr'].cummax() * 100
print("MDD(%): ", df['dd'].max())
df.to_excel("dd.xlsx")
================================================
FILE: ch07/07_14.py
================================================
import pybithumb
import numpy as np
df = pybithumb.get_ohlcv("BTC")
df['ma5'] = df['close'].rolling(window=5).mean().shift(1)
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
df['bull'] = df['open'] > df['ma5']
fee = 0.0032
df['ror'] = np.where((df['high'] > df['target']) & df['bull'],
df['close'] / df['target'] - fee,
1)
df['hpr'] = df['ror'].cumprod()
df['dd'] = (df['hpr'].cummax() - df['hpr']) / df['hpr'].cummax() * 100
print("MDD: ", df['dd'].max())
print("HPR: ", df['hpr'][-2])
df.to_excel("larry_ma.xlsx")
================================================
FILE: ch07/07_15.py
================================================
import pybithumb
import numpy as np
def get_hpr(ticker):
df = pybithumb.get_ohlcv(ticker)
df = df['2018']
df['ma5'] = df['close'].rolling(window=5).mean().shift(1)
df['range'] = (df['high'] - df['low']) * 0.5
df['target'] = df['open'] + df['range'].shift(1)
df['bull'] = df['open'] > df['ma5']
fee = 0.0032
df['ror'] = np.where((df['high'] > df['target']) & df['bull'],
df['close'] / df['target'] - fee,
1)
df['hpr'] = df['ror'].cumprod()
df['dd'] = (df['hpr'].cummax() - df['hpr']) / df['hpr'].cummax() * 100
return df['hpr'][-2]
tickers = pybithumb.get_tickers()
hprs = []
for ticker in tickers:
hpr = get_hpr(ticker)
hprs.append((ticker, hpr))
sorted_hprs = sorted(hprs, key=lambda x:x[1])
print(sorted_hprs[-5:])
================================================
FILE: ch07/run.py
================================================
import pybithumb
df = pybithumb.get_ohlcv(interval="hour")
df['Date'] = df.index.strftime("%Y-%m-%d %H:%M:%S")
print(df.head())
================================================
FILE: ch08/08_01.py
================================================
import pyupbit
tickers = pyupbit.get_tickers()
print(tickers)
================================================
FILE: ch08/08_02.py
================================================
import pyupbit
price = pyupbit.get_current_price("KRW-XRP")
print(price)
================================================
FILE: ch08/08_03.py
================================================
import pyupbit
df = pyupbit.get_ohlcv("KRW-BTC")
print(df)
================================================
FILE: ch08/08_04.py
================================================
import pyupbit
orderbook = pyupbit.get_orderbook("KRW-BTC")
print(orderbook)
================================================
FILE: ch08/08_05.py
================================================
import pyupbit
orderbook = pyupbit.get_orderbook("KRW-BTC")
bids_asks = orderbook[0]['orderbook_units']
for bid_ask in bids_asks:
print(bid_ask)
================================================
FILE: ch08/08_06.py
================================================
import pyupbit
access_key = "t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU"
secret_key = "VCLoAhrxbvyrukYChbxfxD6O1ESegeckIgbqeiQf"
upbit = pyupbit.Upbit(access_key, secret_key)
print(upbit.get_balances())
================================================
FILE: ch08/08_07.py
================================================
import pyupbit
access_key = "t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU"
secret_key = "VCLoAhrxbvyrukYChbxfxD6O1ESegeckIgbqeiQf"
upbit = pyupbit.Upbit(access_key, secret_key)
ret = upbit.buy_limit_order("KRW-XRP", 100, 20)
print(ret)
================================================
FILE: ch08/08_08.py
================================================
import pyupbit
access_key = "t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU"
secret_key = "VCLoAhrxbvyrukYChbxfxD6O1ESegeckIgbqeiQf"
upbit = pyupbit.Upbit(access_key, secret_key)
ret = upbit.sell_limit_order("KRW-XRP", 1000, 20)
print(ret)
================================================
FILE: ch08/08_09.py
================================================
import pyupbit
access_key = "t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU"
secret_key = "VCLoAhrxbvyrukYChbxfxD6O1ESegeckIgbqeiQf"
upbit = pyupbit.Upbit(access_key, secret_key)
ret = upbit.cancel_order('cc52be46-1000-4126-aee7-9bfafb867682')
print(ret)
================================================
FILE: ch08/08_10.py
================================================
import pykorbit
tickers = pykorbit.get_tickers()
print(tickers)
================================================
FILE: ch08/08_11.py
================================================
import pykorbit
price = pykorbit.get_current_price("BTC")
print(price)
================================================
FILE: ch08/08_12.py
================================================
import pykorbit
df = pykorbit.get_ohlc("BTC")
print(df)
================================================
FILE: ch08/08_13.py
================================================
import pykorbit
orderbook = pykorbit.get_orderbook("BTC")
print(orderbook)
================================================
FILE: ch08/08_14.py
================================================
import pykorbit
orderbook = pykorbit.get_orderbook("BTC")
asks = orderbook['asks']
for ask in asks:
print(ask[0], ask[1])
================================================
FILE: ch08/08_15.py
================================================
import pykorbit
email = "ceo_jo@gmail.com"
password = "mypassword"
key = "TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY7b8cWKIez7eGGkzan0"
secret = "MEasLLFhahGAyUucm7refegEEgpvBfTUe3A2DiMA48o4egegEEv9pBmLUq4e3pM"
korbit = pykorbit.Korbit(email, password, key, secret)
balance = korbit.get_balances()
print(balance)
================================================
FILE: ch08/08_16.py
================================================
import pykorbit
email = "ceo_jo@gmail.com"
password = "mypassword"
key = "TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY7b8cWKIez7eGGkzan0"
secret = "MEasLLFhahGAyUucm7refegEEgpvBfTUe3A2DiMA48o4egegEEv9pBmLUq4e3pM"
korbit = pykorbit.Korbit(email, password, key, secret)
order = korbit.buy_limit_order("XRP", 100, 10)
print(order)
================================================
FILE: ch08/08_17.py
================================================
import pykorbit
email = "ceo_jo@gmail.com"
password = "mypassword"
key = "TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY7b8cWKIez7eGGkzan0"
secret = "MEasLLFhahGAyUucm7refegEEgpvBfTUe3A2DiMA48o4egegEEv9pBmLUq4e3pM"
korbit = pykorbit.Korbit(email, password, key, secret)
order = korbit.sell_limit_order("XRP", 100, 10)
print(order)
================================================
FILE: ch08/08_18.py
================================================
import pykorbit
email = "ceo_jo@gmail.com"
password = "mypassword"
key = "TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY7b8cWKIez7eGGkzan0"
secret = "MEasLLFhahGAyUucm7refegEEgpvBfTUe3A2DiMA48o4egegEEv9pBmLUq4e3pM"
korbit = pykorbit.Korbit(email, password, key, secret)
order = korbit.buy_market_order("XRP", 1900)
print(order)
================================================
FILE: ch08/08_19.py
================================================
import pykorbit
email = "ceo_jo@gmail.com"
password = "mypassword"
key = "TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY7b8cWKIez7eGGkzan0"
secret = "MEasLLFhahGAyUucm7refegEEgpvBfTUe3A2DiMA48o4egegEEv9pBmLUq4e3pM"
korbit = pykorbit.Korbit(email, password, key, secret)
order = korbit.sell_market_order("XRP", 20)
print(order)
================================================
FILE: ch08/08_20.py
================================================
import pykorbit
email = "ceo_jo@gmail.com"
password = "mypassword"
key = "TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY7b8cWKIez7eGGkzan0"
secret = "MEasLLFhahGAyUucm7refegEEgpvBfTUe3A2DiMA48o4egegEEv9pBmLUq4e3pM"
korbit = pykorbit.Korbit(email, password, key, secret)
order = korbit.cancel_order("XRP", "12886793")
print(order)
================================================
FILE: ch08/08_21.py
================================================
import ccxt
binance = ccxt.binance()
markets = binance.fetch_tickers()
print(markets.keys())
================================================
FILE: ch08/08_22.py
================================================
import ccxt
binance = ccxt.binance()
ticker = binance.fetch_ticker('ETH/BTC')
print(ticker['open'], ticker['high'], ticker['low'], ticker['close'])
================================================
FILE: ch08/08_23.py
================================================
import ccxt
binance = ccxt.binance()
ohlcvs = binance.fetch_ohlcv('ETH/BTC')
print(ohlcvs)
================================================
FILE: ch08/08_24.py
================================================
import ccxt
from datetime import datetime
binance = ccxt.binance()
ohlcvs = binance.fetch_ohlcv('ETH/BTC')
for ohlc in ohlcvs:
print(datetime.fromtimestamp(ohlc[0]/1000).strftime('%Y-%m-%d %H:%M:%S'))
================================================
FILE: ch08/08_25.py
================================================
import ccxt
binance = ccxt.binance()
orderbook = binance.fetch_order_book('ETH/BTC')
print(orderbook['bids'])
print(orderbook['asks'])
================================================
FILE: ch08/08_26.py
================================================
import ccxt
binance = ccxt.binance()
orderbook = binance.fetch_order_book('ETH/BTC')
for ask in orderbook['asks']:
print(ask[0], ask[1])
================================================
FILE: ch09/09_01.py
================================================
def sync_func1():
print("Hello")
def sync_func2():
print("Bye")
sync_func1()
sync_func2()
================================================
FILE: ch09/09_02.py
================================================
import asyncio
async def async_func1():
print("Hello")
async_func1()
#asyncio.run(async_func1())
================================================
FILE: ch09/09_03.py
================================================
import asyncio
async def async_func1():
print("Hello")
loop = asyncio.get_event_loop()
loop.run_until_complete(async_func1())
loop.close()
================================================
FILE: ch09/09_04.py
================================================
import asyncio
async def make_americano():
print("Americano Start")
await asyncio.sleep(3)
print("Americano End")
async def make_latte():
print("Latte Start")
await asyncio.sleep(5)
print("Latte End")
async def main():
coro1 = make_americano()
coro2 = make_latte()
await asyncio.gather(
coro1,
coro2
)
print("Main Start")
asyncio.run(main())
print("Main End")
================================================
FILE: ch09/09_05.py
================================================
import asyncio
async def make_americano():
print("Americano Start")
await asyncio.sleep(3)
print("Americano End")
return "Americano"
async def make_latte():
print("Latte Start")
await asyncio.sleep(5)
print("Latte End")
return "Latte"
async def main():
coro1 = make_americano()
coro2 = make_latte()
result = await asyncio.gather(
coro1,
coro2
)
print(result)
print("Main Start")
asyncio.run(main())
print("Main End")
================================================
FILE: ch09/09_06.py
================================================
import multiprocessing as mp
if __name__ == "__main__":
proc = mp.current_process()
print(proc.name)
print(proc.pid)
================================================
FILE: ch09/09_07.py
================================================
import multiprocessing as mp
import time
def worker():
proc = mp.current_process()
print(proc.name)
print(proc.pid)
time.sleep(5)
print("SubProcess End")
if __name__ == "__main__":
# main process
proc = mp.current_process()
print(proc.name)
print(proc.pid)
# process spawning
p = mp.Process(name="SubProcess", target=worker)
p.start()
print("MainProcess End")
================================================
FILE: ch09/09_08.py
================================================
import websockets
import asyncio
async def bithumb_ws_client():
uri = "wss://pubwss.bithumb.com/pub/ws"
async with websockets.connect(uri) as websocket:
greeting = await websocket.recv()
print(greeting)
async def main():
await bithumb_ws_client()
asyncio.run(main())
================================================
FILE: ch09/09_09.py
================================================
import websockets
import asyncio
import json
async def bithumb_ws_client():
uri = "wss://pubwss.bithumb.com/pub/ws"
async with websockets.connect(uri, ping_interval=None) as websocket:
greeting = await websocket.recv()
print(greeting)
subscribe_fmt = {
"type":"ticker",
"symbols": ["BTC_KRW"],
"tickTypes": ["1H"]
}
subscribe_data = json.dumps(subscribe_fmt)
await websocket.send(subscribe_data)
while True:
data = await websocket.recv()
data = json.loads(data)
print(data)
async def main():
await bithumb_ws_client()
asyncio.run(main())
================================================
FILE: ch09/09_10.py
================================================
import multiprocessing as mp
import websockets
import asyncio
import json
import sys
import datetime
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
async def bithumb_ws_client(q):
uri = "wss://pubwss.bithumb.com/pub/ws"
async with websockets.connect(uri, ping_interval=None) as websocket:
subscribe_fmt = {
"type":"ticker",
"symbols": ["BTC_KRW"],
"tickTypes": ["1H"]
}
subscribe_data = json.dumps(subscribe_fmt)
await websocket.send(subscribe_data)
while True:
data = await websocket.recv()
data = json.loads(data)
q.put(data)
async def main(q):
await bithumb_ws_client(q)
def producer(q):
asyncio.run(main(q))
class Consumer(QThread):
poped = pyqtSignal(dict)
def __init__(self, q):
super().__init__()
self.q = q
def run(self):
while True:
if not self.q.empty():
data = q.get()
self.poped.emit(data)
class MyWindow(QMainWindow):
def __init__(self, q):
super().__init__()
self.setGeometry(200, 200, 400, 200)
self.setWindowTitle("Bithumb Websocket with PyQt")
# thread for data consumer
self.consumer = Consumer(q)
self.consumer.poped.connect(self.print_data)
self.consumer.start()
# widget
self.label = QLabel("Bitcoin: ", self)
self.label.move(10, 10)
# QLineEdit
self.line_edit = QLineEdit(" ", self)
self.line_edit.resize(150, 30)
self.line_edit.move(100, 10)
@pyqtSlot(dict)
def print_data(self, data):
content = data.get('content')
if content is not None:
current_price = int(content.get('closePrice'))
self.line_edit.setText(format(current_price, ",d"))
now = datetime.datetime.now()
self.statusBar().showMessage(str(now))
if __name__ == "__main__":
q = mp.Queue()
p = mp.Process(name="Producer", target=producer, args=(q,), daemon=True)
p.start()
# Main process
app = QApplication(sys.argv)
mywindow = MyWindow(q)
mywindow.show()
app.exec_()
================================================
FILE: ch09/09_11.py
================================================
from pybithumb import WebSocketManager
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QIcon
import time
class Worker(QThread):
recv = pyqtSignal(str)
def run(self):
# create websocket for Bithumb
wm = WebSocketManager("ticker", ["BTC_KRW"])
while True:
data = wm.get()
self.recv.emit(data['content']['closePrice'])
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
label = QLabel("BTC", self)
label.move(20, 20)
self.price = QLabel("-", self)
self.price.move(80, 20)
self.price.resize(100, 20)
button = QPushButton("Start", self)
button.move(20, 50)
button.clicked.connect(self.click_btn)
self.th = Worker()
self.th.recv.connect(self.receive_msg)
@pyqtSlot(str)
def receive_msg(self, msg):
print(msg)
self.price.setText(msg)
def click_btn(self):
self.th.start()
if __name__ == '__main__':
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
================================================
FILE: ch09/09_12.py
================================================
# korbit websocket connection
import websockets
import asyncio
async def korbit_ws_client():
uri = "wss://ws.korbit.co.kr/v1/user/push"
async with websockets.connect(uri) as websocket:
greeting = await websocket.recv()
print(greeting)
async def main():
await korbit_ws_client()
asyncio.run(main())
================================================
FILE: ch09/09_13.py
================================================
# Korbit Websocket Subscribe Example
import websockets
import asyncio
import json
import datetime
import pprint
async def korbit_ws_client():
uri = "wss://ws.korbit.co.kr/v1/user/push"
async with websockets.connect(uri) as websocket:
now = datetime.datetime.now()
timestamp = int(now.timestamp() * 1000)
subscribe_fmt = {
"accessToken": None,
"timestamp": timestamp,
"event": "korbit:subscribe",
"data": {
"channels": ["ticker:btc_krw"]
}
}
subscribe_data = json.dumps(subscribe_fmt)
await websocket.send(subscribe_data)
while True:
data = await websocket.recv()
data = json.loads(data)
pprint.pprint(data)
async def main():
await korbit_ws_client()
asyncio.run(main())
================================================
FILE: ch09/09_14.py
================================================
import multiprocessing as mp
import websockets
import asyncio
import json
import datetime
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import threading
async def korbit_ws_client(q):
uri = "wss://ws.korbit.co.kr/v1/user/push"
async with websockets.connect(uri) as websocket:
now = datetime.datetime.now()
timestamp = int(now.timestamp() * 1000)
subscribe_fmt = {
"accessToken": None,
"timestamp": timestamp,
"event": "korbit:subscribe",
"data": {
"channels": ["ticker:btc_krw"]
}
}
subscribe_data = json.dumps(subscribe_fmt)
await websocket.send(subscribe_data)
while True:
data = await websocket.recv()
data = json.loads(data)
q.put(data)
async def main(q):
await korbit_ws_client(q)
def producer(q):
proc = mp.current_process()
print("producer's Process: ", proc.name)
print("producer's Thread : ", threading.currentThread().getName())
asyncio.run(main(q))
class Consumer(QThread):
poped = pyqtSignal(dict)
def __init__(self, q):
super().__init__()
self.q = q
def run(self):
proc = mp.current_process()
print("consumer's Process: ", proc.name)
print("consumer's Thread : ", threading.currentThread().getName())
while True:
if not self.q.empty():
data = q.get()
self.poped.emit(data)
class MyWindow(QMainWindow):
def __init__(self, q):
super().__init__()
self.setGeometry(200, 200, 400, 200)
self.setWindowTitle("Korbit Websocket")
# thread for data consumer
proc = mp.current_process()
print("windows's Process: ", proc.name)
print("windows's Thread : ", threading.currentThread().getName())
self.consumer = Consumer(q)
self.consumer.poped.connect(self.print_data)
self.consumer.start()
# widget
self.label = QLabel("Bitcoin: ", self)
self.label.move(10, 10)
# QLineEdit
self.line_edit = QLineEdit(" ", self)
self.line_edit.resize(150, 30)
self.line_edit.move(100, 10)
@pyqtSlot(dict)
def print_data(self, data):
timestamp = data.get('timestamp')
data_dict = data.get('data')
last = data_dict.get('last')
if last is not None:
current_price = int(last)
self.line_edit.setText(format(current_price, ",d"))
now = datetime.datetime.fromtimestamp(int(timestamp)/1000)
self.statusBar().showMessage(str(now))
if __name__ == "__main__":
q = mp.Queue()
p = mp.Process(name="Producer", target=producer, args=(q,), daemon=True)
p.start()
# Main process
app = QApplication(sys.argv)
mywindow = MyWindow(q)
mywindow.show()
app.exec_()
================================================
FILE: ch09/09_15.py
================================================
import websockets
import asyncio
import json
async def upbit_ws_client():
uri = "wss://api.upbit.com/websocket/v1"
async with websockets.connect(uri) as websocket:
subscribe_fmt = [
{"ticket":"test"},
{
"type": "ticker",
"codes":["KRW-BTC"],
"isOnlyRealtime": True
},
{"format":"SIMPLE"}
]
subscribe_data = json.dumps(subscribe_fmt)
await websocket.send(subscribe_data)
while True:
data = await websocket.recv()
data = json.loads(data)
print(data)
async def main():
await upbit_ws_client()
asyncio.run(main())
================================================
FILE: ch09/09_16.py
================================================
import multiprocessing as mp
import websockets
import asyncio
import json
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
async def upbit_ws_client(q):
uri = "wss://api.upbit.com/websocket/v1"
async with websockets.connect(uri) as websocket:
subscribe_fmt = [
{"ticket":"test"},
{
"type": "ticker",
"codes":["KRW-BTC"],
"isOnlyRealtime": True
},
{"format":"SIMPLE"}
]
subscribe_data = json.dumps(subscribe_fmt)
await websocket.send(subscribe_data)
while True:
data = await websocket.recv()
data = json.loads(data)
q.put(data)
async def main(q):
await upbit_ws_client(q)
def producer(q):
asyncio.run(main(q))
class Consumer(QThread):
poped = pyqtSignal(dict)
def __init__(self, q):
super().__init__()
self.q = q
def run(self):
while True:
if not self.q.empty():
data = q.get()
self.poped.emit(data)
class MyWindow(QMainWindow):
def __init__(self, q):
super().__init__()
self.setGeometry(200, 200, 400, 200)
self.setWindowTitle("Upbit Websocket")
# thread for data consumer
self.consumer = Consumer(q)
self.consumer.poped.connect(self.print_data)
self.consumer.start()
# widget
self.label = QLabel("Bitcoin: ", self)
self.label.move(10, 10)
# QLineEdit
self.line_edit = QLineEdit(" ", self)
self.line_edit.resize(150, 30)
self.line_edit.move(100, 10)
@pyqtSlot(dict)
def print_data(self, data):
current_price = int(data.get('tp'))
self.line_edit.setText(format(current_price, ",d"))
if __name__ == "__main__":
q = mp.Queue()
p = mp.Process(name="Producer", target=producer, args=(q,), daemon=True)
p.start()
# Main process
app = QApplication(sys.argv)
mywindow = MyWindow(q)
mywindow.show()
app.exec_()
================================================
FILE: ch09/09_17.py
================================================
from pyupbit import WebSocketManager
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Worker(QThread):
recv = pyqtSignal(dict)
def run(self):
# create websocket for Bithumb
wm = WebSocketManager("ticker", ["KRW-BTC"])
while True:
data = wm.get()
print(data)
self.recv.emit(data)
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
label = QLabel("BTC", self)
label.move(20, 20)
self.price = QLabel("", self)
self.price.move(80, 20)
self.price.resize(100, 20)
button = QPushButton("Start", self)
button.move(20, 50)
button.clicked.connect(self.click_btn)
self.th = Worker()
self.th.recv.connect(self.receive_msg)
@pyqtSlot(dict)
def receive_msg(self, data):
print(data)
close_price = data.get("trade_price")
self.price.setText(str(close_price))
def click_btn(self):
self.th.start()
if __name__ == '__main__':
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
================================================
FILE: ch10/chart.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QPainter
from PyQt5.QtChart import QLineSeries, QChart, QValueAxis, QDateTimeAxis
from PyQt5.QtCore import Qt, QDateTime
import time
import pybithumb
from PyQt5.QtCore import QThread, pyqtSignal
class PriceWorker(QThread):
dataSent = pyqtSignal(float)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
while self.alive:
data = pybithumb.get_current_price(self.ticker)
time.sleep(1)
if data != None:
self.dataSent.emit(data)
def close(self):
self.alive = False
class ChartWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/chart.ui", self)
self.ticker = ticker
self.viewLimit = 128
self.priceData = QLineSeries()
self.priceChart = QChart()
self.priceChart.addSeries(self.priceData)
self.priceChart.legend().hide()
axisX = QDateTimeAxis()
axisX.setFormat("hh:mm:ss")
axisX.setTickCount(4)
dt = QDateTime.currentDateTime()
axisX.setRange(dt, dt.addSecs(self.viewLimit))
axisY = QValueAxis()
axisY.setVisible(False)
self.priceChart.addAxis(axisX, Qt.AlignBottom)
self.priceChart.addAxis(axisY, Qt.AlignRight)
self.priceData.attachAxis(axisX)
self.priceData.attachAxis(axisY)
self.priceChart.layout().setContentsMargins(0, 0, 0, 0)
self.priceView.setChart(self.priceChart)
self.priceView.setRenderHints(QPainter.Antialiasing)
self.pw = PriceWorker(ticker)
self.pw.dataSent.connect(self.appendData)
self.pw.start()
def appendData(self, currPirce):
if len(self.priceData) == self.viewLimit :
self.priceData.remove(0)
dt = QDateTime.currentDateTime()
self.priceData.append(dt.toMSecsSinceEpoch(), currPirce)
self.__updateAxis()
def __updateAxis(self):
pvs = self.priceData.pointsVector()
dtStart = QDateTime.fromMSecsSinceEpoch(int(pvs[0].x()))
if len(self.priceData) == self.viewLimit :
dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1].x()))
else:
dtLast = dtStart.addSecs(self.viewLimit)
ax = self.priceChart.axisX()
ax.setRange(dtStart, dtLast)
ay = self.priceChart.axisY()
dataY = [v.y() for v in pvs]
ay.setRange(min(dataY), max(dataY))
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
cw = ChartWidget()
cw.show()
exit(app.exec_())
================================================
FILE: ch10/chart_0.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
class ChartWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/chart.ui", self)
self.ticker = ticker
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
cw = ChartWidget()
cw.show()
exit(app.exec_())
================================================
FILE: ch10/chart_1.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
# ----------------- 추 가 ------------------
from PyQt5.QtChart import QLineSeries, QChart
# ------------------------------------------
class ChartWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/chart.ui", self)
self.ticker = ticker
# ----------------- 추 가 ------------------
self.viewLimit = 128
self.priceData = QLineSeries()
self.priceData.append(0, 10)
self.priceData.append(1, 20)
self.priceData.append(2, 10)
self.priceChart = QChart()
self.priceChart.addSeries(self.priceData)
self.priceView.setChart(self.priceChart)
# ------------------------------------------
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
cw = ChartWidget()
cw.show()
exit(app.exec_())
================================================
FILE: ch10/chart_2.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtChart import QLineSeries, QChart
# ----------------- 추 가 ------------------
from PyQt5.QtGui import QPainter
# ------------------------------------------
class ChartWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/chart.ui", self)
self.ticker = ticker
self.viewLimit = 128
self.priceData = QLineSeries()
self.priceData.append(0, 10)
self.priceData.append(1, 20)
self.priceData.append(2, 10)
self.priceChart = QChart()
self.priceChart.addSeries(self.priceData)
self.priceView.setChart(self.priceChart)
# ----------------- 추 가 ------------------
self.priceChart.legend().hide()
self.priceView.setRenderHints(QPainter.Antialiasing)
# ------------------------------------------
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
cw = ChartWidget()
cw.show()
exit(app.exec_())
================================================
FILE: ch10/chart_3.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QPainter
# ----------------- 추 가 ------------------
from PyQt5.QtChart import QLineSeries, QChart, QValueAxis, QDateTimeAxis
from PyQt5.QtCore import Qt, QDateTime
# ------------------------------------------
class ChartWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/chart.ui", self)
self.ticker = ticker
self.viewLimit = 128
self.priceData = QLineSeries()
self.priceChart = QChart()
self.priceChart.addSeries(self.priceData)
self.priceChart.legend().hide()
# ----------------- 추 가 ------------------
axisX = QDateTimeAxis()
axisX.setFormat("hh:mm:ss")
axisX.setTickCount(4)
dt = QDateTime.currentDateTime()
axisX.setRange(dt, dt.addSecs(self.viewLimit))
axisY = QValueAxis()
axisY.setVisible(False)
self.priceChart.addAxis(axisX, Qt.AlignBottom)
self.priceChart.addAxis(axisY, Qt.AlignRight)
self.priceData.attachAxis(axisX)
self.priceData.attachAxis(axisY)
self.priceChart.layout().setContentsMargins(0, 0, 0, 0)
# ------------------------------------------
self.priceView.setChart(self.priceChart)
self.priceView.setRenderHints(QPainter.Antialiasing)
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
cw = ChartWidget()
cw.show()
exit(app.exec_())
================================================
FILE: ch10/chart_4.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QPainter
from PyQt5.QtChart import QLineSeries, QChart, QValueAxis, QDateTimeAxis
from PyQt5.QtCore import Qt, QDateTime
class ChartWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/chart.ui", self)
self.ticker = ticker
self.viewLimit = 128
self.priceData = QLineSeries()
self.priceChart = QChart()
self.priceChart.addSeries(self.priceData)
self.priceChart.legend().hide()
axisX = QDateTimeAxis()
axisX.setFormat("hh:mm:ss")
axisX.setTickCount(4)
dt = QDateTime.currentDateTime()
axisX.setRange(dt, dt.addSecs(self.viewLimit))
axisY = QValueAxis()
axisY.setVisible(False)
self.priceChart.addAxis(axisX, Qt.AlignBottom)
self.priceChart.addAxis(axisY, Qt.AlignRight)
self.priceData.attachAxis(axisX)
self.priceData.attachAxis(axisY)
self.priceChart.layout().setContentsMargins(0, 0, 0, 0)
self.priceView.setChart(self.priceChart)
self.priceView.setRenderHints(QPainter.Antialiasing)
# ----------------- 추 가 ------------------
def appendData(self, currPirce):
if len(self.priceData) == self.viewLimit :
self.priceData.remove(0)
dt = QDateTime.currentDateTime()
self.priceData.append(dt.toMSecsSinceEpoch(), currPirce)
self.__updateAxis()
def __updateAxis(self):
pvs = self.priceData.pointsVector()
dtStart = QDateTime.fromMSecsSinceEpoch(int(pvs[0].x()))
if len(self.priceData) == self.viewLimit :
dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1].x()))
else:
dtLast = dtStart.addSecs(self.viewLimit)
ax = self.priceChart.axisX()
ax.setRange(dtStart, dtLast)
ay = self.priceChart.axisY()
dataY = [v.y() for v in pvs]
ay.setRange(min(dataY), max(dataY))
# ------------------------------------------
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
cw = ChartWidget()
cw.appendData(10)
import time
time.sleep(1)
cw.appendData(20)
cw.show()
exit(app.exec_())
================================================
FILE: ch10/chart_5.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QPainter
from PyQt5.QtChart import QLineSeries, QChart, QValueAxis, QDateTimeAxis
from PyQt5.QtCore import Qt, QDateTime
# ----------------- 추 가 ------------------
import time
import pybithumb
from PyQt5.QtCore import QThread, pyqtSignal
class PriceWorker(QThread):
dataSent = pyqtSignal(float)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
while self.alive:
data = pybithumb.get_current_price(self.ticker)
time.sleep(1)
self.dataSent.emit(data)
def close(self):
self.alive = False
# ------------------------------------------
class ChartWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/chart.ui", self)
self.ticker = ticker
self.viewLimit = 128
self.priceData = QLineSeries()
self.priceChart = QChart()
self.priceChart.addSeries(self.priceData)
self.priceChart.legend().hide()
axisX = QDateTimeAxis()
axisX.setFormat("hh:mm:ss")
axisX.setTickCount(4)
dt = QDateTime.currentDateTime()
axisX.setRange(dt, dt.addSecs(self.viewLimit))
axisY = QValueAxis()
axisY.setVisible(False)
self.priceChart.addAxis(axisX, Qt.AlignBottom)
self.priceChart.addAxis(axisY, Qt.AlignRight)
self.priceData.attachAxis(axisX)
self.priceData.attachAxis(axisY)
self.priceChart.layout().setContentsMargins(0, 0, 0, 0)
self.priceView.setChart(self.priceChart)
self.priceView.setRenderHints(QPainter.Antialiasing)
# ----------------- 추 가 ------------------
self.pw = PriceWorker(ticker)
self.pw.dataSent.connect(self.appendData)
self.pw.start()
# ------------------------------------------
def appendData(self, currPirce):
if len(self.priceData) == self.viewLimit :
self.priceData.remove(0)
dt = QDateTime.currentDateTime()
self.priceData.append(dt.toMSecsSinceEpoch(), currPirce)
self.__updateAxis()
def __updateAxis(self):
pvs = self.priceData.pointsVector()
dtStart = QDateTime.fromMSecsSinceEpoch(int(pvs[0].x()))
if len(self.priceData) == self.viewLimit :
dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1].x()))
else:
dtLast = dtStart.addSecs(self.viewLimit)
ax = self.priceChart.axisX()
ax.setRange(dtStart, dtLast)
ay = self.priceChart.axisY()
dataY = [v.y() for v in pvs]
ay.setRange(min(dataY), max(dataY))
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
cw = ChartWidget()
cw.show()
exit(app.exec_())
================================================
FILE: ch10/main.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from pybithumb import Bithumb
import pybithumb
import datetime
from PyQt5.QtCore import QThread, pyqtSignal
from volatility import *
class VolatilityWorker(QThread):
tradingSent = pyqtSignal(str, str, str)
def __init__(self, ticker, bithumb):
super().__init__()
self.ticker = ticker
self.bithumb = bithumb
self.alive = True
def run(self):
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
ma5 = get_yesterday_ma5(self.ticker)
target_price = get_target_price(self.ticker)
wait_flag = False
print("target price :", target_price)
while self.alive:
try:
now = datetime.datetime.now()
if mid < now < mid + datetime.delta(seconds=10):
target_price = get_target_price(self.ticker)
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
ma5 = get_yesterday_ma5(self.ticker)
desc = sell_crypto_currency(self.bithumb, self.ticker)
result = self.bithumb.get_order_completed(desc)
timestamp = result['data']['order_date']
dt = datetime.datetime.fromtimestamp( int(int(timestamp)/1000000) )
tstring = dt.strftime("%Y/%m/%d %H:%M:%S")
self.tradingSent.emit(tstring, "매도", result['data']['order_qty'])
wait_flag = False
if wait_flag == False:
current_price = pybithumb.get_current_price(self.ticker)
if (current_price > target_price) and (current_price > ma5):
desc = buy_crypto_currency(self.bithumb, self.ticker)
result = self.bithumb.get_order_completed(desc)
timestamp = result['data']['order_date']
dt = datetime.datetime.fromtimestamp( int(int(timestamp)/1000000) )
tstring = dt.strftime("%Y/%m/%d %H:%M:%S")
self.tradingSent.emit(tstring, "매수", result['data']['order_qty'])
wait_flag = True
except:
pass
time.sleep(1)
def close(self):
self.alive = False
form_class = uic.loadUiType("resource/main.ui")[0]
class MainWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.ticker = "BTC"
self.button.clicked.connect(self.clickBtn)
self.setWindowTitle("Home Trading System")
with open("bithumb.txt") as f:
lines = f.readlines()
apikey = lines[0].strip()
seckey = lines[1].strip()
self.apiKey.setText(apikey)
self.secKey.setText(seckey)
def clickBtn(self):
if self.button.text() == "매매시작":
apiKey = self.apiKey.text()
secKey = self.secKey.text()
if len(apiKey) != 32 or len(secKey) != 32:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
else:
self.bithumb = Bithumb(apiKey, secKey)
self.balance = self.bithumb.get_balance(self.ticker)
if self.balance == None:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
self.button.setText("매매중지")
self.textEdit.append("------ START ------")
self.textEdit.append(f"보유 현금 : {self.balance[2]} 원")
self.vw = VolatilityWorker(self.ticker, self.bithumb)
self.vw.tradingSent.connect(self.receiveTradingSignal)
self.vw.start()
else:
self.vw.close()
self.textEdit.append("------- END -------")
self.button.setText("매매시작")
def receiveTradingSignal(self, time, type, amount):
self.textEdit.append(f"[{time}] {type} : {amount}")
def closeEvent(self, event):
self.vw.close()
self.widget.closeEvent(event)
self.widget_2.closeEvent(event)
self.widget_3.closeEvent(event)
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
exit(app.exec_())
================================================
FILE: ch10/main_0.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
form_class = uic.loadUiType("resource/main.ui")[0]
class MainWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setWindowTitle("Home Trading System")
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
exit(app.exec_())
================================================
FILE: ch10/main_1.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
form_class = uic.loadUiType("resource/main.ui")[0]
class MainWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setWindowTitle("Home Trading System")
# ----------------- 추 가 ------------------
self.ticker = "BTC" # 추후 사용
self.button.clicked.connect(self.clickBtn)
def clickBtn(self):
if self.button.text() == "매매시작":
text = "매매중지"
else:
text = "매매시작"
self.button.setText(text)
# ------------------------------------------
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
exit(app.exec_())
================================================
FILE: ch10/main_2.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
# ----------------- 추 가 ------------------
from pybithumb import Bithumb
# ------------------------------------------
form_class = uic.loadUiType("resource/main.ui")[0]
class MainWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.ticker = "BTC"
self.button.clicked.connect(self.clickBtn)
self.setWindowTitle("Home Trading System")
def clickBtn(self):
# ----------------- 수 정 ------------------
if self.button.text() == "매매시작":
apiKey = self.apiKey.text()
secKey = self.secKey.text()
if len(apiKey) != 32 or len(secKey) != 32:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
else:
self.bithumb = Bithumb(apiKey, secKey)
self.balance = self.bithumb.get_balance(self.ticker)
if self.balance == None:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
self.button.setText("매매중지")
self.textEdit.append("------ START ------")
self.textEdit.append(f"보유 현금 : {self.balance[2]} 원")
else:
self.textEdit.append("------- END -------")
self.button.setText("매매시작")
# ------------------------------------------
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
exit(app.exec_())
================================================
FILE: ch10/main_3.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
# ----------------- 추 가 ------------------
from pybithumb import Bithumb
# ------------------------------------------
form_class = uic.loadUiType("resource/main.ui")[0]
class MainWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.ticker = "BTC"
self.button.clicked.connect(self.clickBtn)
self.setWindowTitle("Home Trading System")
# ----------------- 추 가 ------------------
with open("bithumb.txt") as f:
lines = f.readlines()
apikey = lines[0].strip()
seckey = lines[1].strip()
self.apiKey.setText(apikey)
self.secKey.setText(seckey)
# ------------------------------------------
def clickBtn(self):
if self.button.text() == "매매시작":
apiKey = self.apiKey.text()
secKey = self.secKey.text()
if len(apiKey) != 32 or len(secKey) != 32:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
else:
self.bithumb = Bithumb(apiKey, secKey)
self.balance = self.bithumb.get_balance(self.ticker)
if self.balance == None:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
self.button.setText("매매중지")
self.textEdit.append("------ START ------")
self.textEdit.append(f"보유 현금 : {self.balance[2]} 원")
else:
self.textEdit.append("------- END -------")
self.button.setText("매매시작")
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
exit(app.exec_())
================================================
FILE: ch10/main_4.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from pybithumb import Bithumb
# ----------------- 추 가 ------------------
import pybithumb
import datetime
import time
from PyQt5.QtCore import QThread, pyqtSignal
class VolatilityWorker(QThread):
tradingSent = pyqtSignal(str, str, str)
def __init__(self, ticker, bithumb):
super().__init__()
self.ticker = ticker
self.bithumb = bithumb
self.alive = True
def run(self):
while self.alive:
self.tradingSent.emit("2021/03/04 12:11:41", "매수", "0.001")
time.sleep(1)
def close(self):
self.alive = False
# ------------------------------------------
form_class = uic.loadUiType("resource/main.ui")[0]
class MainWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.ticker = "BTC"
self.button.clicked.connect(self.clickBtn)
self.setWindowTitle("Home Trading System")
with open("bithumb.txt") as f:
lines = f.readlines()
apikey = lines[0].strip()
seckey = lines[1].strip()
self.apiKey.setText(apikey)
self.secKey.setText(seckey)
def clickBtn(self):
if self.button.text() == "매매시작":
apiKey = self.apiKey.text()
secKey = self.secKey.text()
if len(apiKey) != 32 or len(secKey) != 32:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
else:
self.bithumb = Bithumb(apiKey, secKey)
self.balance = self.bithumb.get_balance(self.ticker)
if self.balance == None:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
self.button.setText("매매중지")
self.textEdit.append("------ START ------")
self.textEdit.append(f"보유 현금 : {self.balance[2]} 원")
# ----------------- 추 가 ------------------
self.vw = VolatilityWorker(self.ticker, self.bithumb)
self.vw.tradingSent.connect(self.receiveTradingSignal)
self.vw.start()
# ------------------------------------------
else:
self.vw.close()
self.textEdit.append("------- END -------")
self.button.setText("매매시작")
# ----------------- 추 가 ------------------
def receiveTradingSignal(self, time, type, amount):
self.textEdit.append(f"[{time}] {type} : {amount}")
# ------------------------------------------
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
exit(app.exec_())
================================================
FILE: ch10/main_5.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from pybithumb import Bithumb
import pybithumb
import datetime
from PyQt5.QtCore import QThread, pyqtSignal
from volatility import *
class VolatilityWorker(QThread):
tradingSent = pyqtSignal(str, str, str)
def __init__(self, ticker, bithumb):
super().__init__()
self.ticker = ticker
self.bithumb = bithumb
self.alive = True
# ----------------- 수 정 ------------------
def run(self):
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
ma5 = get_yesterday_ma5(self.ticker)
target_price = get_target_price(self.ticker)
wait_flag = False
while self.alive:
try:
now = datetime.datetime.now()
if mid < now < mid + datetime.delta(seconds=10):
target_price = get_target_price(self.ticker)
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
ma5 = get_yesterday_ma5(self.ticker)
desc = sell_crypto_currency(self.bithumb, self.ticker)
result = self.bithumb.get_order_completed(desc)
timestamp = result['data']['order_date']
dt = datetime.datetime.fromtimestamp( int(int(timestamp)/1000000) )
tstring = dt.strftime("%Y/%m/%d %H:%M:%S")
self.tradingSent.emit(tstring, "매도", result['data']['order_qty'])
wait_flag = False
if wait_flag == False:
current_price = pybithumb.get_current_price(self.ticker)
if (current_price > target_price) and (current_price > ma5):
desc = buy_crypto_currency(self.bithumb, self.ticker)
result = self.bithumb.get_order_completed(desc)
timestamp = result['data']['order_date']
dt = datetime.datetime.fromtimestamp( int(int(timestamp)/1000000) )
tstring = dt.strftime("%Y/%m/%d %H:%M:%S")
self.tradingSent.emit(tstring, "매수", result['data']['order_qty'])
wait_flag = True
except:
pass
time.sleep(1)
# ------------------------------------------
def close(self):
self.alive = False
form_class = uic.loadUiType("resource/main.ui")[0]
class MainWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.ticker = "BTC"
self.button.clicked.connect(self.clickBtn)
self.setWindowTitle("Home Trading System")
with open("bithumb.txt") as f:
lines = f.readlines()
apikey = lines[0].strip()
seckey = lines[1].strip()
self.apiKey.setText(apikey)
self.secKey.setText(seckey)
def clickBtn(self):
if self.button.text() == "매매시작":
apiKey = self.apiKey.text()
secKey = self.secKey.text()
if len(apiKey) != 32 or len(secKey) != 32:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
else:
self.bithumb = Bithumb(apiKey, secKey)
self.balance = self.bithumb.get_balance(self.ticker)
if self.balance == None:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
self.button.setText("매매중지")
self.textEdit.append("------ START ------")
self.textEdit.append(f"보유 현금 : {self.balance[2]} 원")
self.vw = VolatilityWorker(self.ticker, self.bithumb)
self.vw.tradingSent.connect(self.receiveTradingSignal)
self.vw.start()
else:
self.vw.close()
self.textEdit.append("------- END -------")
self.button.setText("매매시작")
def receiveTradingSignal(self, time, type, amount):
self.textEdit.append(f"[{time}] {type} : {amount}")
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
exit(app.exec_())
================================================
FILE: ch10/main_6.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from pybithumb import Bithumb
import pybithumb
import datetime
from PyQt5.QtCore import QThread, pyqtSignal
from volatility import *
class VolatilityWorker(QThread):
tradingSent = pyqtSignal(str, str, str)
def __init__(self, ticker, bithumb):
super().__init__()
self.ticker = ticker
self.bithumb = bithumb
self.alive = True
def run(self):
now = datetime.datetime.now()
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
ma5 = get_yesterday_ma5(self.ticker)
target_price = get_target_price(self.ticker)
wait_flag = False
print("target price :", target_price)
while self.alive:
try:
now = datetime.datetime.now()
if mid < now < mid + datetime.delta(seconds=10):
target_price = get_target_price(self.ticker)
mid = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1)
ma5 = get_yesterday_ma5(self.ticker)
desc = sell_crypto_currency(self.bithumb, self.ticker)
result = self.bithumb.get_order_completed(desc)
timestamp = result['data']['order_date']
dt = datetime.datetime.fromtimestamp( int(int(timestamp)/1000000) )
tstring = dt.strftime("%Y/%m/%d %H:%M:%S")
self.tradingSent.emit(tstring, "매도", result['data']['order_qty'])
wait_flag = False
if wait_flag == False:
current_price = pybithumb.get_current_price(self.ticker)
if (current_price > target_price) and (current_price > ma5):
desc = buy_crypto_currency(self.bithumb, self.ticker)
result = self.bithumb.get_order_completed(desc)
timestamp = result['data']['order_date']
dt = datetime.datetime.fromtimestamp( int(int(timestamp)/1000000) )
tstring = dt.strftime("%Y/%m/%d %H:%M:%S")
self.tradingSent.emit(tstring, "매수", result['data']['order_qty'])
wait_flag = True
except:
pass
time.sleep(1)
def close(self):
self.alive = False
form_class = uic.loadUiType("resource/main.ui")[0]
class MainWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.ticker = "BTC"
self.button.clicked.connect(self.clickBtn)
self.setWindowTitle("Home Trading System")
with open("bithumb.txt") as f:
lines = f.readlines()
apikey = lines[0].strip()
seckey = lines[1].strip()
self.apiKey.setText(apikey)
self.secKey.setText(seckey)
def clickBtn(self):
if self.button.text() == "매매시작":
apiKey = self.apiKey.text()
secKey = self.secKey.text()
if len(apiKey) != 32 or len(secKey) != 32:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
else:
self.bithumb = Bithumb(apiKey, secKey)
self.balance = self.bithumb.get_balance(self.ticker)
if self.balance == None:
self.textEdit.append("KEY가 올바르지 않습니다.")
return
self.button.setText("매매중지")
self.textEdit.append("------ START ------")
self.textEdit.append(f"보유 현금 : {self.balance[2]} 원")
self.vw = VolatilityWorker(self.ticker, self.bithumb)
self.vw.tradingSent.connect(self.receiveTradingSignal)
self.vw.start()
else:
self.vw.close()
self.textEdit.append("------- END -------")
self.button.setText("매매시작")
def receiveTradingSignal(self, time, type, amount):
self.textEdit.append(f"[{time}] {type} : {amount}")
# ----------------- 추 가 ------------------
def closeEvent(self, event):
self.vw.close()
self.widget.closeEvent(event)
self.widget_2.closeEvent(event)
self.widget_3.closeEvent(event)
# ------------------------------------------
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
exit(app.exec_())
================================================
FILE: ch10/orderbook.py
================================================
import sys
import time
import pybithumb
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QTableWidgetItem, QProgressBar
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QPropertyAnimation
class OrderbookWorker(QThread):
dataSent = pyqtSignal(dict)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
while self.alive:
data = pybithumb.get_orderbook(self.ticker, limit=10)
time.sleep(0.05)
if data != None:
self.dataSent.emit(data)
def close(self):
self.alive = False
class OrderbookWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/orderbook.ui", self)
self.ticker = ticker
self.asksAnim = [ ]
self.bidsAnim = [ ]
for i in range(self.tableBids.rowCount()):
# 매도호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableAsks)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0);border : 0}
QProgressBar::Chunk {background-color : rgba(255, 0, 0, 0.5);border : 0}
""")
self.tableAsks.setCellWidget(i, 2, item_2)
anim = QPropertyAnimation(item_2, b"value")
anim.setDuration(200)
self.asksAnim.append(anim)
# 매수호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableBids)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0);border : 1}
QProgressBar::Chunk {background-color : rgba(0, 255, 0, 0.4);border : 1}
""")
self.tableBids.setCellWidget(i, 2, item_2)
anim = QPropertyAnimation(item_2, b"value")
anim.setDuration(200)
anim.setStartValue(0)
self.bidsAnim.append(anim)
self.ow = OrderbookWorker(self.ticker)
self.ow.dataSent.connect(self.updateData)
self.ow.start()
def updateData(self, data):
tradingBidValues = [ ]
for v in data['bids']:
tradingBidValues.append(int(v['price'] * v['quantity']))
tradingAskValues = [ ]
for v in data['asks'][::-1]:
tradingAskValues.append(int(v['price'] * v['quantity']))
maxtradingValue = max(tradingBidValues + tradingAskValues)
for i, v in enumerate(data['asks'][::-1]):
item_0 = self.tableAsks.item(i, 0)
item_0.setText(f"{v['price']:,}")
item_1 = self.tableAsks.item(i, 1)
item_1.setText(f"{v['quantity']:,}")
item_2 = self.tableAsks.cellWidget(i, 2)
item_2.setRange(0, maxtradingValue)
item_2.setFormat(f"{tradingAskValues[i]:,}")
self.asksAnim[i].setStartValue(item_2.value() if item_2.value() > 0 else 0)
self.asksAnim[i].setEndValue(tradingAskValues[i])
self.asksAnim[i].start()
for i, v in enumerate(data['bids']):
item_0 = self.tableBids.item(i, 0)
item_0.setText(f"{v['price']:,}")
item_1 = self.tableBids.item(i, 1)
item_1.setText(f"{v['quantity']:,}")
item_2 = self.tableBids.cellWidget(i, 2)
item_2.setRange(0, maxtradingValue)
item_2.setFormat(f"{tradingBidValues[i]:,}")
self.bidsAnim[i].setStartValue(item_2.value())
self.bidsAnim[i].setEndValue(tradingBidValues[i])
self.bidsAnim[i].start()
def closeEvent(self, event):
self.ow.close()
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ow = OrderbookWidget()
ow.show()
exit(app.exec_())
================================================
FILE: ch10/orderbook_0.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
class OrderbookWidget(QWidget):
def __init__(self, ticker="BTC"):
super().__init__()
uic.loadUi("resource/orderbook.ui", self)
self.ticker = ticker
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ow = OrderbookWidget()
ow.show()
exit(app.exec_())
================================================
FILE: ch10/orderbook_1.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
# ----------------- 추 가 ------------------
from PyQt5.QtWidgets import QTableWidgetItem, QProgressBar
from PyQt5.QtCore import Qt
# ------------------------------------------
class OrderbookWidget(QWidget):
def __init__(self, ticker="BTC"):
super().__init__()
uic.loadUi("resource/orderbook.ui", self)
self.ticker = ticker
# ----------------- 추 가 ------------------
for i in range(self.tableBids.rowCount()):
# 매도호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableAsks)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0%);border : 1}
QProgressBar::Chunk {background-color : rgba(255, 0, 0, 50%);border : 1}
""")
self.tableAsks.setCellWidget(i, 2, item_2)
# 매수호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableBids)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0%);border : 1}
QProgressBar::Chunk {background-color : rgba(0, 255, 0, 40%);border : 1}
""")
self.tableBids.setCellWidget(i, 2, item_2)
# ------------------------------------------
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ow = OrderbookWidget()
ow.show()
exit(app.exec_())
================================================
FILE: ch10/orderbook_2.py
================================================
import sys
import time
import pybithumb
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QTableWidgetItem, QProgressBar
from PyQt5.QtCore import Qt, QThread, pyqtSignal
# ----------------- 추 가 ------------------
class OrderbookWorker(QThread):
dataSent = pyqtSignal(dict)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
while self.alive:
data = pybithumb.get_orderbook(self.ticker, limit=10)
time.sleep(0.05)
self.dataSent.emit(data)
def close(self):
self.alive = False
# ------------------------------------------
class OrderbookWidget(QWidget):
def __init__(self, ticker="BTC"):
super().__init__()
uic.loadUi("resource/orderbook.ui", self)
self.ticker = ticker
for i in range(self.tableBids.rowCount()):
# 매도호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableAsks)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0%);border : 1}
QProgressBar::Chunk {background-color : rgba(255, 0, 0, 50%);border : 1}
""")
self.tableAsks.setCellWidget(i, 2, item_2)
# 매수호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableBids)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0%);border : 1}
QProgressBar::Chunk {background-color : rgba(0, 255, 0, 40%);border : 1}
""")
self.tableBids.setCellWidget(i, 2, item_2)
# ----------------- 추 가 ------------------
self.ow = OrderbookWorker(self.ticker)
self.ow.dataSent.connect(self.updateData)
self.ow.start()
def updateData(self, data):
print(data)
def closeEvent(self, event):
self.ow.close()
# ------------------------------------------
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ow = OrderbookWidget()
ow.show()
exit(app.exec_())
================================================
FILE: ch10/orderbook_3.py
================================================
import sys
import time
import pybithumb
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QTableWidgetItem, QProgressBar
from PyQt5.QtCore import Qt, QThread, pyqtSignal
class OrderbookWorker(QThread):
dataSent = pyqtSignal(dict)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
while self.alive:
data = pybithumb.get_orderbook(self.ticker, limit=10)
time.sleep(0.05)
self.dataSent.emit(data)
def close(self):
self.alive = False
class OrderbookWidget(QWidget):
def __init__(self, ticker="BTC"):
super().__init__()
uic.loadUi("resource/orderbook.ui", self)
self.ticker = ticker
for i in range(self.tableBids.rowCount()):
# 매도호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableAsks)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0%);border : 1}
QProgressBar::Chunk {background-color : rgba(255, 0, 0, 50%);border : 1}
""")
self.tableAsks.setCellWidget(i, 2, item_2)
# 매수호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableBids)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0%);border : 1}
QProgressBar::Chunk {background-color : rgba(0, 255, 0, 40%);border : 1}
""")
self.tableBids.setCellWidget(i, 2, item_2)
self.ow = OrderbookWorker(self.ticker)
self.ow.dataSent.connect(self.updateData)
self.ow.start()
def updateData(self, data):
# ----------------- 수 정 ------------------
tradingBidValues = [ ]
for v in data['bids']:
tradingBidValues.append(int(v['price'] * v['quantity']))
tradingAskValues = [ ]
for v in data['asks'][::-1]:
tradingAskValues.append(int(v['price'] * v['quantity']))
maxtradingValue = max(tradingBidValues + tradingAskValues)
for i, v in enumerate(data['asks'][::-1]):
item_0 = self.tableAsks.item(i, 0)
item_0.setText(f"{v['price']:,}")
item_1 = self.tableAsks.item(i, 1)
item_1.setText(f"{v['quantity']:,}")
item_2 = self.tableAsks.cellWidget(i, 2)
item_2.setRange(0, maxtradingValue)
item_2.setFormat(f"{tradingAskValues[i]:,}")
item_2.setValue(tradingAskValues[i])
for i, v in enumerate(data['bids']):
item_0 = self.tableBids.item(i, 0)
item_0.setText(f"{v['price']:,}")
item_1 = self.tableBids.item(i, 1)
item_1.setText(f"{v['quantity']:,}")
item_2 = self.tableBids.cellWidget(i, 2)
item_2.setRange(0, maxtradingValue)
item_2.setFormat(f"{tradingBidValues[i]:,}")
item_2.setValue(tradingBidValues[i])
# ------------------------------------------
def closeEvent(self, event):
self.ow.close()
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ow = OrderbookWidget()
ow.show()
exit(app.exec_())
================================================
FILE: ch10/orderbook_4.py
================================================
import sys
import time
import pybithumb
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QTableWidgetItem, QProgressBar
# ----------------- 수 정 ------------------
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QPropertyAnimation
# ------------------------------------------
class OrderbookWorker(QThread):
dataSent = pyqtSignal(dict)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
while self.alive:
data = pybithumb.get_orderbook(self.ticker, limit=10)
time.sleep(0.05)
self.dataSent.emit(data)
def close(self):
self.alive = False
class OrderbookWidget(QWidget):
def __init__(self, ticker="BTC"):
super().__init__()
uic.loadUi("resource/orderbook.ui", self)
self.ticker = ticker
# ----------------- 추 가 ------------------
self.asksAnim = [ ]
self.bidsAnim = [ ]
# ------------------------------------------
for i in range(self.tableBids.rowCount()):
# 매도호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableAsks.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableAsks)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0%);border : 1}
QProgressBar::Chunk {background-color : rgba(255, 0, 0, 50%);border : 1}
""")
self.tableAsks.setCellWidget(i, 2, item_2)
# ----------------- 추 가 ------------------
anim = QPropertyAnimation(item_2, b"value")
anim.setDuration(200)
self.asksAnim.append(anim)
# ------------------------------------------
# 매수호가
item_0 = QTableWidgetItem(str(""))
item_0.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 0, item_0)
item_1 = QTableWidgetItem(str(""))
item_1.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.tableBids.setItem(i, 1, item_1)
item_2 = QProgressBar(self.tableBids)
item_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
item_2.setStyleSheet("""
QProgressBar {background-color : rgba(0, 0, 0, 0%);border : 1}
QProgressBar::Chunk {background-color : rgba(0, 255, 0, 40%);border : 1}
""")
self.tableBids.setCellWidget(i, 2, item_2)
# ----------------- 추 가 ------------------
anim = QPropertyAnimation(item_2, b"value")
anim.setDuration(200)
self.bidsAnim.append(anim)
# ------------------------------------------
self.ow = OrderbookWorker(self.ticker)
self.ow.dataSent.connect(self.updateData)
self.ow.start()
def updateData(self, data):
tradingBidValues = [ ]
for v in data['bids']:
tradingBidValues.append(int(v['price'] * v['quantity']))
tradingAskValues = [ ]
for v in data['asks'][::-1]:
tradingAskValues.append(int(v['price'] * v['quantity']))
maxtradingValue = max(tradingBidValues + tradingAskValues)
for i, v in enumerate(data['asks'][::-1]):
item_0 = self.tableAsks.item(i, 0)
item_0.setText(f"{v['price']:,}")
item_1 = self.tableAsks.item(i, 1)
item_1.setText(f"{v['quantity']:,}")
item_2 = self.tableAsks.cellWidget(i, 2)
item_2.setRange(0, maxtradingValue)
item_2.setFormat(f"{tradingAskValues[i]:,}")
# item_2.setValue(tradingAskValues[i])
# ----------------- 추 가 ------------------
self.asksAnim[i].setStartValue(item_2.value() if item_2.value() > 0 else 0)
self.asksAnim[i].setEndValue(tradingAskValues[i])
self.asksAnim[i].start()
# ------------------------------------------
for i, v in enumerate(data['bids']):
item_0 = self.tableBids.item(i, 0)
item_0.setText(f"{v['price']:,}")
item_1 = self.tableBids.item(i, 1)
item_1.setText(f"{v['quantity']:,}")
item_2 = self.tableBids.cellWidget(i, 2)
item_2.setRange(0, maxtradingValue)
item_2.setFormat(f"{tradingBidValues[i]:,}")
# item_2.setValue(tradingBidValues[i])
# ----------------- 추 가 ------------------
self.bidsAnim[i].setStartValue(item_2.value() if item_2.value() > 0 else 0)
self.bidsAnim[i].setEndValue(tradingBidValues[i])
self.bidsAnim[i].start()
# ------------------------------------------
def closeEvent(self, event):
self.ow.close()
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ow = OrderbookWidget()
ow.show()
exit(app.exec_())
================================================
FILE: ch10/overview.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from pybithumb import WebSocketManager
class OverViewWorker(QThread):
data24Sent = pyqtSignal(int, float, int, float, int, int)
dataMidSent = pyqtSignal(int, float, float)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
wm = WebSocketManager("ticker", [f"{self.ticker}_KRW"], ["24H", "MID"])
while self.alive:
data = wm.get()
if data['content']['tickType'] == "MID":
self.dataMidSent.emit(int (data['content']['closePrice' ]),
float(data['content']['chgRate' ]),
float(data['content']['volumePower' ]))
else:
self.data24Sent.emit(int (data['content']['closePrice' ]),
float(data['content']['volume' ]),
int (data['content']['highPrice' ]),
float(data['content']['value' ]),
int (data['content']['lowPrice' ]),
int (data['content']['prevClosePrice']))
wm.terminate()
def close(self):
self.alive = False
class OverviewWidget(QWidget):
def __init__(self, parent=None, ticker="BTC", ):
super().__init__(parent)
uic.loadUi("resource/overview.ui", self)
self.ticker = ticker
self.ovw = OverViewWorker(ticker)
self.ovw.data24Sent.connect(self.fill24Data)
self.ovw.dataMidSent.connect(self.fillMidData)
self.ovw.start()
def closeEvent(self, event):
self.ovw.close()
def fill24Data(self, currPrice, volume, highPrice, value, lowPrice, PrevClosePrice):
self.label_1.setText(f"{currPrice:,}")
self.label_4.setText(f"{volume:.4f} {self.ticker}")
self.label_6.setText(f"{highPrice:,}")
self.label_8.setText(f"{value/100000000:,.1f} 억")
self.label_10.setText(f"{lowPrice:,}")
self.label_14.setText(f"{PrevClosePrice:,}")
self.__updateStyle()
def fillMidData(self, currPrice, chgRate, volumePower):
self.label_1.setText(f"{currPrice:,}")
self.label_2.setText(f"{chgRate:+.2f}%")
self.label_12.setText(f"{volumePower:.2f}%")
self.__updateStyle()
def __updateStyle(self):
if '-' in self.label_2.text():
self.label_1.setStyleSheet("color:blue;")
self.label_2.setStyleSheet("background-color:blue;color:white")
else:
self.label_1.setStyleSheet("color:red;")
self.label_2.setStyleSheet("background-color:red;color:white")
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ob = OverviewWidget()
ob.show()
exit(app.exec_())
================================================
FILE: ch10/overview_0.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
class OverviewWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/overview.ui", self)
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ob = OverviewWidget()
ob.show()
exit(app.exec_())
================================================
FILE: ch10/overview_1.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from pybithumb import WebSocketManager
class OverViewWorker(QThread):
dataSent = pyqtSignal(int, float, float, int, float, int, float, int)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
wm = WebSocketManager("ticker", [f"{self.ticker}_KRW"], ["24H"])
while self.alive:
data = wm.get()
self.dataSent.emit(int (data['content']['closePrice' ]),
float(data['content']['chgRate' ]),
float(data['content']['volume' ]),
int (data['content']['highPrice' ]),
float(data['content']['value' ]),
int (data['content']['lowPrice' ]),
float(data['content']['volumePower' ]),
int (data['content']['prevClosePrice']))
class OverviewWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/overview.ui", self)
self.ticker = ticker
self.ovw = OverViewWorker(ticker)
self.ovw.dataSent.connect(self.fillData)
self.ovw.start()
def fillData(self, currPrice, chgRate, volume, highPrice, value, lowPrice, volumePower, PrevClosePrice):
self.label_1.setText(f"{currPrice:,}")
self.label_2.setText(f"{chgRate:+.2f}%")
self.label_4.setText(f"{volume:,.4f} {self.ticker}")
self.label_6.setText(f"{highPrice:,}")
self.label_8.setText(f"{value/100000000:,.1f} 억")
self.label_10.setText(f"{lowPrice:,}")
self.label_12.setText(f"{volumePower:.2f}%")
self.label_14.setText(f"{PrevClosePrice:,}")
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ob = OverviewWidget()
ob.show()
exit(app.exec_())
================================================
FILE: ch10/overview_2.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from pybithumb import WebSocketManager
class OverViewWorker(QThread):
dataSent = pyqtSignal(int, float, float, int, float, int, float, int)
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
wm = WebSocketManager("ticker", [f"{self.ticker}_KRW"], ["24H"])
while self.alive:
data = wm.get()
self.dataSent.emit(int (data['content']['closePrice' ]),
float(data['content']['chgRate' ]),
float(data['content']['volume' ]),
int (data['content']['highPrice' ]),
float(data['content']['value' ]),
int (data['content']['lowPrice' ]),
float(data['content']['volumePower' ]),
int (data['content']['prevClosePrice']))
# ----------------- 추 가 ------------------
wm.terminate()
def close(self):
self.alive = False
# ------------------------------------------
class OverviewWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/overview.ui", self)
self.ticker = ticker
self.ovw = OverViewWorker(ticker)
self.ovw.dataSent.connect(self.fillData)
self.ovw.start()
# ----------------- 추 가 ------------------
def closeEvent(self, event):
self.ovw.close()
# ------------------------------------------
def fillData(self, currPrice, chgRate, volume, highPrice, value, lowPrice, volumePower, PrevClosePrice):
self.label_1.setText(f"{currPrice:,}")
self.label_2.setText(f"{chgRate:+.2f}%")
self.label_4.setText(f"{volume:,.4f} {self.ticker}")
self.label_6.setText(f"{highPrice:,}")
self.label_8.setText(f"{value/100000000:,.1f} 억")
self.label_10.setText(f"{lowPrice:,}")
self.label_12.setText(f"{volumePower:.2f}%")
self.label_14.setText(f"{PrevClosePrice:,}")
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ob = OverviewWidget()
ob.show()
exit(app.exec_())
================================================
FILE: ch10/overview_3.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from pybithumb import WebSocketManager
class OverViewWorker(QThread):
# ----------------- 수 정 ------------------
data24Sent = pyqtSignal(int, float, int, float, int, int)
dataMidSent = pyqtSignal(int, float, float)
# ------------------------------------------
def __init__(self, ticker):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
# ----------------- 수 정 ------------------
wm = WebSocketManager("ticker", [f"{self.ticker}_KRW"], ["24H", "MID"])
while self.alive:
data = wm.get()
if data['content']['tickType'] == "MID":
self.dataMidSent.emit(int (data['content']['closePrice' ]),
float(data['content']['chgRate' ]),
float(data['content']['volumePower' ]))
else:
self.data24Sent.emit(int (data['content']['closePrice' ]),
float(data['content']['volume' ]),
int (data['content']['highPrice' ]),
float(data['content']['value' ]),
int (data['content']['lowPrice' ]),
int (data['content']['prevClosePrice']))
# ------------------------------------------
wm.terminate()
def close(self):
self.alive = False
class OverviewWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/overview.ui", self)
self.ticker = ticker
self.ovw = OverViewWorker(ticker)
# ----------------- 수 정 ------------------
self.ovw.data24Sent.connect(self.fill24Data)
self.ovw.dataMidSent.connect(self.fillMidData)
# ------------------------------------------
self.ovw.start()
def closeEvent(self, event):
self.ovw.close()
# ----------------- 수 정 ------------------
def fill24Data(self, currPrice, volume, highPrice, value, lowPrice, PrevClosePrice):
self.label_1.setText(f"{currPrice:,}")
self.label_4.setText(f"{volume:,.4f} {self.ticker}")
self.label_6.setText(f"{highPrice:,}")
self.label_8.setText(f"{value/100000000:,.1f} 억")
self.label_10.setText(f"{lowPrice:,}")
self.label_14.setText(f"{PrevClosePrice:,}")
def fillMidData(self, currPrice, chgRate, volumePower):
self.label_1.setText(f"{currPrice:,}")
self.label_2.setText(f"{chgRate:+.2f}%")
self.label_12.setText(f"{volumePower:.2f}%")
# ------------------------------------------
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ob = OverviewWidget()
ob.show()
exit(app.exec_())
================================================
FILE: ch10/overview_4.py
================================================
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from pybithumb import WebSocketManager
class OverViewWorker(QThread):
data24Sent = pyqtSignal(int, float, int, float, int, int)
dataMidSent = pyqtSignal(int, float, float)
def __init__(self, ticker="BTC"):
super().__init__()
self.ticker = ticker
self.alive = True
def run(self):
wm = WebSocketManager("ticker", [f"{self.ticker}_KRW"], ["24H", "MID"])
while self.alive:
data = wm.get()
if data['content']['tickType'] == "MID":
self.dataMidSent.emit(int (data['content']['closePrice' ]),
float(data['content']['chgRate' ]),
float(data['content']['volumePower' ]))
else:
self.data24Sent.emit(int (data['content']['closePrice' ]),
float(data['content']['volume' ]),
int (data['content']['highPrice' ]),
float(data['content']['value' ]),
int (data['content']['lowPrice' ]),
int (data['content']['prevClosePrice']))
wm.terminate()
def close(self):
self.alive = False
class OverviewWidget(QWidget):
def __init__(self, parent=None, ticker="BTC"):
super().__init__(parent)
uic.loadUi("resource/overview.ui", self)
self.ticker = ticker
self.ovw = OverViewWorker(ticker)
self.ovw.data24Sent.connect(self.fill24Data)
self.ovw.dataMidSent.connect(self.fillMidData)
self.ovw.start()
def closeEvent(self, event):
self.ovw.close()
def fill24Data(self, currPrice, volume, highPrice, value, lowPrice, PrevClosePrice):
self.label_1.setText(f"{currPrice:,}")
self.label_4.setText(f"{volume:,.4f} {self.ticker}")
self.label_6.setText(f"{highPrice:,}")
self.label_8.setText(f"{value/100000000:,.1f} 억")
self.label_10.setText(f"{lowPrice:,}")
self.label_14.setText(f"{PrevClosePrice:,}")
# ----------------- 추 가 ------------------
self.__updateStyle()
# ------------------------------------------
def fillMidData(self, currPrice, chgRate, volumePower):
self.label_1.setText(f"{currPrice:,}")
self.label_2.setText(f"{chgRate:+.2f}%")
self.label_12.setText(f"{volumePower:.2f}%")
# ----------------- 추 가 ------------------
self.__updateStyle()
# ------------------------------------------
# ----------------- 추 가 ------------------
def __updateStyle(self):
if '-' in self.label_2.text():
self.label_1.setStyleSheet("color:blue;")
self.label_2.setStyleSheet("background-color:blue;color:white")
else:
self.label_1.setStyleSheet("color:red;")
self.label_2.setStyleSheet("background-color:red;color:white")
# ------------------------------------------
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
ob = OverviewWidget()
ob.show()
exit(app.exec_())
================================================
FILE: ch10/resource/chart.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>506</width>
<height>129</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QChartView" name="priceView" native="true"/>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>QChartView</class>
<extends>QWidget</extends>
<header>PyQt5.QtChart</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
================================================
FILE: ch10/resource/main.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>695</width>
<height>545</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="OverviewWidget" name="widget_3" native="true">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>120</height>
</size>
</property>
</widget>
</item>
<item>
<widget class="ChartWidget" name="widget_2" native="true">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>150</height>
</size>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLineEdit" name="apiKey">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="secKey">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="button">
<property name="text">
<string>매매시작</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QTextEdit" name="textEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</item>
<item row="0" column="1">
<widget class="OrderbookWidget" name="widget" native="true"/>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>695</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<customwidgets>
<customwidget>
<class>OrderbookWidget</class>
<extends>QWidget</extends>
<header>orderbook</header>
<container>1</container>
</customwidget>
<customwidget>
<class>OverviewWidget</class>
<extends>QWidget</extends>
<header>overview</header>
<container>1</container>
</customwidget>
<customwidget>
<class>ChartWidget</class>
<extends>QWidget</extends>
<header>chart</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
================================================
FILE: ch10/resource/orderbook.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>638</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>400</width>
<height>0</height>
</size>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>4</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTableWidget" name="tableAsks">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="sizeAdjustPolicy">
<enum>QAbstractScrollArea::AdjustToContents</enum>
</property>
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="tabKeyNavigation">
<bool>false</bool>
</property>
<property name="showDropIndicator" stdset="0">
<bool>false</bool>
</property>
<property name="dragDropOverwriteMode">
<bool>false</bool>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="rowCount">
<number>10</number>
</property>
<property name="columnCount">
<number>3</number>
</property>
<attribute name="horizontalHeaderVisible">
<bool>true</bool>
</attribute>
<attribute name="horizontalHeaderStretchLastSection">
<bool>true</bool>
</attribute>
<attribute name="verticalHeaderVisible">
<bool>false</bool>
</attribute>
<attribute name="verticalHeaderHighlightSections">
<bool>true</bool>
</attribute>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<column>
<property name="text">
<string>가격</string>
</property>
</column>
<column>
<property name="text">
<string>규모</string>
</property>
</column>
<column>
<property name="text">
<string>총액</string>
</property>
</column>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QTableWidget" name="tableBids">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="sizeAdjustPolicy">
<enum>QAbstractScrollArea::AdjustToContents</enum>
</property>
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="tabKeyNavigation">
<bool>false</bool>
</property>
<property name="showDropIndicator" stdset="0">
<bool>false</bool>
</property>
<property name="dragDropOverwriteMode">
<bool>false</bool>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="rowCount">
<number>10</number>
</property>
<property name="columnCount">
<number>3</number>
</property>
<attribute name="horizontalHeaderVisible">
<bool>false</bool>
</attribute>
<attribute name="horizontalHeaderStretchLastSection">
<bool>true</bool>
</attribute>
<attribute name="verticalHeaderVisible">
<bool>false</bool>
</attribute>
<attribute name="verticalHeaderHighlightSections">
<bool>true</bool>
</attribute>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<row/>
<column/>
<column/>
<column/>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
================================================
FILE: ch10/resource/overview.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>442</width>
<height>116</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label_1">
<property name="minimumSize">
<size>
<width>180</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>100</height>
</size>
</property>
<property name="font">
<font>
<family>맑은 고딕</family>
<pointsize>22</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color:red;</string>
</property>
<property name="text">
<string>54,070,000</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="minimumSize">
<size>
<width>70</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>70</width>
<height>30</height>
</size>
</property>
<property name="font">
<font>
<pointsize>10</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">background-color:red;color:white</string>
</property>
<property name="text">
<string>+5.17%</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="label_3">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color:gray</string>
</property>
<property name="text">
<string>거래량(24H)</string>
</property>
</widget>
</item>
<item row="1" column="3">
<widget class="QLabel" name="label_10">
<property name="text">
<string>49,440,000</string>
</property>
</widget>
</item>
<item row="1" column="2">
<widget class="QLabel" name="label_9">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color:gray</string>
</property>
<property name="text">
<string>저가(당일)</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_7">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color:gray</string>
</property>
<property name="text">
<string>거래금액(24H)</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="label_8">
<property name="text">
<string>7,830.4 억</string>
</property>
</widget>
</item>
<item row="0" column="3">
<widget class="QLabel" name="label_6">
<property name="text">
<string>54,298,000</string>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QLabel" name="label_5">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color:gray</string>
</property>
<property name="text">
<string>고가(당일)</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLabel" name="label_4">
<property name="text">
<string>14,963,8166 BTC</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_11">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color:gray</string>
</property>
<property name="text">
<string>체결강도(24H)</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="label_12">
<property name="text">
<string>93.28%</string>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QLabel" name="label_13">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color:gray</string>
</property>
<property name="text">
<string>전일종가</string>
</property>
</widget>
</item>
<item row="2" column="3">
<widget class="QLabel" name="label_14">
<property name="text">
<string>51,403,000</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
================================================
FILE: ch10/volatility.py
================================================
import time
import pybithumb
def get_target_price(ticker):
df = pybithumb.get_ohlcv(ticker)
yesterday = df.iloc[-2]
today_open = yesterday['close']
yesterday_high = yesterday['high']
yesterday_low = yesterday['low']
target = today_open + (yesterday_high - yesterday_low) * 0.5
return target
def buy_crypto_currency(bithumb, ticker):
krw = bithumb.get_balance(ticker)[2]
orderbook = pybithumb.get_orderbook(ticker)
sell_price = orderbook['asks'][0]['price']
unit = krw/float(sell_price) * 0.7
return bithumb.buy_market_order(ticker, unit)
def sell_crypto_currency(bithumb, ticker):
unit = bithumb.get_balance(ticker)[0]
return bithumb.sell_market_order(ticker, unit)
def get_yesterday_ma5(ticker):
df = pybithumb.get_ohlcv(ticker)
close = df['close']
ma = close.rolling(5).mean()
return ma[-2]
gitextract__f95lk4z/
├── LICENSE
├── README.md
├── ch03/
│ ├── 03_01.py
│ ├── 03_02.py
│ ├── 03_03.py
│ ├── 03_04.py
│ ├── 03_05.py
│ ├── 03_06.py
│ ├── 03_07.py
│ ├── 03_08.py
│ ├── 03_09.py
│ ├── 03_10.py
│ ├── 03_11.py
│ ├── 03_12.py
│ ├── 03_13.py
│ ├── 03_14.py
│ ├── 03_15.py
│ ├── 03_16.py
│ ├── 03_17.py
│ ├── 03_18.py
│ ├── 03_19.py
│ ├── 03_20.py
│ ├── 03_21.py
│ ├── 03_22.py
│ ├── 03_23.py
│ ├── 03_24.py
│ ├── 03_25.py
│ ├── 03_26.py
│ ├── 03_27.py
│ ├── 03_28.py
│ ├── mywindow.ui
│ └── window.ui
├── ch04/
│ ├── 04_01.py
│ ├── 04_02.py
│ ├── 04_03.py
│ ├── 04_04.py
│ ├── 04_05.py
│ ├── 04_06.py
│ ├── 04_07.py
│ ├── 04_08.py
│ ├── 04_09.py
│ ├── 04_10.py
│ ├── 04_11.py
│ ├── 04_12.py
│ ├── 04_13.py
│ ├── 04_14.py
│ ├── 04_15.py
│ ├── 04_16.py
│ ├── 04_17.py
│ ├── 04_18.py
│ ├── 04_19.py
│ ├── 04_20.py
│ ├── 04_21.py
│ ├── 04_22.py
│ ├── 04_23.py
│ ├── 04_24.py
│ ├── 04_25.py
│ └── ohlc.xlsx
├── ch05/
│ ├── 05_01.py
│ ├── 05_02.py
│ ├── 05_03.py
│ ├── 05_04.py
│ ├── 05_05.py
│ ├── 05_06.py
│ ├── 05_07.py
│ ├── 05_08.py
│ ├── 05_09.py
│ ├── 05_10.py
│ ├── 05_11.py
│ ├── 05_12.py
│ ├── 05_13.py
│ ├── 05_14.py
│ ├── 05_15.py
│ ├── 05_16.py
│ ├── 05_17.py
│ ├── 05_18.py
│ ├── 05_19.py
│ ├── 05_20.py
│ ├── 05_21.py
│ ├── 05_22.py
│ ├── 05_23.py
│ ├── 05_24.py
│ ├── 05_25.py
│ ├── 05_26.py
│ ├── 05_27.py
│ ├── 05_ex_01.py
│ └── bull.ui
├── ch06/
│ ├── 06_01.py
│ ├── 06_02.py
│ ├── 06_03.py
│ ├── 06_04.py
│ ├── 06_05.py
│ ├── 06_06.py
│ ├── 06_07.py
│ ├── 06_08.py
│ ├── 06_09.py
│ ├── 06_10.py
│ ├── 06_11.py
│ ├── 06_12.py
│ ├── 06_13.py
│ ├── 06_14.py
│ ├── 06_15.py
│ ├── 06_16.py
│ ├── 06_17.py
│ ├── 06_18.py
│ ├── 06_19.py
│ └── 06_20.py
├── ch07/
│ ├── 07_01.py
│ ├── 07_02.py
│ ├── 07_03.py
│ ├── 07_04.py
│ ├── 07_05.py
│ ├── 07_06.py
│ ├── 07_07.py
│ ├── 07_08.py
│ ├── 07_09.py
│ ├── 07_10.py
│ ├── 07_11.py
│ ├── 07_12.py
│ ├── 07_13.py
│ ├── 07_14.py
│ ├── 07_15.py
│ ├── btc.xlsx
│ └── run.py
├── ch08/
│ ├── 08_01.py
│ ├── 08_02.py
│ ├── 08_03.py
│ ├── 08_04.py
│ ├── 08_05.py
│ ├── 08_06.py
│ ├── 08_07.py
│ ├── 08_08.py
│ ├── 08_09.py
│ ├── 08_10.py
│ ├── 08_11.py
│ ├── 08_12.py
│ ├── 08_13.py
│ ├── 08_14.py
│ ├── 08_15.py
│ ├── 08_16.py
│ ├── 08_17.py
│ ├── 08_18.py
│ ├── 08_19.py
│ ├── 08_20.py
│ ├── 08_21.py
│ ├── 08_22.py
│ ├── 08_23.py
│ ├── 08_24.py
│ ├── 08_25.py
│ └── 08_26.py
├── ch09/
│ ├── 09_01.py
│ ├── 09_02.py
│ ├── 09_03.py
│ ├── 09_04.py
│ ├── 09_05.py
│ ├── 09_06.py
│ ├── 09_07.py
│ ├── 09_08.py
│ ├── 09_09.py
│ ├── 09_10.py
│ ├── 09_11.py
│ ├── 09_12.py
│ ├── 09_13.py
│ ├── 09_14.py
│ ├── 09_15.py
│ ├── 09_16.py
│ └── 09_17.py
└── ch10/
├── chart.py
├── chart_0.py
├── chart_1.py
├── chart_2.py
├── chart_3.py
├── chart_4.py
├── chart_5.py
├── main.py
├── main_0.py
├── main_1.py
├── main_2.py
├── main_3.py
├── main_4.py
├── main_5.py
├── main_6.py
├── orderbook.py
├── orderbook_0.py
├── orderbook_1.py
├── orderbook_2.py
├── orderbook_3.py
├── orderbook_4.py
├── overview.py
├── overview_0.py
├── overview_1.py
├── overview_2.py
├── overview_3.py
├── overview_4.py
├── resource/
│ ├── chart.ui
│ ├── main.ui
│ ├── orderbook.ui
│ └── overview.ui
└── volatility.py
SYMBOL INDEX (334 symbols across 88 files)
FILE: ch03/03_01.py
function forward (line 3) | def forward(pos):
FILE: ch03/03_02.py
class SuperMario (line 1) | class SuperMario:
method __init__ (line 2) | def __init__(self):
method forward (line 4) | def forward(self):
FILE: ch03/03_03.py
function forward (line 4) | def forward(pos):
FILE: ch03/03_04.py
class SuperMario (line 1) | class SuperMario:
method __init__ (line 2) | def __init__(self):
method forward (line 4) | def forward(self):
FILE: ch03/03_05.py
class MyClass (line 1) | class MyClass:
method method (line 2) | def method(self):
FILE: ch03/03_06.py
class MyClass (line 1) | class MyClass:
method add (line 2) | def add(self, a, b):
FILE: ch03/03_07.py
class Customer (line 1) | class Customer:
method __init__ (line 2) | def __init__(self, id, name):
FILE: ch03/03_08.py
class Parent (line 1) | class Parent:
method sing (line 2) | def sing(self):
FILE: ch03/03_09.py
class Parent (line 1) | class Parent:
method sing (line 2) | def sing(self):
class LuckyChild (line 5) | class LuckyChild(Parent):
FILE: ch03/03_10.py
class Parent (line 1) | class Parent:
method sing (line 2) | def sing(self):
class LuckyChild (line 5) | class LuckyChild(Parent):
method dance (line 6) | def dance(self):
FILE: ch03/03_11.py
class Car (line 1) | class Car:
method __init__ (line 2) | def __init__(self, model, year):
FILE: ch03/03_14.py
class MyWindow (line 4) | class MyWindow(QMainWindow):
method __init__ (line 5) | def __init__(self):
FILE: ch03/03_15.py
class MyWindow (line 5) | class MyWindow(QMainWindow):
method __init__ (line 6) | def __init__(self):
FILE: ch03/03_16.py
class MyWindow (line 6) | class MyWindow(QMainWindow):
method __init__ (line 7) | def __init__(self):
FILE: ch03/03_17.py
class MyWindow (line 6) | class MyWindow(QMainWindow):
method __init__ (line 7) | def __init__(self):
FILE: ch03/03_18.py
class MyWindow (line 6) | class MyWindow(QMainWindow):
method __init__ (line 7) | def __init__(self):
FILE: ch03/03_19.py
class MyWindow (line 6) | class MyWindow(QMainWindow):
method __init__ (line 7) | def __init__(self):
method btn_clicked (line 17) | def btn_clicked(self):
FILE: ch03/03_20.py
class MyWindow (line 8) | class MyWindow(QMainWindow, form_class):
method __init__ (line 9) | def __init__(self):
FILE: ch03/03_21.py
class MyWindow (line 8) | class MyWindow(QMainWindow, form_class):
method __init__ (line 9) | def __init__(self):
method btn_clicked (line 14) | def btn_clicked(self):
FILE: ch03/03_22.py
class MyWindow (line 8) | class MyWindow(QMainWindow, form_class):
method __init__ (line 9) | def __init__(self):
method inquiry (line 14) | def inquiry(self):
FILE: ch03/03_23.py
class MyWindow (line 8) | class MyWindow(QMainWindow, form_class):
method __init__ (line 9) | def __init__(self):
method inquiry (line 14) | def inquiry(self):
FILE: ch03/03_24.py
class MyWindow (line 8) | class MyWindow(QMainWindow, form_class):
method __init__ (line 9) | def __init__(self):
method inquiry (line 14) | def inquiry(self):
FILE: ch03/03_25.py
class MyWindow (line 6) | class MyWindow(QMainWindow):
method __init__ (line 7) | def __init__(self):
method timeout (line 13) | def timeout(self):
FILE: ch03/03_26.py
class MyWindow (line 9) | class MyWindow(QMainWindow, form_class):
method __init__ (line 10) | def __init__(self):
method inquiry (line 18) | def inquiry(self):
FILE: ch03/03_27.py
class MySignal (line 6) | class MySignal(QObject):
method run (line 9) | def run(self):
class MyWindow (line 13) | class MyWindow(QMainWindow):
method __init__ (line 14) | def __init__(self):
method signal1_emitted (line 22) | def signal1_emitted(self):
FILE: ch03/03_28.py
class MySignal (line 6) | class MySignal(QObject):
method run (line 10) | def run(self):
class MyWindow (line 15) | class MyWindow(QMainWindow):
method __init__ (line 16) | def __init__(self):
method signal1_emitted (line 25) | def signal1_emitted(self):
method signal2_emitted (line 29) | def signal2_emitted(self, arg1, arg2):
FILE: ch04/04_04.py
function get_per (line 4) | def get_per(code):
function get_dividend (line 13) | def get_dividend(code):
FILE: ch05/05_18.py
function bull_market (line 3) | def bull_market(ticker):
FILE: ch05/05_19.py
function bull_market (line 3) | def bull_market(ticker):
FILE: ch05/05_20.py
class MyWindow (line 7) | class MyWindow(QMainWindow, form_class):
method __init__ (line 8) | def __init__(self):
FILE: ch05/05_21.py
class MyWindow (line 8) | class MyWindow(QMainWindow, form_class):
method __init__ (line 9) | def __init__(self):
method timeout (line 17) | def timeout(self):
FILE: ch05/05_22.py
class MyWindow (line 9) | class MyWindow(QMainWindow, form_class):
method __init__ (line 10) | def __init__(self):
method timeout (line 18) | def timeout(self):
FILE: ch05/05_23.py
class MyWindow (line 10) | class MyWindow(QMainWindow, form_class):
method __init__ (line 11) | def __init__(self):
method get_market_infos (line 19) | def get_market_infos(self, ticker):
method timeout (line 33) | def timeout(self):
FILE: ch05/05_24.py
class Worker (line 3) | class Worker(QThread):
method run (line 4) | def run(self):
FILE: ch05/05_25.py
class Worker (line 5) | class Worker(QThread):
method run (line 6) | def run(self):
class MyWindow (line 11) | class MyWindow(QMainWindow):
method __init__ (line 12) | def __init__(self):
FILE: ch05/05_26.py
class Worker (line 11) | class Worker(QThread):
method run (line 12) | def run(self):
method get_market_infos (line 22) | def get_market_infos(self, ticker):
class MyWindow (line 39) | class MyWindow(QMainWindow, form_class):
method __init__ (line 40) | def __init__(self):
FILE: ch05/05_27.py
class Worker (line 11) | class Worker(QThread):
method run (line 14) | def run(self):
method get_market_infos (line 24) | def get_market_infos(self, ticker):
class MyWindow (line 41) | class MyWindow(QMainWindow, form_class):
method __init__ (line 42) | def __init__(self):
method update_table_widget (line 51) | def update_table_widget(self, data):
FILE: ch06/06_16.py
function get_target_price (line 5) | def get_target_price(ticker):
FILE: ch06/06_17.py
function get_target_price (line 9) | def get_target_price(ticker):
FILE: ch06/06_18.py
function get_target_price (line 9) | def get_target_price(ticker):
function buy_crypto_currency (line 19) | def buy_crypto_currency(ticker):
function sell_crypto_currency (line 26) | def sell_crypto_currency(ticker):
FILE: ch06/06_19.py
function get_target_price (line 11) | def get_target_price(ticker):
function buy_crypto_currency (line 21) | def buy_crypto_currency(ticker):
function sell_crypto_currency (line 28) | def sell_crypto_currency(ticker):
FILE: ch06/06_20.py
function get_target_price (line 11) | def get_target_price(ticker):
function buy_crypto_currency (line 21) | def buy_crypto_currency(ticker):
function sell_crypto_currency (line 28) | def sell_crypto_currency(ticker):
function get_yesterday_ma5 (line 32) | def get_yesterday_ma5(ticker):
FILE: ch07/07_11.py
function get_ror (line 5) | def get_ror(k=0.5):
FILE: ch07/07_15.py
function get_hpr (line 5) | def get_hpr(ticker):
FILE: ch09/09_01.py
function sync_func1 (line 1) | def sync_func1():
function sync_func2 (line 4) | def sync_func2():
FILE: ch09/09_02.py
function async_func1 (line 3) | async def async_func1():
FILE: ch09/09_03.py
function async_func1 (line 3) | async def async_func1():
FILE: ch09/09_04.py
function make_americano (line 3) | async def make_americano():
function make_latte (line 8) | async def make_latte():
function main (line 13) | async def main():
FILE: ch09/09_05.py
function make_americano (line 3) | async def make_americano():
function make_latte (line 9) | async def make_latte():
function main (line 15) | async def main():
FILE: ch09/09_07.py
function worker (line 4) | def worker():
FILE: ch09/09_08.py
function bithumb_ws_client (line 4) | async def bithumb_ws_client():
function main (line 11) | async def main():
FILE: ch09/09_09.py
function bithumb_ws_client (line 5) | async def bithumb_ws_client():
function main (line 26) | async def main():
FILE: ch09/09_10.py
function bithumb_ws_client (line 11) | async def bithumb_ws_client(q):
function main (line 28) | async def main(q):
function producer (line 31) | def producer(q):
class Consumer (line 34) | class Consumer(QThread):
method __init__ (line 37) | def __init__(self, q):
method run (line 41) | def run(self):
class MyWindow (line 48) | class MyWindow(QMainWindow):
method __init__ (line 49) | def __init__(self, q):
method print_data (line 69) | def print_data(self, data):
FILE: ch09/09_11.py
class Worker (line 9) | class Worker(QThread):
method run (line 11) | def run(self):
class MyWindow (line 19) | class MyWindow(QMainWindow):
method __init__ (line 20) | def __init__(self):
method receive_msg (line 38) | def receive_msg(self, msg):
method click_btn (line 42) | def click_btn(self):
FILE: ch09/09_12.py
function korbit_ws_client (line 5) | async def korbit_ws_client():
function main (line 12) | async def main():
FILE: ch09/09_13.py
function korbit_ws_client (line 8) | async def korbit_ws_client():
function main (line 32) | async def main():
FILE: ch09/09_14.py
function korbit_ws_client (line 11) | async def korbit_ws_client(q):
function main (line 34) | async def main(q):
function producer (line 37) | def producer(q):
class Consumer (line 43) | class Consumer(QThread):
method __init__ (line 46) | def __init__(self, q):
method run (line 50) | def run(self):
class MyWindow (line 61) | class MyWindow(QMainWindow):
method __init__ (line 62) | def __init__(self, q):
method print_data (line 86) | def print_data(self, data):
FILE: ch09/09_15.py
function upbit_ws_client (line 5) | async def upbit_ws_client():
function main (line 27) | async def main():
FILE: ch09/09_16.py
function upbit_ws_client (line 10) | async def upbit_ws_client(q):
function main (line 31) | async def main(q):
function producer (line 34) | def producer(q):
class Consumer (line 37) | class Consumer(QThread):
method __init__ (line 40) | def __init__(self, q):
method run (line 44) | def run(self):
class MyWindow (line 51) | class MyWindow(QMainWindow):
method __init__ (line 52) | def __init__(self, q):
method print_data (line 72) | def print_data(self, data):
FILE: ch09/09_17.py
class Worker (line 7) | class Worker(QThread):
method run (line 10) | def run(self):
class MyWindow (line 19) | class MyWindow(QMainWindow):
method __init__ (line 20) | def __init__(self):
method receive_msg (line 38) | def receive_msg(self, data):
method click_btn (line 43) | def click_btn(self):
FILE: ch10/chart.py
class PriceWorker (line 11) | class PriceWorker(QThread):
method __init__ (line 14) | def __init__(self, ticker):
method run (line 19) | def run(self):
method close (line 26) | def close(self):
class ChartWidget (line 29) | class ChartWidget(QWidget):
method __init__ (line 30) | def __init__(self, parent=None, ticker="BTC"):
method appendData (line 62) | def appendData(self, currPirce):
method __updateAxis (line 69) | def __updateAxis(self):
FILE: ch10/chart_0.py
class ChartWidget (line 5) | class ChartWidget(QWidget):
method __init__ (line 6) | def __init__(self, parent=None, ticker="BTC"):
FILE: ch10/chart_1.py
class ChartWidget (line 8) | class ChartWidget(QWidget):
method __init__ (line 9) | def __init__(self, parent=None, ticker="BTC"):
FILE: ch10/chart_2.py
class ChartWidget (line 9) | class ChartWidget(QWidget):
method __init__ (line 10) | def __init__(self, parent=None, ticker="BTC"):
FILE: ch10/chart_3.py
class ChartWidget (line 10) | class ChartWidget(QWidget):
method __init__ (line 11) | def __init__(self, parent=None, ticker="BTC"):
FILE: ch10/chart_4.py
class ChartWidget (line 8) | class ChartWidget(QWidget):
method __init__ (line 9) | def __init__(self, parent=None, ticker="BTC"):
method appendData (line 38) | def appendData(self, currPirce):
method __updateAxis (line 45) | def __updateAxis(self):
FILE: ch10/chart_5.py
class PriceWorker (line 12) | class PriceWorker(QThread):
method __init__ (line 15) | def __init__(self, ticker):
method run (line 20) | def run(self):
method close (line 26) | def close(self):
class ChartWidget (line 30) | class ChartWidget(QWidget):
method __init__ (line 31) | def __init__(self, parent=None, ticker="BTC"):
method appendData (line 65) | def appendData(self, currPirce):
method __updateAxis (line 72) | def __updateAxis(self):
FILE: ch10/main.py
class VolatilityWorker (line 10) | class VolatilityWorker(QThread):
method __init__ (line 13) | def __init__(self, ticker, bithumb):
method run (line 19) | def run(self):
method close (line 56) | def close(self):
class MainWindow (line 61) | class MainWindow(QMainWindow, form_class):
method __init__ (line 62) | def __init__(self):
method clickBtn (line 76) | def clickBtn(self):
method receiveTradingSignal (line 102) | def receiveTradingSignal(self, time, type, amount):
method closeEvent (line 105) | def closeEvent(self, event):
FILE: ch10/main_0.py
class MainWindow (line 7) | class MainWindow(QMainWindow, form_class):
method __init__ (line 8) | def __init__(self):
FILE: ch10/main_1.py
class MainWindow (line 7) | class MainWindow(QMainWindow, form_class):
method __init__ (line 8) | def __init__(self):
method clickBtn (line 17) | def clickBtn(self):
FILE: ch10/main_2.py
class MainWindow (line 10) | class MainWindow(QMainWindow, form_class):
method __init__ (line 11) | def __init__(self):
method clickBtn (line 18) | def clickBtn(self):
FILE: ch10/main_3.py
class MainWindow (line 10) | class MainWindow(QMainWindow, form_class):
method __init__ (line 11) | def __init__(self):
method clickBtn (line 27) | def clickBtn(self):
FILE: ch10/main_4.py
class VolatilityWorker (line 11) | class VolatilityWorker(QThread):
method __init__ (line 14) | def __init__(self, ticker, bithumb):
method run (line 20) | def run(self):
method close (line 25) | def close(self):
class MainWindow (line 31) | class MainWindow(QMainWindow, form_class):
method __init__ (line 32) | def __init__(self):
method clickBtn (line 46) | def clickBtn(self):
method receiveTradingSignal (line 74) | def receiveTradingSignal(self, time, type, amount):
FILE: ch10/main_5.py
class VolatilityWorker (line 10) | class VolatilityWorker(QThread):
method __init__ (line 13) | def __init__(self, ticker, bithumb):
method run (line 20) | def run(self):
method close (line 58) | def close(self):
class MainWindow (line 63) | class MainWindow(QMainWindow, form_class):
method __init__ (line 64) | def __init__(self):
method clickBtn (line 78) | def clickBtn(self):
method receiveTradingSignal (line 104) | def receiveTradingSignal(self, time, type, amount):
FILE: ch10/main_6.py
class VolatilityWorker (line 10) | class VolatilityWorker(QThread):
method __init__ (line 13) | def __init__(self, ticker, bithumb):
method run (line 19) | def run(self):
method close (line 56) | def close(self):
class MainWindow (line 61) | class MainWindow(QMainWindow, form_class):
method __init__ (line 62) | def __init__(self):
method clickBtn (line 76) | def clickBtn(self):
method receiveTradingSignal (line 102) | def receiveTradingSignal(self, time, type, amount):
method closeEvent (line 106) | def closeEvent(self, event):
FILE: ch10/orderbook.py
class OrderbookWorker (line 9) | class OrderbookWorker(QThread):
method __init__ (line 12) | def __init__(self, ticker):
method run (line 17) | def run(self):
method close (line 24) | def close(self):
class OrderbookWidget (line 28) | class OrderbookWidget(QWidget):
method __init__ (line 29) | def __init__(self, parent=None, ticker="BTC"):
method updateData (line 83) | def updateData(self, data):
method closeEvent (line 117) | def closeEvent(self, event):
FILE: ch10/orderbook_0.py
class OrderbookWidget (line 5) | class OrderbookWidget(QWidget):
method __init__ (line 6) | def __init__(self, ticker="BTC"):
FILE: ch10/orderbook_1.py
class OrderbookWidget (line 9) | class OrderbookWidget(QWidget):
method __init__ (line 10) | def __init__(self, ticker="BTC"):
FILE: ch10/orderbook_2.py
class OrderbookWorker (line 10) | class OrderbookWorker(QThread):
method __init__ (line 13) | def __init__(self, ticker):
method run (line 18) | def run(self):
method close (line 24) | def close(self):
class OrderbookWidget (line 29) | class OrderbookWidget(QWidget):
method __init__ (line 30) | def __init__(self, ticker="BTC"):
method updateData (line 75) | def updateData(self, data):
method closeEvent (line 78) | def closeEvent(self, event):
FILE: ch10/orderbook_3.py
class OrderbookWorker (line 10) | class OrderbookWorker(QThread):
method __init__ (line 13) | def __init__(self, ticker):
method run (line 18) | def run(self):
method close (line 24) | def close(self):
class OrderbookWidget (line 28) | class OrderbookWidget(QWidget):
method __init__ (line 29) | def __init__(self, ticker="BTC"):
method updateData (line 73) | def updateData(self, data):
method closeEvent (line 104) | def closeEvent(self, event):
FILE: ch10/orderbook_4.py
class OrderbookWorker (line 11) | class OrderbookWorker(QThread):
method __init__ (line 14) | def __init__(self, ticker):
method run (line 19) | def run(self):
method close (line 25) | def close(self):
class OrderbookWidget (line 29) | class OrderbookWidget(QWidget):
method __init__ (line 30) | def __init__(self, ticker="BTC"):
method updateData (line 89) | def updateData(self, data):
method closeEvent (line 128) | def closeEvent(self, event):
FILE: ch10/overview.py
class OverViewWorker (line 7) | class OverViewWorker(QThread):
method __init__ (line 11) | def __init__(self, ticker):
method run (line 16) | def run(self):
method close (line 35) | def close(self):
class OverviewWidget (line 39) | class OverviewWidget(QWidget):
method __init__ (line 40) | def __init__(self, parent=None, ticker="BTC", ):
method closeEvent (line 50) | def closeEvent(self, event):
method fill24Data (line 53) | def fill24Data(self, currPrice, volume, highPrice, value, lowPrice, Pr...
method fillMidData (line 62) | def fillMidData(self, currPrice, chgRate, volumePower):
method __updateStyle (line 68) | def __updateStyle(self):
FILE: ch10/overview_0.py
class OverviewWidget (line 5) | class OverviewWidget(QWidget):
method __init__ (line 6) | def __init__(self, parent=None, ticker="BTC"):
FILE: ch10/overview_1.py
class OverViewWorker (line 7) | class OverViewWorker(QThread):
method __init__ (line 10) | def __init__(self, ticker):
method run (line 15) | def run(self):
class OverviewWidget (line 29) | class OverviewWidget(QWidget):
method __init__ (line 30) | def __init__(self, parent=None, ticker="BTC"):
method fillData (line 39) | def fillData(self, currPrice, chgRate, volume, highPrice, value, lowPr...
FILE: ch10/overview_2.py
class OverViewWorker (line 7) | class OverViewWorker(QThread):
method __init__ (line 10) | def __init__(self, ticker):
method run (line 15) | def run(self):
method close (line 30) | def close(self):
class OverviewWidget (line 35) | class OverviewWidget(QWidget):
method __init__ (line 36) | def __init__(self, parent=None, ticker="BTC"):
method closeEvent (line 46) | def closeEvent(self, event):
method fillData (line 50) | def fillData(self, currPrice, chgRate, volume, highPrice, value, lowPr...
FILE: ch10/overview_3.py
class OverViewWorker (line 7) | class OverViewWorker(QThread):
method __init__ (line 13) | def __init__(self, ticker):
method run (line 18) | def run(self):
method close (line 39) | def close(self):
class OverviewWidget (line 43) | class OverviewWidget(QWidget):
method __init__ (line 44) | def __init__(self, parent=None, ticker="BTC"):
method closeEvent (line 56) | def closeEvent(self, event):
method fill24Data (line 60) | def fill24Data(self, currPrice, volume, highPrice, value, lowPrice, Pr...
method fillMidData (line 68) | def fillMidData(self, currPrice, chgRate, volumePower):
FILE: ch10/overview_4.py
class OverViewWorker (line 7) | class OverViewWorker(QThread):
method __init__ (line 11) | def __init__(self, ticker="BTC"):
method run (line 16) | def run(self):
method close (line 35) | def close(self):
class OverviewWidget (line 39) | class OverviewWidget(QWidget):
method __init__ (line 40) | def __init__(self, parent=None, ticker="BTC"):
method closeEvent (line 50) | def closeEvent(self, event):
method fill24Data (line 53) | def fill24Data(self, currPrice, volume, highPrice, value, lowPrice, Pr...
method fillMidData (line 64) | def fillMidData(self, currPrice, chgRate, volumePower):
method __updateStyle (line 73) | def __updateStyle(self):
FILE: ch10/volatility.py
function get_target_price (line 4) | def get_target_price(ticker):
function buy_crypto_currency (line 14) | def buy_crypto_currency(bithumb, ticker):
function sell_crypto_currency (line 21) | def sell_crypto_currency(bithumb, ticker):
function get_yesterday_ma5 (line 25) | def get_yesterday_ma5(ticker):
Condensed preview — 199 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (174K chars).
[
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 103,
"preview": "# 파이썬을 이용한 비트코인 자동매매\n\n<div>\n\n<img src=\"http://image.yes24.com/goods/69773561/800x0\" width=300>\n\n</div>\n"
},
{
"path": "ch03/03_01.py",
"chars": 78,
"preview": "pos = 0\n\ndef forward(pos):\n return pos + 20\n\npos = forward(pos)\nprint(pos)\n"
},
{
"path": "ch03/03_02.py",
"chars": 174,
"preview": "class SuperMario:\n def __init__(self):\n self.pos = 0\n def forward(self):\n self.pos = self.pos + 20\n\n"
},
{
"path": "ch03/03_03.py",
"chars": 111,
"preview": "p1_pos = 0\np2_pos = 0\n\ndef forward(pos):\n return pos + 20\n\np1_pos = forward(p1_pos)\np2_pos = forward(p2_pos)"
},
{
"path": "ch03/03_04.py",
"chars": 206,
"preview": "class SuperMario:\n def __init__(self):\n self.pos = 0\n def forward(self):\n self.pos = self.pos + 20\n\n"
},
{
"path": "ch03/03_05.py",
"chars": 91,
"preview": "class MyClass:\n def method(self):\n print(\"method\")\n\nobj = MyClass()\nobj.method()\n"
},
{
"path": "ch03/03_06.py",
"chars": 109,
"preview": "class MyClass:\n def add(self, a, b):\n return a + b\n\nobj = MyClass()\nret = obj.add(3, 4)\nprint(ret)\n"
},
{
"path": "ch03/03_07.py",
"chars": 96,
"preview": "class Customer:\n def __init__(self, id, name):\n self.id = id\n self.name = name\n"
},
{
"path": "ch03/03_08.py",
"chars": 95,
"preview": "class Parent:\n def sing(self):\n print(\"sing a song\")\nfather = Parent()\nfather.sing()\n"
},
{
"path": "ch03/03_09.py",
"chars": 140,
"preview": "class Parent:\n def sing(self):\n print(\"sing a song\")\n\nclass LuckyChild(Parent):\n pass\n\t\nluckyboy = LuckyChi"
},
{
"path": "ch03/03_10.py",
"chars": 199,
"preview": "class Parent:\n def sing(self):\n print(\"sing a song\")\n\nclass LuckyChild(Parent):\n def dance(self):\n p"
},
{
"path": "ch03/03_11.py",
"chars": 213,
"preview": "class Car:\n def __init__(self, model, year):\n self.model = model\n self.year = year\n\nsonata = Car(\"SONAT"
},
{
"path": "ch03/03_12.py",
"chars": 120,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\n\napp = QApplication(sys.argv)\nlabel = QLabel(\"Hello\")\nlabel.show()\napp.exec_()\n"
},
{
"path": "ch03/03_13.py",
"chars": 176,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\n\napp = QApplication(sys.argv) \n\nbtn = QPushButton(\"Hello\") # 버튼 객체 생"
},
{
"path": "ch03/03_14.py",
"chars": 199,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\n\nclass MyWindow(QMainWindow):\n def __init__(self):\n super().__init__("
},
{
"path": "ch03/03_15.py",
"chars": 245,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\n\n\nclass MyWindow(QMainWindow):\n def __init__(self):\n super().__init__"
},
{
"path": "ch03/03_16.py",
"chars": 351,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\n\nclass MyWindow(QMainWindow):\n def __init__(self)"
},
{
"path": "ch03/03_17.py",
"chars": 393,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\n\nclass MyWindow(QMainWindow):\n def __init__(self)"
},
{
"path": "ch03/03_18.py",
"chars": 484,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\n\nclass MyWindow(QMainWindow):\n def __init__(self)"
},
{
"path": "ch03/03_19.py",
"chars": 514,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\n\nclass MyWindow(QMainWindow):\n def __init__(self)"
},
{
"path": "ch03/03_20.py",
"chars": 313,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\n \nform_class = uic.loadUiType(\"mywindow.ui\")[0]\n \n \nclass"
},
{
"path": "ch03/03_21.py",
"chars": 418,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\n\nform_class = uic.loadUiType(\"mywindow.ui\")[0]\n \n \nclass "
},
{
"path": "ch03/03_22.py",
"chars": 413,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\n\nform_class = uic.loadUiType(\"mywindow.ui\")[0]\n \n \nclass "
},
{
"path": "ch03/03_23.py",
"chars": 471,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nimport pykorbit\n \nform_class = uic.loadUiType(\"window.ui\""
},
{
"path": "ch03/03_24.py",
"chars": 496,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nimport pykorbit\n \nform_class = uic.loadUiType(\"window.ui\""
},
{
"path": "ch03/03_25.py",
"chars": 504,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n \n \nclass MyWindow(QMainWindow):\n def __init__(se"
},
{
"path": "ch03/03_26.py",
"chars": 718,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\nimport pykorbit\n \nform_class ="
},
{
"path": "ch03/03_27.py",
"chars": 518,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n\n\nclass MySignal(QObject):\n signal1 = pyqtSignal("
},
{
"path": "ch03/03_28.py",
"chars": 753,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n\n\nclass MySignal(QObject):\n signal1 = pyqtSignal("
},
{
"path": "ch03/mywindow.ui",
"chars": 988,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>MainWindow</class>\n <widget class=\"QMainWindow\" name=\""
},
{
"path": "ch03/window.ui",
"chars": 1486,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>MainWindow</class>\n <widget class=\"QMainWindow\" name=\""
},
{
"path": "ch04/04_01.py",
"chars": 120,
"preview": "import requests\n \nurl = \"https://finance.naver.com/item/main.nhn?code=000660\"\nhtml = requests.get(url).text\nprint(html)\n"
},
{
"path": "ch04/04_02.py",
"chars": 236,
"preview": "import requests\nfrom bs4 import BeautifulSoup\n \nurl = \"http://finance.naver.com/item/main.nhn?code=000660\"\nhtml = reques"
},
{
"path": "ch04/04_03.py",
"chars": 236,
"preview": "import requests\nfrom bs4 import BeautifulSoup\n \nurl = \"http://finance.naver.com/item/main.nhn?code=000660\"\nhtml = reques"
},
{
"path": "ch04/04_04.py",
"chars": 583,
"preview": "import requests\nfrom bs4 import BeautifulSoup\n \ndef get_per(code):\n\turl = \"http://finance.naver.com/item/main.nhn?code=\""
},
{
"path": "ch04/04_05.py",
"chars": 258,
"preview": "import requests\nfrom bs4 import BeautifulSoup\n\nurl = \"http://finance.naver.com/item/main.nhn?code=000660\"\nhtml = request"
},
{
"path": "ch04/04_06.py",
"chars": 265,
"preview": "import requests\nfrom bs4 import BeautifulSoup\n\nurl = \"http://finance.naver.com/item/main.nhn?code=000660\"\nhtml = request"
},
{
"path": "ch04/04_07.py",
"chars": 306,
"preview": "import requests\nfrom bs4 import BeautifulSoup\n\nurl = \"http://finance.naver.com/item/main.nhn?code=000660\"\nhtml = request"
},
{
"path": "ch04/04_08.py",
"chars": 160,
"preview": "import requests \nr = requests.get(\"https://api.korbit.co.kr/v1/ticker/detailed?currency_pair=btc_krw\")\nbitcoin = r.json("
},
{
"path": "ch04/04_09.py",
"chars": 245,
"preview": "import requests \nimport datetime \n \nr = requests.get(\"https://api.korbit.co.kr/v1/ticker/detailed?currency_pair=btc_krw\""
},
{
"path": "ch04/04_10.py",
"chars": 189,
"preview": "from pandas import Series \ndate = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05'] \nxrp_close = [5"
},
{
"path": "ch04/04_11.py",
"chars": 215,
"preview": "from pandas import Series \n\ndate = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05'] \nxrp_close = ["
},
{
"path": "ch04/04_12.py",
"chars": 252,
"preview": "from pandas import Series \n\ndate = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05'] \nxrp_close = ["
},
{
"path": "ch04/04_13.py",
"chars": 219,
"preview": "from pandas import Series \n\ndate = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05'] \nxrp_close = ["
},
{
"path": "ch04/04_14.py",
"chars": 243,
"preview": "from pandas import Series \n \ndate = ['2018-08-01', '2018-08-02', '2018-08-03', '2018-08-04', '2018-08-05']\nxrp_close = ["
},
{
"path": "ch04/04_15.py",
"chars": 73,
"preview": "from pandas import Series \ns = Series([100, 200, 300, 400])\nprint(s /10)\n"
},
{
"path": "ch04/04_16.py",
"chars": 113,
"preview": "from pandas import DataFrame \n\ndata = {'open': [100, 200], \"high\": [110, 210]} \ndf = DataFrame(data ) \nprint(df)\n"
},
{
"path": "ch04/04_17.py",
"chars": 189,
"preview": "from pandas import DataFrame \n\ndata = {\"open\": [737, 750], \"high\": [755, 780], \"low\": [700, 710], \"close\": [750, 770]} \n"
},
{
"path": "ch04/04_18.py",
"chars": 64,
"preview": "import pandas as pd \ndf = pd.read_excel(\"ohlc.xlsx\") \nprint(df)\n"
},
{
"path": "ch04/04_19.py",
"chars": 117,
"preview": "import pandas as pd \ndf = pd.read_excel(\"ohlc.xlsx\") \ndf = df.set_index('date')\nprint(df)\ndf.to_excel(\"ohlc-2.xlsx\")\n"
},
{
"path": "ch04/04_20.py",
"chars": 123,
"preview": "import pandas as pd \nurl = \"https://finance.naver.com/item/sise_day.nhn?code=066570\" \ndf = pd.read_html(url) \nprint(df[0"
},
{
"path": "ch04/04_21.py",
"chars": 194,
"preview": "from pandas import DataFrame\n\ndata = {\"open\": [730, 750], \"high\": [755, 780], \"low\": [700, 710], \"close\": [750, 770]} \nd"
},
{
"path": "ch04/04_22.py",
"chars": 204,
"preview": "from pandas import DataFrame\n\ndata = {\"open\": [730, 750], \"high\": [755, 780], \"low\": [700, 710], \"close\": [750, 770]} \nd"
},
{
"path": "ch04/04_23.py",
"chars": 201,
"preview": "from pandas import Series, DataFrame\n\ndata = {\"open\": [737, 750], \"high\": [755, 780], \"low\": [700, 710], \"close\": [750, "
},
{
"path": "ch04/04_24.py",
"chars": 246,
"preview": "from pandas import Series, DataFrame\n\ndata = {\"open\": [737, 750], \"high\": [755, 780], \"low\": [700, 710], \"close\": [750, "
},
{
"path": "ch04/04_25.py",
"chars": 95,
"preview": "from pandas import Series \n\ns = Series([100, 200, 300]) \ns2 = s.shift(1) \nprint(s) \nprint(s2)\n\n"
},
{
"path": "ch05/05_01.py",
"chars": 108,
"preview": "import pybithumb\n\ntickers = pybithumb.get_tickers()\nprint(tickers)\nprint(len(tickers))\nprint(type(tickers))\n"
},
{
"path": "ch05/05_02.py",
"chars": 73,
"preview": "import pybithumb\n\nprice = pybithumb.get_current_price(\"BTC\")\nprint(price)"
},
{
"path": "ch05/05_03.py",
"chars": 123,
"preview": "import pybithumb\nimport time\n\nwhile True:\n price = pybithumb.get_current_price(\"BTC\")\n print(price)\n time.sleep"
},
{
"path": "ch05/05_04.py",
"chars": 179,
"preview": "import pybithumb\nimport time\n\ntickers = pybithumb.get_tickers()\nfor ticker in tickers:\n price = pybithumb.get_current"
},
{
"path": "ch05/05_05.py",
"chars": 96,
"preview": "import pybithumb\n\ndetail = pybithumb.get_market_detail(\"BTC\")\nprint(detail)\nprint(type(detail))\n"
},
{
"path": "ch05/05_06.py",
"chars": 111,
"preview": "import pybithumb\n\norderbook = pybithumb.get_orderbook(\"BTC\")\nprint(orderbook)\n\nfor k in orderbook:\n print(k)"
},
{
"path": "ch05/05_07.py",
"chars": 166,
"preview": "import pybithumb\nimport datetime\n\norderbook = pybithumb.get_orderbook(\"BTC\")\nms = int(orderbook['timestamp'])\n\ndt = date"
},
{
"path": "ch05/05_08.py",
"chars": 383,
"preview": "import pybithumb\n\norderbook = pybithumb.get_orderbook(\"BTC\")\nbids = orderbook['bids']\nasks = orderbook['asks']\nprint(bid"
},
{
"path": "ch05/05_09.py",
"chars": 343,
"preview": "import pybithumb\n\norderbook = pybithumb.get_orderbook(\"BTC\")\nbids = orderbook['bids']\nasks = orderbook['asks']\n\nfor bid "
},
{
"path": "ch05/05_10.py",
"chars": 100,
"preview": "import pybithumb\n\nall = pybithumb.get_current_price(\"ALL\")\nfor k, v in all.items():\n print(k, v)\n"
},
{
"path": "ch05/05_11.py",
"chars": 164,
"preview": "import pybithumb\n\ntickers = pybithumb.get_tickers()\nall = pybithumb.get_current_price(\"ALL\")\n\nfor ticker in tickers:\n "
},
{
"path": "ch05/05_12.py",
"chars": 117,
"preview": "price = {\"open\": 100, \"high\": 150, \"low\": 90, \"close\": 130}\nprint(\"point-1\")\nopen = price[\"open1\"]\nprint(\"point-2\")\n\n"
},
{
"path": "ch05/05_13.py",
"chars": 128,
"preview": "import pybithumb\nimport time\n\nwhile True:\n price = pybithumb.get_current_price(\"BTC\")\n print(price/10)\n time.sl"
},
{
"path": "ch05/05_14.py",
"chars": 95,
"preview": "import pybithumb\n\nbtc = pybithumb.get_ohlcv(\"BTC\")\nprint(btc)\nclose = btc['close']\nprint(close)"
},
{
"path": "ch05/05_15.py",
"chars": 264,
"preview": "import pybithumb\n\nbtc = pybithumb.get_ohlcv(\"BTC\")\nclose = btc['close']\nprint((close[0] + close[1] + close[2] + close[3]"
},
{
"path": "ch05/05_16.py",
"chars": 130,
"preview": "import pybithumb\n\nbtc = pybithumb.get_ohlcv(\"BTC\")\nclose = btc['close']\n\nwindow = close.rolling(5)\nma5 = window.mean()\np"
},
{
"path": "ch05/05_17.py",
"chars": 226,
"preview": "import pybithumb\n\ndf = pybithumb.get_ohlcv(\"BTC\")\nma5 = df['close'].rolling(window=5).mean()\nlast_ma5 = ma5[-2]\n\ncur_pri"
},
{
"path": "ch05/05_18.py",
"chars": 339,
"preview": "import pybithumb\n\ndef bull_market(ticker):\n df = pybithumb.get_ohlcv(ticker)\n ma5 = df['close'].rolling(5).mean()\n"
},
{
"path": "ch05/05_19.py",
"chars": 456,
"preview": "import pybithumb\n\ndef bull_market(ticker):\n df = pybithumb.get_ohlcv(ticker)\n ma5 = df['close'].rolling(5).mean()\n"
},
{
"path": "ch05/05_20.py",
"chars": 302,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\n\nform_class = uic.loadUiType(\"bull.ui\")[0]\n\nclass MyWindo"
},
{
"path": "ch05/05_21.py",
"chars": 475,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\n\nform_class = uic.loadUiType(\""
},
{
"path": "ch05/05_22.py",
"chars": 631,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\n\ntickers = [\"BTC\", \"ETH\", \"BCH"
},
{
"path": "ch05/05_23.py",
"chars": 1301,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\nimport pybithumb\n\ntickers = [\""
},
{
"path": "ch05/05_24.py",
"chars": 142,
"preview": "from PyQt5.QtCore import *\n\nclass Worker(QThread):\n def run(self):\n while True:\n print(\"안녕하세요\")\n "
},
{
"path": "ch05/05_25.py",
"chars": 405,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n\nclass Worker(QThread):\n def run(self):\n w"
},
{
"path": "ch05/05_26.py",
"chars": 1163,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\nimport pybithumb\nimport time\n\n"
},
{
"path": "ch05/05_27.py",
"chars": 1803,
"preview": "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\nimport pybithumb\nimport time\n\n"
},
{
"path": "ch05/05_ex_01.py",
"chars": 209,
"preview": "import pybithumb\n\nall = pybithumb.get_current_price(\"ALL\")\ntickers = pybithumb.get_tickers()\n\nfor ticker in tickers:\n "
},
{
"path": "ch05/bull.ui",
"chars": 1528,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>MainWindow</class>\n <widget class=\"QMainWindow\" name=\""
},
{
"path": "ch06/06_01.py",
"chars": 155,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_02.py",
"chars": 207,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_03.py",
"chars": 302,
"preview": "import pybithumb\nimport time\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n"
},
{
"path": "ch06/06_04.py",
"chars": 224,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_05.py",
"chars": 212,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_06.py",
"chars": 324,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_07.py",
"chars": 379,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_08.py",
"chars": 221,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_09.py",
"chars": 273,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_10.py",
"chars": 253,
"preview": "import pybithumb\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n\nbithumb = p"
},
{
"path": "ch06/06_11.py",
"chars": 304,
"preview": "import pybithumb\nimport time\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77c573weg34af17a\"\n"
},
{
"path": "ch06/06_12.py",
"chars": 126,
"preview": "import pybithumb\nimport time\n\nwhile True:\n price = pybithumb.get_current_price(\"BTC\")\n print(price)\n time.sleep"
},
{
"path": "ch06/06_13.py",
"chars": 250,
"preview": "import pybithumb\n\ndf = pybithumb.get_ohlcv(\"BTC\")\nyesterday = df.iloc[-2]\n\ntoday_open = yesterday['close']\nyesterday_hig"
},
{
"path": "ch06/06_14.py",
"chars": 404,
"preview": "import time\nimport datetime\n\nnow = datetime.datetime.now()\nmid = datetime.datetime(now.year, now.month, now.day) + datet"
},
{
"path": "ch06/06_15.py",
"chars": 371,
"preview": "import time\nimport datetime\n\nnow = datetime.datetime.now()\nmid = datetime.datetime(now.year, now.month, now.day) + datet"
},
{
"path": "ch06/06_16.py",
"chars": 818,
"preview": "import time\nimport pybithumb\nimport datetime\n\ndef get_target_price(ticker):\n df = pybithumb.get_ohlcv(\"BTC\")\n yest"
},
{
"path": "ch06/06_17.py",
"chars": 1202,
"preview": "import time\nimport pybithumb\nimport datetime\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77"
},
{
"path": "ch06/06_18.py",
"chars": 1409,
"preview": "import time\nimport pybithumb\nimport datetime\n\ncon_key = \"81dd5f25e5daa70b2fff603901d2c09c\"\nsec_key = \"82333efegeg9eg3e77"
},
{
"path": "ch06/06_19.py",
"chars": 1518,
"preview": "import time\nimport pybithumb\nimport datetime\n\nwith open(\"bithumb.txt\") as f:\n lines = f.readlines()\n key = lines[0"
},
{
"path": "ch06/06_20.py",
"chars": 1780,
"preview": "import time\nimport pybithumb\nimport datetime\n\nwith open(\"bithumb.txt\") as f:\n lines = f.readlines()\n key = lines[0"
},
{
"path": "ch07/07_01.py",
"chars": 66,
"preview": "import pybithumb\n\ndf = pybithumb.get_ohlcv(\"BTC\")\nprint(df.tail())"
},
{
"path": "ch07/07_02.py",
"chars": 74,
"preview": "import pybithumb\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf.to_excel(\"btc.xlsx\")\n"
},
{
"path": "ch07/07_03.py",
"chars": 118,
"preview": "import pybithumb\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf.to_excel(\"btc.xlsx\")"
},
{
"path": "ch07/07_04.py",
"chars": 167,
"preview": "import pybithumb\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf['target'] = df['open']"
},
{
"path": "ch07/07_05.py",
"chars": 209,
"preview": "import pybithumb\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf['range_shift1'] = df['"
},
{
"path": "ch07/07_06.py",
"chars": 209,
"preview": "import numpy as np\nfrom pandas import DataFrame\n\ndata = {'빗썸': [100, 100, 100],\n '코빗': [90, 110, 120]}\n\ndf = Data"
},
{
"path": "ch07/07_07.py",
"chars": 311,
"preview": "import pybithumb\nimport numpy as np\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf['ta"
},
{
"path": "ch07/07_08.py",
"chars": 327,
"preview": "import pybithumb\nimport numpy as np\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf['ta"
},
{
"path": "ch07/07_09.py",
"chars": 344,
"preview": "import pybithumb\nimport numpy as np\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf = df['2018']\n\ndf['range'] = (df['high'] - df['lo"
},
{
"path": "ch07/07_10.py",
"chars": 347,
"preview": "import pybithumb\nimport numpy as np\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf['ta"
},
{
"path": "ch07/07_11.py",
"chars": 490,
"preview": "import pybithumb\nimport numpy as np\n\n\ndef get_ror(k=0.5):\n df = pybithumb.get_ohlcv(\"BTC\")\n df['range'] = (df['hig"
},
{
"path": "ch07/07_12.py",
"chars": 362,
"preview": "import pybithumb\nimport numpy as np\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf['ta"
},
{
"path": "ch07/07_13.py",
"chars": 464,
"preview": "import pybithumb\nimport numpy as np\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf['ta"
},
{
"path": "ch07/07_14.py",
"chars": 609,
"preview": "import pybithumb\nimport numpy as np\n\ndf = pybithumb.get_ohlcv(\"BTC\")\n\ndf['ma5'] = df['close'].rolling(window=5).mean().s"
},
{
"path": "ch07/07_15.py",
"chars": 831,
"preview": "import pybithumb\nimport numpy as np\n\n\ndef get_hpr(ticker):\n df = pybithumb.get_ohlcv(ticker)\n df = df['2018']\n\n "
},
{
"path": "ch07/run.py",
"chars": 129,
"preview": "import pybithumb\n\ndf = pybithumb.get_ohlcv(interval=\"hour\")\ndf['Date'] = df.index.strftime(\"%Y-%m-%d %H:%M:%S\")\nprint(df"
},
{
"path": "ch08/08_01.py",
"chars": 62,
"preview": "import pyupbit\n\ntickers = pyupbit.get_tickers()\nprint(tickers)"
},
{
"path": "ch08/08_02.py",
"chars": 73,
"preview": "import pyupbit\n\nprice = pyupbit.get_current_price(\"KRW-XRP\")\nprint(price)"
},
{
"path": "ch08/08_03.py",
"chars": 59,
"preview": "import pyupbit\n\ndf = pyupbit.get_ohlcv(\"KRW-BTC\")\nprint(df)"
},
{
"path": "ch08/08_04.py",
"chars": 77,
"preview": "import pyupbit\n\norderbook = pyupbit.get_orderbook(\"KRW-BTC\")\nprint(orderbook)"
},
{
"path": "ch08/08_05.py",
"chars": 151,
"preview": "import pyupbit\n\norderbook = pyupbit.get_orderbook(\"KRW-BTC\")\nbids_asks = orderbook[0]['orderbook_units']\n\nfor bid_ask in"
},
{
"path": "ch08/08_06.py",
"chars": 202,
"preview": "import pyupbit\n\naccess_key = \"t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU\"\nsecret_key = \"VCLoAhrxbvyrukYChbxfxD6O1ESegeckIg"
},
{
"path": "ch08/08_07.py",
"chars": 234,
"preview": "import pyupbit\n\naccess_key = \"t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU\"\nsecret_key = \"VCLoAhrxbvyrukYChbxfxD6O1ESegeckIg"
},
{
"path": "ch08/08_08.py",
"chars": 237,
"preview": "import pyupbit\n\naccess_key = \"t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU\"\nsecret_key = \"VCLoAhrxbvyrukYChbxfxD6O1ESegeckIg"
},
{
"path": "ch08/08_09.py",
"chars": 251,
"preview": "import pyupbit\n\naccess_key = \"t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU\"\nsecret_key = \"VCLoAhrxbvyrukYChbxfxD6O1ESegeckIg"
},
{
"path": "ch08/08_10.py",
"chars": 65,
"preview": "import pykorbit\n\ntickers = pykorbit.get_tickers()\nprint(tickers)\n"
},
{
"path": "ch08/08_11.py",
"chars": 71,
"preview": "import pykorbit\n\nprice = pykorbit.get_current_price(\"BTC\")\nprint(price)"
},
{
"path": "ch08/08_12.py",
"chars": 57,
"preview": "import pykorbit\n\ndf = pykorbit.get_ohlc(\"BTC\")\nprint(df)\n"
},
{
"path": "ch08/08_13.py",
"chars": 75,
"preview": "import pykorbit\n\norderbook = pykorbit.get_orderbook(\"BTC\")\nprint(orderbook)"
},
{
"path": "ch08/08_14.py",
"chars": 127,
"preview": "import pykorbit\n\norderbook = pykorbit.get_orderbook(\"BTC\")\nasks = orderbook['asks']\nfor ask in asks:\n print(ask[0], a"
},
{
"path": "ch08/08_15.py",
"chars": 318,
"preview": "import pykorbit\n\nemail = \"ceo_jo@gmail.com\"\npassword = \"mypassword\"\nkey = \"TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY"
},
{
"path": "ch08/08_16.py",
"chars": 331,
"preview": "import pykorbit\n\nemail = \"ceo_jo@gmail.com\"\npassword = \"mypassword\"\nkey = \"TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY"
},
{
"path": "ch08/08_17.py",
"chars": 332,
"preview": "import pykorbit\n\nemail = \"ceo_jo@gmail.com\"\npassword = \"mypassword\"\nkey = \"TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY"
},
{
"path": "ch08/08_18.py",
"chars": 329,
"preview": "import pykorbit\n\nemail = \"ceo_jo@gmail.com\"\npassword = \"mypassword\"\nkey = \"TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY"
},
{
"path": "ch08/08_19.py",
"chars": 328,
"preview": "import pykorbit\n\nemail = \"ceo_jo@gmail.com\"\npassword = \"mypassword\"\nkey = \"TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY"
},
{
"path": "ch08/08_20.py",
"chars": 332,
"preview": "import pykorbit\n\nemail = \"ceo_jo@gmail.com\"\npassword = \"mypassword\"\nkey = \"TVMtMRtcap22CRnFeegege84cNDuTJVmvv9FaGWJTRriY"
},
{
"path": "ch08/08_21.py",
"chars": 94,
"preview": "import ccxt\n\nbinance = ccxt.binance()\nmarkets = binance.fetch_tickers()\nprint(markets.keys())\n"
},
{
"path": "ch08/08_22.py",
"chars": 149,
"preview": "import ccxt\n\nbinance = ccxt.binance()\nticker = binance.fetch_ticker('ETH/BTC')\nprint(ticker['open'], ticker['high'], tic"
},
{
"path": "ch08/08_23.py",
"chars": 92,
"preview": "import ccxt\n\nbinance = ccxt.binance()\nohlcvs = binance.fetch_ohlcv('ETH/BTC')\nprint(ohlcvs)\n"
},
{
"path": "ch08/08_24.py",
"chars": 207,
"preview": "import ccxt\nfrom datetime import datetime\n\nbinance = ccxt.binance()\nohlcvs = binance.fetch_ohlcv('ETH/BTC')\n\nfor ohlc in"
},
{
"path": "ch08/08_25.py",
"chars": 136,
"preview": "import ccxt\n\nbinance = ccxt.binance()\norderbook = binance.fetch_order_book('ETH/BTC')\nprint(orderbook['bids'])\nprint(ord"
},
{
"path": "ch08/08_26.py",
"chars": 142,
"preview": "import ccxt\n\nbinance = ccxt.binance()\norderbook = binance.fetch_order_book('ETH/BTC')\nfor ask in orderbook['asks']:\n "
},
{
"path": "ch09/09_01.py",
"chars": 101,
"preview": "def sync_func1():\n print(\"Hello\")\n\ndef sync_func2():\n print(\"Bye\")\n\nsync_func1()\nsync_func2()\n\n"
},
{
"path": "ch09/09_02.py",
"chars": 104,
"preview": "import asyncio \n\nasync def async_func1():\n print(\"Hello\")\n\nasync_func1()\n#asyncio.run(async_func1())\n"
},
{
"path": "ch09/09_03.py",
"chars": 145,
"preview": "import asyncio \n\nasync def async_func1():\n print(\"Hello\")\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(as"
},
{
"path": "ch09/09_04.py",
"chars": 421,
"preview": "import asyncio \n\nasync def make_americano():\n print(\"Americano Start\")\n await asyncio.sleep(3)\n print(\"American"
},
{
"path": "ch09/09_05.py",
"chars": 490,
"preview": "import asyncio \n\nasync def make_americano():\n print(\"Americano Start\")\n await asyncio.sleep(3)\n print(\"American"
},
{
"path": "ch09/09_06.py",
"chars": 131,
"preview": "import multiprocessing as mp \n\n\nif __name__ == \"__main__\":\n proc = mp.current_process()\n print(proc.name)\n prin"
},
{
"path": "ch09/09_07.py",
"chars": 416,
"preview": "import multiprocessing as mp\nimport time\n\ndef worker():\n proc = mp.current_process()\n print(proc.name)\n print(p"
},
{
"path": "ch09/09_08.py",
"chars": 301,
"preview": "import websockets\nimport asyncio \n\nasync def bithumb_ws_client():\n uri = \"wss://pubwss.bithumb.com/pub/ws\"\n\n async"
},
{
"path": "ch09/09_09.py",
"chars": 688,
"preview": "import websockets\nimport asyncio \nimport json\n\nasync def bithumb_ws_client():\n uri = \"wss://pubwss.bithumb.com/pub/ws"
},
{
"path": "ch09/09_10.py",
"chars": 2207,
"preview": "import multiprocessing as mp\nimport websockets\nimport asyncio \nimport json\nimport sys\nimport datetime\nfrom PyQt5.QtWidge"
},
{
"path": "ch09/09_11.py",
"chars": 1137,
"preview": "from pybithumb import WebSocketManager\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.Qt"
},
{
"path": "ch09/09_12.py",
"chars": 332,
"preview": "# korbit websocket connection\nimport websockets\nimport asyncio \n\nasync def korbit_ws_client():\n uri = \"wss://ws.korbi"
},
{
"path": "ch09/09_13.py",
"chars": 861,
"preview": "# Korbit Websocket Subscribe Example\nimport websockets\nimport asyncio \nimport json\nimport datetime \nimport pprint\n\nasync"
},
{
"path": "ch09/09_14.py",
"chars": 2928,
"preview": "import multiprocessing as mp\nimport websockets\nimport asyncio \nimport json\nimport datetime\nimport sys\nfrom PyQt5.QtWidge"
},
{
"path": "ch09/09_15.py",
"chars": 702,
"preview": "import websockets\nimport asyncio \nimport json\n\nasync def upbit_ws_client():\n uri = \"wss://api.upbit.com/websocket/v1\""
},
{
"path": "ch09/09_16.py",
"chars": 2085,
"preview": "import multiprocessing as mp\nimport websockets\nimport asyncio \nimport json\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom"
},
{
"path": "ch09/09_17.py",
"chars": 1155,
"preview": "from pyupbit import WebSocketManager\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n\n\nclass Worker("
},
{
"path": "ch10/chart.py",
"chars": 2792,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtGui import QPainter\nfrom PyQt5.QtChart"
},
{
"path": "ch10/chart_0.py",
"chars": 437,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\n\nclass ChartWidget(QWidget):\n def __init__(self,"
},
{
"path": "ch10/chart_1.py",
"chars": 991,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\n# ----------------- 추 가 ------------------\nfrom PyQ"
},
{
"path": "ch10/chart_2.py",
"chars": 1125,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtChart import QLineSeries, QChart\n# ---"
},
{
"path": "ch10/chart_3.py",
"chars": 1590,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtGui import QPainter\n# ----------------"
},
{
"path": "ch10/chart_4.py",
"chars": 2352,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtGui import QPainter\nfrom PyQt5.QtChart"
},
{
"path": "ch10/chart_5.py",
"chars": 2951,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtGui import QPainter\nfrom PyQt5.QtChart"
},
{
"path": "ch10/main.py",
"chars": 4398,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom pybithumb import Bithumb\nimp"
},
{
"path": "ch10/main_0.py",
"chars": 432,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n\nform_class = uic.loadUiType(\"res"
},
{
"path": "ch10/main_1.py",
"chars": 791,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n\nform_class = uic.loadUiType(\"res"
},
{
"path": "ch10/main_2.py",
"chars": 1555,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n# ----------------- 추 가 ---------"
},
{
"path": "ch10/main_3.py",
"chars": 1785,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n# ----------------- 추 가 ---------"
},
{
"path": "ch10/main_4.py",
"chars": 2710,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom pybithumb import Bithumb\n# -"
},
{
"path": "ch10/main_5.py",
"chars": 4274,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom pybithumb import Bithumb\nimp"
},
{
"path": "ch10/main_6.py",
"chars": 4494,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom pybithumb import Bithumb\nimp"
},
{
"path": "ch10/orderbook.py",
"chars": 4621,
"preview": "import sys\nimport time\nimport pybithumb\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets i"
},
{
"path": "ch10/orderbook_0.py",
"chars": 430,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\n\nclass OrderbookWidget(QWidget):\n def __init__(s"
},
{
"path": "ch10/orderbook_1.py",
"chars": 2249,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\n# ----------------- 추 가 ------------------\nfrom PyQ"
},
{
"path": "ch10/orderbook_2.py",
"chars": 2933,
"preview": "import sys\nimport time\nimport pybithumb\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets i"
},
{
"path": "ch10/orderbook_3.py",
"chars": 4059,
"preview": "import sys\nimport time\nimport pybithumb\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets i"
},
{
"path": "ch10/orderbook_4.py",
"chars": 5307,
"preview": "import sys\nimport time\nimport pybithumb\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets i"
},
{
"path": "ch10/overview.py",
"chars": 3053,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtCore import Qt, QThread, pyqtSignal\nfr"
},
{
"path": "ch10/overview_0.py",
"chars": 417,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\n\nclass OverviewWidget(QWidget):\n def __init__(se"
},
{
"path": "ch10/overview_1.py",
"chars": 2130,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtCore import Qt, QThread, pyqtSignal\nfr"
},
{
"path": "ch10/overview_2.py",
"chars": 2454,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtCore import Qt, QThread, pyqtSignal\nfr"
},
{
"path": "ch10/overview_3.py",
"chars": 3054,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtCore import Qt, QThread, pyqtSignal\nfr"
},
{
"path": "ch10/overview_4.py",
"chars": 3363,
"preview": "import sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtCore import Qt, QThread, pyqtSignal\nfr"
},
{
"path": "ch10/resource/chart.ui",
"chars": 1063,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>Form</class>\n <widget class=\"QWidget\" name=\"Form\">\n <"
},
{
"path": "ch10/resource/main.ui",
"chars": 3491,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>MainWindow</class>\n <widget class=\"QMainWindow\" name=\""
},
{
"path": "ch10/resource/orderbook.ui",
"chars": 4952,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>Form</class>\n <widget class=\"QWidget\" name=\"Form\">\n <"
},
{
"path": "ch10/resource/overview.ui",
"chars": 6248,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>Form</class>\n <widget class=\"QWidget\" name=\"Form\">\n <"
},
{
"path": "ch10/volatility.py",
"chars": 870,
"preview": "import time\nimport pybithumb\n\ndef get_target_price(ticker):\n df = pybithumb.get_ohlcv(ticker)\n yesterday = df.iloc"
}
]
// ... and 2 more files (download for full content)
About this extraction
This page contains the full source code of the sharebook-kr/book-cryptocurrency GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 199 files (153.5 KB), approximately 46.0k tokens, and a symbol index with 334 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.