<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">import os
import json
import requests
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv('C:/Users/user/projects/st/config/.env')

# Read environment variables from .env
MY_AGENT = os.getenv('MY_AGENT')
MY_APP = os.getenv('MY_APP')
MY_SEC = os.getenv('MY_SEC')
MY_ACCT_STOCK = os.getenv('MY_ACCT_STOCK')
MY_PROD = os.getenv('MY_PROD')
PROD_URL = os.getenv('PROD_URL')
CANO = os.getenv('CANO')
USER_ID = os.getenv('USER_ID')

# Function to load configuration from config.json
def load_config():
    config_path = 'C:/Users/user/projects/st/config/config.json'
    try:
        with open(config_path, 'r') as file:
            config = json.load(file)
            print("Configuration successfully read from file.")
            return config
    except FileNotFoundError:
        print(f"Configuration file not found at {config_path}")
        return None
    except json.JSONDecodeError:
        print("Error decoding the configuration JSON file.")
        return None

# Load configuration from config.json if environment variables are not set
config = load_config()
if config:
    MY_AGENT = MY_AGENT or config.get('my_agent')
    MY_APP = MY_APP or config.get('my_app')
    MY_SEC = MY_SEC or config.get('my_sec')
    MY_ACCT_STOCK = MY_ACCT_STOCK or config.get('my_acct_stock')
    MY_PROD = MY_PROD or config.get('my_prod')
    PROD_URL = PROD_URL or config.get('prod')
    CANO = CANO or config.get('kis_devlp.yaml', {}).get('CANO')

_BASE_URL = PROD_URL

# Function to read token from JSON file
def read_token():
    token_path = 'C:/Users/user/projects/st/config/token.json'
    try:
        with open(token_path, 'r') as file:
            token_data = json.load(file)
            print("Token data successfully read from file.")
            token = token_data.get('access_token')
            valid_date = token_data.get('expiration')
            if token and valid_date:
                return token, valid_date
            else:
                print("Token or valid_date is missing in the token file.")
                return None, None
    except FileNotFoundError:
        print(f"Token file not found at {token_path}")
        return None, None
    except json.JSONDecodeError:
        print("Error decoding the token JSON file.")
        return None, None

# Function to get access token
def get_access_token():
    token, valid_date = read_token()
    if token:
        # Check if the token is still valid
        valid_date = datetime.strptime(valid_date, "%Y-%m-%d %H:%M:%S")
        if valid_date &gt; datetime.now():
            print("Using the existing token.")
            return token
        else:
            print("Token has expired. Please obtain a new token.")
            return None
    else:
        print("Token not found. Please obtain a new token.")
        return None

# Function to get account balance
def get_acct_balance():
    url = f"{_BASE_URL}/uapi/domestic-stock/v1/trading/inquire-balance"
    access_token = get_access_token()
    if not access_token:
        print("Unable to retrieve a valid access token.")
        return None

    headers = {
        "Content-Type": "application/json; charset=utf-8",
        "Authorization": f"Bearer {access_token}",
        "appkey": MY_APP,
        "appsecret": MY_SEC,
        "tr_id": "TTTC8434R",
        "User-Agent": MY_AGENT
    }
    print(f"Request headers: {headers}")

    params = {
        "CANO": CANO,
        "ACNT_PRDT_CD": MY_ACCT_STOCK,
        "AFHR_FLPR_YN": "N",
        "OFL_YN": "",
        "INQR_DVSN": "01",
        "UNPR_DVSN": "01",
        "FUND_STTL_ICLD_YN": "N",
        "FNCG_AMT_AUTO_RDPT_YN": "N",
        "PRCS_DVSN": "00",
        "CTX_AREA_FK100": "",
        "CTX_AREA_NK100": ""
    }
    print(f"Request params: {params}")

    try:
        response = requests.get(url, headers=headers, params=params)
        print(f"HTTP response status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print("API response data:")
            print(json.dumps(data, indent=2))  # Print the entire response for debugging
            if data['rt_cd'] == '0':
                df_output1 = pd.DataFrame(data['output1'])
                df_output2 = pd.DataFrame(data['output2'])
                save_balance_to_json(df_output1, df_output2)
                dnca_tot_amt = data['output2'][0]['dnca_tot_amt']
                return df_output1, df_output2, dnca_tot_amt
            else:
                print("API error:", data['msg1'])
                return None
        else:
            print("HTTP error:", response.status_code)
            print("Response content:", response.content)  # Print the response content for debugging
            return None
    except requests.exceptions.RequestException as e:
        print("Request exception occurred:", e)
        return None

# Function to save balance data to a JSON file
def save_balance_to_json(df_output1, df_output2):
    balance_json_path_output1 = os.path.join('C:/Users/user/projects/st/data', 'balance_output1.json')
    balance_json_path_output2 = os.path.join('C:/Users/user/projects/st/data', 'balance_output2.json')
    df_output1.to_json(balance_json_path_output1, orient='records', force_ascii=False)
    df_output2.to_json(balance_json_path_output2, orient='records', force_ascii=False)
    print(f"Account balance saved to {balance_json_path_output1} and {balance_json_path_output2}")

# Main function
if __name__ == "__main__":
    # �붿븸 議고쉶
    print("Getting account balance...")
    balance_df_output1, balance_df_output2, dnca_tot_amt = get_acct_balance()
    if balance_df_output1 is not None and balance_df_output2 is not None:
        print("Output 1 DataFrame:")
        print(balance_df_output1)
        print("Output 2 DataFrame:")
        print(balance_df_output2)
        print(f"�덉닔湲� 珥앷툑�� (dnca_tot_amt): {dnca_tot_amt}")
    else:
        print("�붿븸�� 議고쉶�� �� �놁뒿�덈떎.")
</pre></body></html>