반응형
안녕하세요. 이번 포스팅에서는 이전에 작성했던 코드들을 취합 및 수정하고, 메모장 기능을 추가한 코드를 포스팅하도록 하겠습니다.
1. 메모장 추가
tkinter의 Text를 이용하여 메모할 수 있도록 공간을 마련했습니다. '.env' 파일에 memoBefore이라는 key로 메모 내용을 저장하고 불러와서 text에 insert 하여, 코드 실행 시 자동적으로 이전의 메모를 불러오고, 메모 내용에 변화가 있을 시 해당 내용을 '.env' 파일에 수정할 수 있게 했습니다.
2. 수정사항
가독성을 위해 기본 글씨색을 노란색으로 수정해 주었고, 메모장 내의 깜빡이는 커서 색은 흰색으로 할당해주었습니다.(insertbackground)
새로고침 할 경우 이전내용이 삭제가 안되고 남아있는 경우가 발생해 (특히 포지션 개수가 줄어드는 경우), 업데이트 이전의 레이블을 destroy 하는 방법을 생각했으나 코드가 복잡해질 것 같아, 새로고침 할 때 다른 레이블들을 덮어버릴 큰 레이블 하나를 배치하는 것으로 대신했습니다.

3. 코드
import ccxt
import os
import dotenv
import tkinter
import tkinter.font
from tkinter import *
import datetime as dt
import threading
import time
dotenv_file = dotenv.find_dotenv()
dotenv.load_dotenv(dotenv_file)
apikey = os.environ['bn_apikey']
apisecret = os.environ['bn_secret']
memoBefore = os.environ['memoBefore']
############################################################
# 폰트색상
def color(amount):
if amount >=0:
return 'green'
else:
return 'red'
############################################################
# 윈도우 생성
def gui():
global font
win = tkinter.Tk ()
win.title("Traiding Tools")
win.configure(background='black')
win.geometry('155x400')
font=tkinter.font.Font(family="Arial", size=10, slant="italic", weight='bold')
#메모장
text = Text(win, bg = 'black', insertbackground='white', height=10, width=17, fg='yellow',font=tkinter.font.Font(family="Arial", size=12, weight='bold'))
text.place(x = 0, y =200)
text.insert(END, memoBefore)
binance = ccxt.binance(config={'apiKey': apikey, 'secret': apisecret})
############################################################
# 새로고침
def update():
############################################################
# 선물 포지션 불러오기
def from_binance():
global symbol
global size
global pnl
while True:
try:
balance = binance.fetch_balance(params={"type": "future"})
break
except:
time.sleep(5)
positions = balance['info']['positions']
# 오픈 포지션 분리
symbol = []
size = []
pnl = []
for position in positions:
if position['initialMargin'] != '0':
symbol.append(position['symbol'])
size.append(position['notional'])
pnl.append(float(position['unrealizedProfit']))
############################################################
# 레이블 배치
def arrange_label():
# 지우기
lb_clear = tkinter.Label(width=20, height=10, background='black')
lb_clear.place(x=0, y=0)
# 현재시간 표시
y = 0
lb_time = tkinter.Label(font=font, fg='yellow', background='black')
lb_time.place(x = 0, y = y)
now_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
lb_time.configure(text = now_time)
# 현재포지션 표시
for n in range(len(symbol)):
# 포지션 배치
x = 70
y += 16.5
globals()['lb_sym_' + symbol[n]] = tkinter.Label(font=font, fg=color(float(size[n])), background='black')
globals()['lb_pnl_' + symbol[n]] = tkinter.Label(font=font, fg=color(pnl[n]), background='black')
globals()['lb_sym_' + symbol[n]].place(x = 0, y = y)
globals()['lb_pnl_' + symbol[n]].place(x = x, y = y)
globals()['lb_sym_' + symbol[n]].configure(text = "{0}".format(symbol[n]))
globals()['lb_pnl_' + symbol[n]].configure(text = "{0:.2f} $".format(pnl[n]))
# total pnl
pnl_tot = sum(pnl)
y = y+16.5
lb_tot = tkinter.Label(font=font, fg = color(sum(pnl)), background='black')
lb_tot.place(x=0, y=y)
lb_tot.configure(text = "Total pnl: {0:.2f} $".format(pnl_tot))
############################################################
# 메모장 내용 저장
def saveMemo():
global memoBefore
memoText = text.get(1.0, 'end-1c')
if memoText != memoBefore:
dotenv.set_key(dotenv_file, 'memoBefore', memoText)
memoBefore = memoText
from_binance()
arrange_label()
saveMemo()
threading.Timer(5, update).start()
update()
win.mainloop()
gui()
여기까지 tkinter을 이용해 새로운 윈도우에 필요한 정보들(시간, 포지션, 메모)을 띄울 수 있는 코드를 작성해 보았습니다. 향후 추가적인 기능을 넣거나, 에러 발생 시 추가 업데이트 예정입니다. 읽어주셔서 감사합니다.
반응형
'Python > 바이낸스 포지션 - ccxt, tkinter' 카테고리의 다른 글
파이썬 바이낸스 선물 포지션 조회 및 출력 [2/3] (0) | 2022.10.20 |
---|---|
파이썬 바이낸스 선물 포지션 조회 및 출력 [1/3] (0) | 2022.10.18 |