From e1787d66e727b5e1c525b8dca6f278af272040a0 Mon Sep 17 00:00:00 2001 From: dsyoon Date: Thu, 7 Aug 2025 02:12:26 +0900 Subject: [PATCH] init --- stock_monitor.py | 58 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/stock_monitor.py b/stock_monitor.py index 7d8c479..eba95b8 100644 --- a/stock_monitor.py +++ b/stock_monitor.py @@ -13,9 +13,45 @@ import schedule from config import * import FinanceDataReader as fdr import numpy as np +import os hts = HTS() +# 매수 금지 시간을 관리하는 JSON 파일 경로 +COOLDOWN_FILE = 'coins_buy_time.json' + +def load_buy_cooldown(): + """매수 금지 시간을 JSON 파일에서 로드""" + if os.path.exists(COOLDOWN_FILE): + try: + with open(COOLDOWN_FILE, 'r', encoding='utf-8') as f: + data = json.load(f) + # 문자열을 datetime 객체로 변환 + cooldown = {} + for symbol, time_str in data.items(): + cooldown[symbol] = datetime.fromisoformat(time_str) + return cooldown + except Exception as e: + print(f"Error loading cooldown data: {e}") + return {} + return {} + +def save_buy_cooldown(cooldown): + """매수 금지 시간을 JSON 파일에 저장""" + try: + # datetime 객체를 문자열로 변환 + data = {} + for symbol, dt in cooldown.items(): + data[symbol] = dt.isoformat() + + with open(COOLDOWN_FILE, 'w', encoding='utf-8') as f: + json.dump(data, f, ensure_ascii=False, indent=2) + except Exception as e: + print(f"Error saving cooldown data: {e}") + +# 매수 금지 시간을 추적하는 전역 딕셔너리 +buy_cooldown = load_buy_cooldown() + def send_coin_msg(text): coin_client = telegram.Bot(token=COIN_TELEGRAM_BOT_TOKEN) asyncio.run(coin_client.send_message(chat_id=COIN_TELEGRAM_CHAT_ID, text=text)) @@ -40,6 +76,14 @@ def send_coin_telegram_message(message_list, header): def buy_ticker(symbole, data): try: + # 매수 금지 시간 확인 (20분) + current_time = datetime.now() + if symbole in buy_cooldown: + time_diff = current_time - buy_cooldown[symbole] + if time_diff.total_seconds() < 1200: # 20분 = 1200초 + print(f"{symbole}: 매수 금지 중 (남은 시간: {1200 - time_diff.total_seconds():.0f}초)") + return False + BUY_AMOUNT = 6000 if data['buy_signal'].iloc[-1] == 'movingaverage': @@ -50,8 +94,16 @@ def buy_ticker(symbole, data): BUY_AMOUNT = 6000 _ = hts.buyCoinMarket(symbole, BUY_AMOUNT) + + # 매수 성공 시 금지 시간 설정 및 파일에 저장 + buy_cooldown[symbole] = current_time + save_buy_cooldown(buy_cooldown) + print(f"{symbole}: 매수 완료, 20분간 매수 금지 시작") + return True + except Exception as e: print(f"Error buying {symbole}: {str(e)}") + return False return @@ -449,7 +501,9 @@ def monitor_coins(): message_list.append(format_message('COIN', symbol, KR_COINS[symbol], recent_data['Close'].iloc[-1], recent_data['buy_signal'].iloc[-1])) # buy - buy_ticker(symbol, recent_data) + buy_success = buy_ticker(symbol, recent_data) + if not buy_success: + continue # 매수 금지 중이면 다음 코인으로 넘어감 except Exception as e: print(f"Error processing data for {symbol}: {str(e)}") @@ -482,6 +536,8 @@ def run_schedule(): schedule.every().day.at("07:10").do(monitor_kr_stocks) print("Scheduler started. Monitoring will run at specified times.") + print(f"Loaded cooldown data for {len(buy_cooldown)} coins") + while True: schedule.run_pending() time.sleep(1)