샘플코드 HOME API문서 샘플코드
국내주식부문
REST
국내주식부문 API 구현 예제
Java
Java Code
import jdk.nashorn.internal.objects.NativeJSON; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class TTTC0802U { public static void main(String[] args) throws IOException { // 국내 주식 주문 String url = "https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/order-cash"; String tr_id = "TTTC0802U"; String data = "{\n" + " \"CANO\": \"종합계좌번호\",\n" + " \"ACNT_PRDT_CD\": \"계좌상품코드\",\n" + " \"ACNT_PWD\": \"계좌비밀번호\",\n" + " \"PDNO\": \"상품번호\",\n" + " \"ORD_DVSN\": \"주문구분\",\n" + " \"ORD_QTY\": \"주문수량\",\n" + " \"ORD_UNPR\": \"주문단가\",\n" + " \"CTAC_TLNO\": \"연락전화번호\"\n" + "}"; httpPostBodyConnection(url,data,tr_id); } public static void httpPostBodyConnection(String UrlData, String ParamData,String TrId) throws IOException { String totalUrl = ""; totalUrl = UrlData.trim().toString(); URL url = null; HttpURLConnection conn = null; String responseData = ""; BufferedReader br = null; StringBuffer sb = new StringBuffer(); String returnData = ""; try{ url = new URL(totalUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("authorization", "Bearer {TOKEN}"); conn.setRequestProperty("appKey", "{Client_ID}"); conn.setRequestProperty("appSecret", "{Client_Secret}"); conn.setRequestProperty("personalSeckey", "{personalSeckey}"); conn.setRequestProperty("tr_id", TrId); conn.setRequestProperty("tr_cont", " "); conn.setRequestProperty("custtype", "법인(B), 개인(P)"); conn.setRequestProperty("seq_no", "법인(01), 개인( )"); conn.setRequestProperty("mac_address", "{Mac_address}"); conn.setRequestProperty("phone_num", "P01011112222"); conn.setRequestProperty("ip_addr", "{IP_addr}"); conn.setRequestProperty("hashkey", "{Hash값}"); conn.setRequestProperty("gt_uid", "{Global UID}"); conn.setDoOutput(true); try (OutputStream os = conn.getOutputStream()) { byte request_data[] = ParamData.getBytes("utf-8"); os.write(request_data); os.close(); } catch (Exception e) { e.printStackTrace(); } conn.connect(); System.out.println("http 요청 방식" + "POST BODY JSON"); System.out.println("http 요청 타입" + "application/json"); System.out.println("http 요청 주소" + UrlData); System.out.println(""); br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); } catch (IOException e){ br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); } finally { try { sb = new StringBuffer(); while ((responseData = br.readLine()) != null) { sb.append(responseData); } returnData = sb.toString(); String responseCode = String.valueOf(conn.getResponseCode()); System.out.println("http 응답 코드 : " + responseCode); System.out.println("http 응답 데이터 : " + returnData); if (br != null){ br.close(); } } catch (IOException e){ throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e); } } } }
Javascript
Javascript Code
var xhr = new XMLHttpRequest(); /* 국내 주식 주문 */ var url = 'https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/order-cash'; xhr.open('post',url); xhr.setRequestHeader('Content-Type','application/json') xhr.setRequestHeader('authorization','Bearer {TOKEN}') xhr.setRequestHeader('appKey','{Client_ID}') xhr.setRequestHeader('appSecret','{Client_Secret}') xhr.setRequestHeader('personalSeckey','{personalSeckey}') xhr.setRequestHeader('tr_id','FHKST01010100') xhr.setRequestHeader('tr_cont','') xhr.setRequestHeader('custtype','법인(B), 개인(P)') xhr.setRequestHeader('seq_no','법인(01), 개인( )') xhr.setRequestHeader('mac_address','{Mac_address}') xhr.setRequestHeader('phone_num','P01011112222') xhr.setRequestHeader('ip_addr','{IP_addr}') xhr.setRequestHeader('hashkey','{Hash값}') xhr.setRequestHeader('gt_uid','{Global UID}') xhr.onreadystatechange = function () { if (this.readyState == 4) { console.log('Status : ' + this.status + '\nHeaders:' + JSON.stringify(this.getAllResponseHeaders()) + '\Body :' + this.responseText); } }; xhr.send('{\n' + ' "CANO": "종합계좌번호",\n' + ' "ACNT_PRDT_CD": "계좌상품코드",\n' + ' "ACNT_PWD": "계좌비밀번호",\n' + ' "PDNO": "상품번호",\n' + ' "ORD_DVSN": "주문구분",\n' + ' "ORD_QTY": "주문수량",\n' + ' "ORD_UNPR": "주문단가",\n' + ' "CTAC_TLNO": "연락전화번호"\n' + '}');
Python
Python Code
# requests 모듈 설치 필요 (pip install requests) import requests import json url = 'https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/order-cash' body = { "CANO": "종합계좌번호", "ACNT_PRDT_CD": "계좌상품코드", "PDNO": "상품번호", "ORD_DVSN": "주문구분", "ORD_QTY": "주문수량", "ORD_UNPR": "주문단가", "CTAC_TLNO": "연락전화번호" } headers = { "Content-Type": "application/json", "authorization": "Bearer {TOKEN}", "appKey": "{Client_ID}", "appSecret": "{Client_Secret}", "personalSeckey": "{personalSeckey}", "tr_id": "TTTC0802U", "tr_cont": " ", "custtype": "법인(B), 개인(P)", "seq_no": "법인(01), 개인( )", "mac_address": "{Mac_address}", "phone_num": "P01011112222", "ip_addr": "{IP_addr}", "hashkey": "{Hash값}", "gt_uid": "{Global UID}" } res = requests.post(url, data=json.dumps(body), headers=headers) rescode = res.status_code if rescode == 200: print(res.headers) print(str(rescode) + " | " + res.text) else: print("Error Code : " + str(rescode) + " | " + res.text)
매수가능조회
REST
매수가능조회 API 구현 예제
Java
Java Code
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class TTTC8908R { public static void main(String[] args) throws IOException { // 매수가능 조회 String url = "https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/inquire-psbl-order"; String tr_id = "TTTC8908R"; String data = "{\n" + " \"CANO\": \"종합계좌번호\",\n" + " \"ACNT_PRDT_CD\": \"계좌상품코드\",\n" + " \"ACNT_PWD\": \"계좌비밀번호\",\n" + " \"PDNO\": \"상품번호\",\n" + " \"ORD_UNPR\": \"주문단가\",\n" + " \"ORD_DVSN\": \"주문구분\",\n" + " \"CMA_EVLU_AMT_ICLD_YN\": \"CMA평가금액포함여부\",\n" + " \"OVRS_ICLD_YN\": \"해외포함여부\"\n" + "}"; httpPostBodyConnection(url,data,tr_id); } public static void httpPostBodyConnection(String UrlData, String ParamData,String TrId) throws IOException { String totalUrl = ""; totalUrl = UrlData.trim().toString(); URL url = null; HttpURLConnection conn = null; String responseData = ""; BufferedReader br = null; StringBuffer sb = new StringBuffer(); String returnData = ""; try{ url = new URL(totalUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("authorization", "Bearer {TOKEN}"); conn.setRequestProperty("appKey", "{Client_ID}"); conn.setRequestProperty("appSecret", "{Client_Secret}"); conn.setRequestProperty("personalSeckey", "{personalSeckey}"); conn.setRequestProperty("tr_id", TrId); conn.setRequestProperty("tr_cont", " "); conn.setRequestProperty("custtype", "법인(B), 개인(P)"); conn.setRequestProperty("seq_no", "법인(01), 개인( )"); conn.setRequestProperty("mac_address", "{Mac_address}"); conn.setRequestProperty("phone_num", "P01011112222"); conn.setRequestProperty("ip_addr", "{IP_addr}"); conn.setRequestProperty("hashkey", "{Hash값}"); conn.setRequestProperty("gt_uid", "{Global UID}"); conn.setDoOutput(true); try (OutputStream os = conn.getOutputStream()) { byte request_data[] = ParamData.getBytes("utf-8"); os.write(request_data); os.close(); } catch (Exception e) { e.printStackTrace(); } conn.connect(); System.out.println("http 요청 방식" + "POST BODY JSON"); System.out.println("http 요청 타입" + "application/json"); System.out.println("http 요청 주소" + UrlData); System.out.println(""); br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); } catch (IOException e){ br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); } finally { try { sb = new StringBuffer(); while ((responseData = br.readLine()) != null) { sb.append(responseData); } returnData = sb.toString(); String responseCode = String.valueOf(conn.getResponseCode()); System.out.println("http 응답 코드 : " + responseCode); System.out.println("http 응답 데이터 : " + returnData); if (br != null){ br.close(); } } catch (IOException e){ throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e); } } } }
Javascript
Javascript Code
var xhr = new XMLHttpRequest(); /* 계좌주문 체결내역 조회 */ var url = 'https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/inquire-daily-ccld'; xhr.open('post',url); xhr.setRequestHeader('Content-Type','application/json') xhr.setRequestHeader('authorization','Bearer {TOKEN}') xhr.setRequestHeader('appKey','{Client_ID}') xhr.setRequestHeader('appSecret','{Client_Secret}') xhr.setRequestHeader('personalSeckey','{personalSeckey}') xhr.setRequestHeader('tr_id','FHKST01010100') xhr.setRequestHeader('tr_cont','') xhr.setRequestHeader('custtype','법인(B), 개인(P)') xhr.setRequestHeader('seq_no','법인(01), 개인( )') xhr.setRequestHeader('mac_address','{Mac_address}') xhr.setRequestHeader('phone_num','P01011112222') xhr.setRequestHeader('ip_addr','{IP_addr}') xhr.setRequestHeader('hashkey','{Hash값}') xhr.setRequestHeader('gt_uid','{Global UID}') xhr.onreadystatechange = function () { if (this.readyState == 4) { console.log('Status : ' + this.status + '\nHeaders:' + JSON.stringify(this.getAllResponseHeaders()) + '\Body :' + this.responseText); } }; xhr.send('{\n' + ' "CANO": "종합계좌번호",\n' + ' "ACNT_PRDT_CD": "계좌상품코드",\n' + ' "PWD": "비밀번호",\n' + ' "INQR_STRT_DT": "조회시작일자",\n' + ' "INQR_END_DT": "조회종료일자",\n' + ' "SLL_BUY_DVSN_CD": "매도매수구분코드",\n' + ' "INQR_DVSN": "조회구분",\n' + ' "PDNO": "상품번호",\n' + ' "CCLD_DVSN": "체결구분",\n' + ' "ORD_GNO_BRNO": "주문채번지점번호",\n' + ' "ODNO": "주문번호",\n' + ' "INQR_DVSN_3": "조회구분3",\n' + ' "INQR_DVSN_1": "조회구분1",\n' + ' "CTX_AREA_FK100": "연속조회검색조건100",\n' + ' "CTX_AREA_NK100": "연속조회키100"\n' + '}');
Python
Python Code
# requests 모듈 설치 필요 (pip install requests) import requests url = 'https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/inquire-psbl-order' params = { "CANO": "종합계좌번호", "ACNT_PRDT_CD": "계좌상품코드", "ACNT_PWD": "계좌비밀번호", "PDNO": "상품번호", "ORD_UNPR": "주문단가", "ORD_DVSN": "주문구분", "CMA_EVLU_AMT_ICLD_YN": "CMA평가금액포함여부", "OVRS_ICLD_YN": "해외포함여부" } headers = { "Content-Type": "application/json", "authorization": "Bearer {TOKEN}", "appKey": "{Client_ID}", "appSecret": "{Client_Secret}", "personalSeckey": "{personalSeckey}", "tr_id": "TTTC8908R", "tr_cont": " ", "custtype": "법인(B), 개인(P)", "seq_no": "법인(01), 개인( )", "mac_address": "{Mac_address}", "phone_num": "P01011112222", "ip_addr": "{IP_addr}", "hashkey": "{Hash값}", "gt_uid": "{Global UID}" } res = requests.get(url, params=params, headers=headers) rescode = res.status_code if rescode == 200: print(res.headers) print(str(rescode) + " | " + res.text) else: print("Error Code : " + str(rescode) + " | " + res.text)
주식일별주문체결조회
REST
주식일별주문체결조회 API 구현 예제
Java
Java Code
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class TTTC8001R { public static void main(String[] args) throws IOException { // 계좌주문 체결내역 조회 String url = "https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/inquire-daily-ccld"; String tr_id = "TTTC8001R"; String data = "{\n" + " \"CANO\": \"종합계좌번호\",\n" + " \"ACNT_PRDT_CD\": \"계좌상품코드\",\n" + " \"PWD\": \"비밀번호\",\n" + " \"INQR_STRT_DT\": \"조회시작일자\",\n" + " \"INQR_END_DT\": \"조회종료일자\",\n" + " \"SLL_BUY_DVSN_CD\": \"매도매수구분코드\",\n" + " \"INQR_DVSN\": \"조회구분\",\n" + " \"PDNO\": \"상품번호\",\n" + " \"CCLD_DVSN\": \"체결구분\",\n" + " \"ORD_GNO_BRNO\": \"주문채번지점번호\",\n" + " \"ODNO\": \"주문번호\",\n" + " \"INQR_DVSN_3\": \"조회구분3\",\n" + " \"INQR_DVSN_1\": \"조회구분1\",\n" + " \"CTX_AREA_FK100\": \"연속조회검색조건100\",\n" + " \"CTX_AREA_NK100\": \"연속조회키100\"\n" + "}"; httpPostBodyConnection(url,data,tr_id); } public static void httpPostBodyConnection(String UrlData, String ParamData,String TrId) throws IOException { String totalUrl = ""; totalUrl = UrlData.trim().toString(); URL url = null; HttpURLConnection conn = null; String responseData = ""; BufferedReader br = null; StringBuffer sb = new StringBuffer(); String returnData = ""; try{ url = new URL(totalUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("authorization", "Bearer {TOKEN}"); conn.setRequestProperty("appKey", "{Client_ID}"); conn.setRequestProperty("appSecret", "{Client_Secret}"); conn.setRequestProperty("personalSeckey", "{personalSeckey}"); conn.setRequestProperty("tr_id", TrId); conn.setRequestProperty("tr_cont", " "); conn.setRequestProperty("custtype", "법인(B), 개인(P)"); conn.setRequestProperty("seq_no", "법인(01), 개인( )"); conn.setRequestProperty("mac_address", "{Mac_address}"); conn.setRequestProperty("phone_num", "P01011112222"); conn.setRequestProperty("ip_addr", "{IP_addr}"); conn.setRequestProperty("hashkey", "{Hash값}"); conn.setRequestProperty("gt_uid", "{Global UID}"); conn.setDoOutput(true); try (OutputStream os = conn.getOutputStream()) { byte request_data[] = ParamData.getBytes("utf-8"); os.write(request_data); os.close(); } catch (Exception e) { e.printStackTrace(); } conn.connect(); System.out.println("http 요청 방식" + "POST BODY JSON"); System.out.println("http 요청 타입" + "application/json"); System.out.println("http 요청 주소" + UrlData); System.out.println(""); br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); } catch (IOException e){ br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); } finally { try { sb = new StringBuffer(); while ((responseData = br.readLine()) != null) { sb.append(responseData); } returnData = sb.toString(); String responseCode = String.valueOf(conn.getResponseCode()); System.out.println("http 응답 코드 : " + responseCode); System.out.println("http 응답 데이터 : " + returnData); if (br != null){ br.close(); } } catch (IOException e){ throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e); } } } }
Javascript
Javascript Code
var xhr = new XMLHttpRequest(); /* 계좌주문 체결내역 조회 */ var url = 'https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/inquire-psbl-order'; xhr.open('post',url); xhr.setRequestHeader('Content-Type','application/json') xhr.setRequestHeader('authorization','Bearer {TOKEN}') xhr.setRequestHeader('appKey','{Client_ID}') xhr.setRequestHeader('appSecret','{Client_Secret}') xhr.setRequestHeader('personalSeckey','{personalSeckey}') xhr.setRequestHeader('tr_id','FHKST01010100') xhr.setRequestHeader('tr_cont','') xhr.setRequestHeader('custtype','법인(B), 개인(P)') xhr.setRequestHeader('seq_no','법인(01), 개인( )') xhr.setRequestHeader('mac_address','{Mac_address}') xhr.setRequestHeader('phone_num','P01011112222') xhr.setRequestHeader('ip_addr','{IP_addr}') xhr.setRequestHeader('hashkey','{Hash값}') xhr.setRequestHeader('gt_uid','{Global UID}') xhr.onreadystatechange = function () { if (this.readyState == 4) { console.log('Status : ' + this.status + '\nHeaders:' + JSON.stringify(this.getAllResponseHeaders()) + '\Body :' + this.responseText); } }; xhr.send('{\n' + ' "CANO": "종합계좌번호",\n' + ' "ACNT_PRDT_CD": "계좌상품코드",\n' + ' "ACNT_PWD": "계좌비밀번호",\n' + ' "PDNO": "상품번호",\n' + ' "ORD_UNPR": "주문단가",\n' + ' "ORD_DVSN": "주문구분",\n' + ' "CMA_EVLU_AMT_ICLD_YN": "CMA평가금액포함여부",\n' + ' "OVRS_ICLD_YN": "해외포함여부"\n' + '}');
Python
Python Code
# requests 모듈 설치 필요 (pip install requests) import requests url = 'https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/trading/inquire-daily-ccld' params = { "CANO": "종합계좌번호", "ACNT_PRDT_CD": "계좌상품코드", "INQR_STRT_DT": "조회시작일자", "INQR_END_DT": "조회종료일자", "SLL_BUY_DVSN_CD": "매도매수구분코드", "INQR_DVSN": "조회구분", "PDNO": "상품번호", "CCLD_DVSN": "체결구분", "ORD_GNO_BRNO": "주문채번지점번호", "ODNO": "주문번호", "INQR_DVSN_3": "조회구분3", "INQR_DVSN_1": "조회구분1", "CTX_AREA_FK100": "연속조회검색조건100", "CTX_AREA_NK100": "연속조회키100" } headers = { "Content-Type": "application/json", "authorization": "Bearer {TOKEN}", "appKey": "{Client_ID}", "appSecret": "{Client_Secret}", "personalSeckey": "{personalSeckey}", "tr_id": "TTTC8001R", "tr_cont": " ", "custtype": "법인(B), 개인(P)", "seq_no": "법인(01), 개인( )", "mac_address": "{Mac_address}", "phone_num": "P01011112222", "ip_addr": "{IP_addr}", "hashkey": "{Hash값}", "gt_uid": "{Global UID}" } res = requests.get(url, params=params, headers=headers) rescode = res.status_code if rescode == 200: print(res.headers) print(str(rescode) + " | " + res.text) else: print("Error Code : " + str(rescode) + " | " + res.text)
국내주식시세조회
REST
국내주식시세조회 API 구현 예제
Java
Java Code
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FHKST01010100 { public static void main(String[] args) throws IOException { // 국내 주식 시세 조회 String url = "https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/quotations/inquire-price"; String tr_id = "FHKST01010100"; String data = "?fid_cond_mrkt_div_code=J" + //FID 조건 시장 분류 코드 "&fid_input_iscd=000660"; //FID 입력 종목코드 httpGetConnection(url,data,tr_id); } public static void httpGetConnection(String UrlData, String ParamData,String TrId) throws IOException { String totalUrl = ""; totalUrl = UrlData.trim().toString(); URL url = null; HttpURLConnection conn = null; String responseData = ""; BufferedReader br = null; StringBuffer sb = new StringBuffer(); String returnData = ""; try{ url = new URL(totalUrl+ParamData); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("authorization", "Bearer {TOKEN}"); conn.setRequestProperty("appKey", "{Client_ID}"); conn.setRequestProperty("appSecret", "{Client_Secret}"); conn.setRequestProperty("personalSeckey", "{personalSeckey}"); conn.setRequestProperty("tr_id", TrId); conn.setRequestProperty("tr_cont", " "); conn.setRequestProperty("custtype", "법인(B), 개인(P)"); conn.setRequestProperty("seq_no", "법인(01), 개인( )"); conn.setRequestProperty("mac_address", "{Mac_address}"); conn.setRequestProperty("phone_num", "P01011112222"); conn.setRequestProperty("ip_addr", "{IP_addr}"); conn.setRequestProperty("hashkey", "{Hash값}"); conn.setRequestProperty("gt_uid", "{Global UID}"); conn.setDoOutput(true); conn.connect(); br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); } catch (IOException e){ br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); } finally { try { sb = new StringBuffer(); while ((responseData = br.readLine()) != null) { sb.append(responseData); } returnData = sb.toString(); String responseCode = String.valueOf(conn.getResponseCode()); System.out.println("http 응답 코드 : " + responseCode); System.out.println("http 응답 데이터 : " + returnData); if (br != null){ br.close(); } } catch (IOException e){ throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e); } } } }
Javascript
Javascript Code
var xhr = new XMLHttpRequest(); /* 국내주식 시세 조회 */ var url = 'https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/quotations/inquire-price'; xhr.open('GET',url+'?fid_cond_mrkt_div_code=J&fid_input_iscd=000660'); xhr.setRequestHeader('Content-Type','application/json') xhr.setRequestHeader('authorization','Bearer {TOKEN}') xhr.setRequestHeader('appKey','{Client_ID}') xhr.setRequestHeader('appSecret','{Client_Secret}') xhr.setRequestHeader('personalSeckey','{personalSeckey}') xhr.setRequestHeader('tr_id','FHKST01010100') xhr.setRequestHeader('tr_cont','') xhr.setRequestHeader('custtype','법인(B), 개인(P)') xhr.setRequestHeader('seq_no','법인(01), 개인( )') xhr.setRequestHeader('mac_address','{Mac_address}') xhr.setRequestHeader('phone_num','P01011112222') xhr.setRequestHeader('ip_addr','{IP_addr}') xhr.setRequestHeader('hashkey','{Hash값}') xhr.setRequestHeader('gt_uid','{Global UID}') xhr.onreadystatechange = function () { if (this.readyState == 4) { console.log('Status : ' + this.status + '\nHeaders:' + JSON.stringify(this.getAllResponseHeaders()) + '\Body :' + this.responseText); } }; xhr.send(null);
Python
샘플 코드에서 YOUR_CLIENT_ID 또는 YOUR-CLIENT-ID에는 애플리케이션을 등록하고 발급받은 클라이언트 아이디 값을 입력합니다. 샘플 코드에서 YOUR_CLIENT_SECRET 또는 YOUR-CLIENT-SECRET에는 애플리케이션을 등록하고 발급받은 클라이언트 시크릿 값을 입력합니다.
Python Code
# requests 모듈 설치 필요 (pip install requests) import requests url = 'https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/quotations/inquire-price' params = { "fid_cond_mrkt_div_code": "FID조건시장분류코드", "fid_input_iscd": "FID입력종목코드" } headers = { "Content-Type": "application/json", "authorization": "Bearer {TOKEN}", "appKey": "{Client_ID}", "appSecret": "{Client_Secret}", "personalSeckey": "{personalSeckey}", "tr_id": "FHKST01010100", "tr_cont": " ", "custtype": "법인(B), 개인(P)", "seq_no": "법인(01), 개인( )", "mac_address": "{Mac_address}", "phone_num": "P01011112222", "ip_addr": "{IP_addr}", "hashkey": "{Hash값}", "gt_uid": "{Global UID}" } res = requests.get(url, params=params, headers=headers) rescode = res.status_code if rescode == 200: print(res.headers) print(str(rescode) + " | " + res.text) else: print("Error Code : " + str(rescode) + " | " + res.text)
국내주식체결가(실시간)
Javascript Code
<title>WebSocket Test Page</title> <!-- crypto-js.min.js 들어갈자리, for use aes256 decode --> <!-- <script src="C:\cryptojs\crypto-js.min.js"></script> --> <script src=".\crypto-js.min.js"></script> <!-- 화면분할을 위한 div 처리 --> <style> div.row { width: 100%; display: flex; border: 1px solid #003458; } div.left { width: 300px; float: left; box-sizing: border-box; /* background: #FFF5EE; */ font-size: 12px; } div.middle { width: 300px; float: left; box-sizing: border-box; background: #ece6cc; } div.right { width: 300px; float: left; box-sizing: border-box; background: #ece6cc; } </style> <script> /** button action 시 stockcode 저장 전역변수 */ var stockcode1=""; var stockcode2=""; var htsid=""; var g_app_key="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // send data 용 app_key var g_appsecret="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; var g_personalseckey="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; var ping=0; var pingpong=0; // pingpong count /** AES256 DECODE IV, KEY 선언*****/ var encryptkey=''; var iv=''; /*** Start unicode replace step ********************************************************/ var escapable = /[\x00-\x1f\ud800-\udfff\u200c\u2028-\u202f\u2060-\u206f\ufff0-\uffff]/g; function filterUnicode(quoted) { escapable.lastIndex = 0; if (!escapable.test(quoted)) return quoted; return quoted.replace (escapable, function(a){ return ''; }); } /** End of unicode replace step ********************************************************/ /** start of aes256Decode function **********************/ function aes256Decode (secretKey, Iv, data) { console.log(""); console.log("[aes256Decode] : [start]"); console.log("[Key] : " + secretKey); console.log("[Iv] : " + Iv); console.log("[Data] : " + data); const cipher = CryptoJS.AES.decrypt (data, CryptoJS.enc.Utf8.parse(secretKey), { iv: CryptoJS.enc.Utf8.parse(Iv), padding: CryptoJS.pad.Pkcs7, mode: CryptoJS.mode.CBC }); aes256DecodeData = cipher.toString(CryptoJS.enc.Utf8); console.log("[aes256Decode] : [decode]"); console.log("[data] : "+aes256DecodeData); console.log(""); return aes256DecodeData; }; /** end of aes256Decode function **********************/ // output log print var log = function(s,f) { //console.log(s); if (document.readyState !== "complete") { log.buffer.push(s); }else { if (f == 1) { document.getElementById("output").style.fontSize = "12px"; document.getElementById("output").innerHTML += (s + "\n"); } else if (f == 2) { document.getElementById("output_1").style.fontSize = "12px"; document.getElementById("output_1").innerHTML += (s + "\n"); } } } log.buffer = []; // output1 log print, color blue, red var log1 = function(a,s) { console.log(s); if (document.readyState !== "complete") { log1.buffer.push(s); }else { document.getElementById("output1").style.fontSize = "12px"; if (a == "02") { document.getElementById("output1").style.color = "red"; } else if (a == "01") { document.getElementById("output1").style.color = "blue"; } document.getElementById("output1").innerHTML += (s + "\n"); } } log1.buffer = []; var log2 = function(s, f) { console.log(s); if (document.readyState !== "complete") { log2.buffer.push(s); }else { if (f == 1) { document.getElementById("output2").style.fontSize = "12px"; document.getElementById("output2").innerHTML += (s + "\n"); } else if (f == 2) { document.getElementById("output2_1").style.fontSize = "12px"; document.getElementById("output2_1").innerHTML += (s + "\n"); } } } log2.buffer = []; var log3 = function(s) { console.log(s); if (document.readyState !== "complete") { log3.buffer.push(s); }else { document.getElementById("output3").style.fontSize = "12px"; document.getElementById("output3").innerHTML += (s + "\n"); } } log3.buffer = []; // ws 접속용 websocket try { //url = "ws://ops.koreainvestment.com:31000"; //모의투자 url = "ws://ops.koreainvestment.com:21000"; w = new WebSocket(url); } catch (e) { log(e); } // websocket standby w.onopen = function() { log3("[Connection OK]"); log3("[OPS(WebSocket) Test Ready.]"); } // websocket close w.onclose = function(e) { log3("[CONNECTION CLOSED]"); } w.onmessage = function(e) { var recvdata = filterUnicode(e.data); console.log ("<<---"+recvdata); // 첫데이터가 0이나 1일경우 (암호화 여부) if (recvdata[0] == 0|| recvdata[0] == 1) { var strArray = recvdata.split('|'); // 구분자로 문자열 자르기 var trid = strArray[1]; // trid array var bodydata = (strArray[3]); // receve data if (trid == "H0STCNT0" || trid == "K0STCNT0") { console.log (bodydata); } { /** aes256Decode Step **/ if (strArray[0] == 1) { // aes256Decode function 을 사용해 key, iv, 암호화데이터를 넘겨 decode를 한다 var decodedata = aes256Decode (encryptkey, iv, bodydata); if (trid == "K0STCNI0" || trid == "K0STCNI9" ||trid == "H0STCNI0" || trid == "H0STCNI9") // 주식체결통보, 모의투자체결통보 step { var i=0; var objectlist="고 객 I D ,계 좌 번 호 ,주 문 번 호 ,원주문 번 호 ,매도매수 구분 ,정 정 구 분 ,주 문 종 류 ,주 문 조 건 ,주식단축종목코드 ,체 결 수 량 ,체 결 단 가 ,주식체결 시간 ,거 부 여 부 ,체 결 여 부 ,접 수 여 부 ,지 점 번 호 ,계 좌 명 ,주 문 수 량 ,주 문 가 격 ,체결 종목명 ,신 용 구 분 ,신용 대출일자 ,체결종목명40 "; var arrObject = objectlist.split(','); // 메뉴리스트를 ','으로 잘라서 array 에 할당 한다. var strResult = decodedata.split('^'); // result data 의 구분자가 '^'이므로 해당 값으로 split 한다. document.getElementById("output1").innerHTML = (""); // output1 screen clear console.log(strResult[4]); log1(strResult[4],""); log1(strResult[4],""); log1(strResult[4],"===================================="); for (i=0;i<strResult.length;i++) { log1(strResult[4],arrObject[i]+"["+strResult[i]+"]"); } } } else if (strArray[0] == 0) { // 암호화 미처리 step if (trid == "H0STASP0") { // 주식호가 var strResult = bodydata.split('^'); var screenflag = 0; if (stockcode1 == strResult[ 0]) { screenflag = 1; document.getElementById("output").innerHTML = (""); // screen clear } else if (stockcode2 == strResult[ 0]) { screenflag = 2; document.getElementById("output_1").innerHTML = (""); // screen clear } log("유가증권 단축 종목코드 ["+strResult[ 0]+"]", screenflag); log("영업 시간["+strResult[ 1]+"]"+"시간 구분 코드["+strResult[ 2]+"]", screenflag); log("====================================", screenflag); log("매도호가10["+strResult[12]+"]"+" 잔량10["+strResult[32]+"]", screenflag); log("매도호가09["+strResult[11]+"]"+" 잔량09["+strResult[31]+"]", screenflag); log("매도호가08["+strResult[10]+"]"+" 잔량08["+strResult[30]+"]", screenflag); log("매도호가07["+strResult[ 9]+"]"+" 잔량07["+strResult[29]+"]", screenflag); log("매도호가06["+strResult[ 8]+"]"+" 잔량06["+strResult[28]+"]", screenflag); log("매도호가05["+strResult[ 7]+"]"+" 잔량05["+strResult[27]+"]", screenflag); log("매도호가04["+strResult[ 6]+"]"+" 잔량04["+strResult[26]+"]", screenflag); log("매도호가03["+strResult[ 5]+"]"+" 잔량03["+strResult[25]+"]", screenflag); log("매도호가02["+strResult[ 4]+"]"+" 잔량02["+strResult[24]+"]", screenflag); log("매도호가01["+strResult[ 3]+"]"+" 잔량01["+strResult[23]+"]", screenflag); log("------------------------------------", screenflag); log("매수호가01["+strResult[13]+"]"+" 잔량01["+strResult[33]+"]", screenflag); log("매수호가02["+strResult[14]+"]"+" 잔량02["+strResult[34]+"]", screenflag); log("매수호가03["+strResult[15]+"]"+" 잔량03["+strResult[35]+"]", screenflag); log("매수호가04["+strResult[16]+"]"+" 잔량04["+strResult[36]+"]", screenflag); log("매수호가05["+strResult[17]+"]"+" 잔량05["+strResult[37]+"]", screenflag); log("매수호가06["+strResult[18]+"]"+" 잔량06["+strResult[38]+"]", screenflag); log("매수호가07["+strResult[19]+"]"+" 잔량07["+strResult[39]+"]", screenflag); log("매수호가08["+strResult[20]+"]"+" 잔량08["+strResult[40]+"]", screenflag); log("매수호가09["+strResult[21]+"]"+" 잔량09["+strResult[41]+"]", screenflag); log("매수호가10["+strResult[22]+"]"+" 잔량10["+strResult[42]+"]", screenflag); log("====================================", screenflag); log("총매도호가 잔량 ["+strResult[43]+"]", screenflag); log("총매도호가잔량증감 ["+strResult[54]+"]", screenflag); log("총매수호가 잔량 ["+strResult[44]+"]", screenflag); log("총매수호가잔량증감 ["+strResult[55]+"]", screenflag); log("시간외 총매도호가 잔량["+strResult[45]+"]", screenflag); log("시간외 총매도호가증감 ["+strResult[56]+"]", screenflag); log("시간외 총매수호가 잔량["+strResult[46]+"]", screenflag); log("시간외 총매수호가증감 ["+strResult[57]+"]", screenflag); log("예상체결가 ["+strResult[47]+"]", screenflag); log("예상체결량 ["+strResult[48]+"]", screenflag); log("예상거래량 ["+strResult[49]+"]", screenflag); log("예상체결 대비 ["+strResult[50]+"]", screenflag); log("부호 ["+strResult[51]+"]", screenflag); log("예상체결 전일대비율 ["+strResult[52]+"]", screenflag); log("누적거래량 ["+strResult[53]+"]", screenflag); log("주식매매 구분코드 ["+strResult[58]+"]", screenflag); } else if (trid == "H0STCNT0" || trid == "K0STCNT0") { //주식체결가 //document.getElementById("output2").innerHTML = (""); // screen clear var objectlist = "유가증권단축종목코드 ,주식체결시간 ,주식현재가 ,전일대비부호 ,전일대비 ,전일대비율 ,가중평균주식가격 ,주식시가 ,주식최고가 ,주식최저가 ,매도호가1 ,매수호가1 ,체결거래량 ,누적거래량 ,누적거래대금 ,매도체결건수 ,매수체결건수 ,순매수 체결건수 ,체결강도 ,총 매도수량 ,총 매수수량 ,체결구분 ,매수비율 ,전일 거래량대비등락율 ,시가시간 ,시가대비 구분 ,시가대비 ,최고가 시간 ,고가대비구분 ,고가대비 ,최저가시간 ,저가대비구분 ,저가대비 ,영업일자 ,신 장운영 구분코드 ,거래정지 여부 ,매도호가잔량 ,매수호가잔량 ,총 매도호가잔량 ,총 매수호가잔량 ,거래량 회전율 ,전일 동시간 누적거래량 ,전일 동시간 누적거래량 비율,시간구분코드 ,임의종료구분코드 ,정적VI발동기준가 "; var strResult = bodydata.split('^'); // 주식체결가 구분값으로 분할해서 array 처리 var objectarray = objectlist.split(','); // objectlist를 구분값으러 분할해서 array처리, 항목명 // 어느쪽에 업데이트해야할지 종목코드로 판단한다. if (stockcode1 == strResult[ 0]) { screenflag = 1; document.getElementById("output2").innerHTML = (""); // screen clear } else if (stockcode2 == strResult[ 0]) { screenflag = 2; document.getElementById("output2_1").innerHTML = (""); // screen clear } var tot_loop_cnt = strArray[2]; // 주식 체결 건수 var k = 1; // 현재 표시 번호 log2("주식 체결 건수 ["+"00"+k+"/"+tot_loop_cnt+"]", screenflag); // 주식체결건수가 있어 모든데이터 활용시 분할해서 처리 필요 log2("", screenflag); // line feed log2("====================================", screenflag); var array_count = strResult.length; // array 의 총 갯수 console.log("array count:"+array_count); var nloopcount = array_count / tot_loop_cnt; // 1회당 총 출력 개수 console.log("objectarray.length:"+objectarray.length); var i = 0; var j = 0; // 체결건수가 1건 이상일 경우도 처리하도록 한다. for (i=0; i<array_count; i++) { // 항목갯수가 데이터의 1셋트 이므로 출력되는 데이터가 초과되면 데이터 1세트 출력 완료처리. if (j == objectarray.length) { if (stockcode1 == strResult[ 0]) { document.getElementById("output2").innerHTML = (""); // screen clear } else if (stockcode2 == strResult[ 0]) { document.getElementById("output2_1").innerHTML = (""); // screen clear } k += 1; log2("주식 체결 건수 ["+"00"+k+"/"+tot_loop_cnt+"]", screenflag); log2("", screenflag); log2("====================================", screenflag); j = 0; } //log2(objectarray[j]+objectarray[j].length+"["+strResult[i]+"]"); log2(objectarray[j]+"["+strResult[i]+"]", screenflag); j++; } } } } } else { // 첫데이터가 암호화 구분값이 아닌 데이터를 처리하기위한 step console.log("[RECV] < "+"["+recvdata.length+"] "+recvdata); const json = e.data; try { var obj = JSON.parse(json); var trid = obj.header.tr_id; var encyn = obj.header.encrypt; } catch (e) { log3(" ERROR : ["+e+"]"); } // key, iv set step, 들어온 데이터가 parsing 후 trid를 참조하여 전달받은 keyt, iv 값을 사용하기 위한처리, 체결통보의 경우에만 암호화 처리를 하므로 해당 trid만 처리하도록 한다. if (trid == 'K0STCNI0' || trid == 'H0STCNI0') { if (obj.body.msg1.includes("MAX SUBSCRIBE OVER")) { log3("[RECV] : 주식체결통보 등록요청 실패하하였습니다. MSG["+obj.body.msg1+"]"); alert("주식체결통보 등록초과 입니다."); } else { try { encryptkey = obj.body.output.key; iv = obj.body.output.iv; log3("[RECV] : 주식체결통보등록요청 성공하였습니다. (수신KEY ["+encryptkey+"]"+" 수신IV ["+iv+"] )"); log3(" : 체결통보 수신시 수신KEY와 수신IV를 참고로 데이터 복호화 처리함."); } catch(e) { log3(" ERROR : ["+e+"]"); } } } else if (trid == "PINGPONG") { // pingpong step ping+=1; //pingpong+=1; console.log ("pingpong ["+pingpong+"]"); /** pingpond 횟수가 5회 넘어가면 화면 reload 및 console clear 처리를 한다 */ if (pingpong == 5) { //console.clear(); pingpong = 0; //location.reload(); document.getElementById("output3").innerHTML = (""); } log3("[RECV] < "+"["+recvdata.length+"]"+recvdata+"["+ping+"]"); // 수신받은 pingpong 데이터를 send 하기위해 변수에 저장 var result = e.data; /** pingpong send stop **/ //w.send(result); //log3 ("[SEND] > "+"["+result.length+"] "+result); pingpong+=1; } else if (trid == "H0STCNT0" || trid == "K0STCNT0") { //성공실패 메세지 처리를 한다. if (obj.body.msg1.includes("UNSUBSCRIBE")) // 실패일경우 msg영역에 해당 메세지가 존재하므로 구분 { if (obj.body.msg1.includes("SUCCESS")) log3("[RECV] : 주식체결 등록요청해지 성공하였습니다."); else if (obj.body.msg1.includes("ERROR")) log3("[RECV] : 주식체결 등록요청해지 실패하였습니다. ["+obj.body.msg1+"]"); } else if (obj.body.msg1.includes("MAX SUBSCRIBE OVER")) { log3("[RECV] : 주식체결 등록요청 실패하하였습니다. MSG["+obj.body.msg1+"]"); alert("주식체결 등록초과 입니다."); } else { log3("[RECV] : 주식체결 등록요청 성공하였습니다."); } } else if (trid == "H0STASP0") { if (obj.body.msg1.includes("UNSUBSCRIBE")) { if (obj.body.msg1.includes("SUCCESS")) log3("[RECV] : 주식호가 등록요청해지 성공하였습니다."); else if (obj.body.msg1.includes("ERROR")) log3("[RECV] : 주식호가 등록요청해지 실패하였습니다. ["+obj.body.msg1+"]"); } else if (obj.body.msg1.includes("MAX SUBSCRIBE OVER")) { log3("[RECV] : 주식호가 등록요청 실패하하였습니다. MSG["+obj.body.msg1+"]"); alert("주식호가 등록초과 입니다."); } else { log3("[RECV] : 주식호가 등록요청 성공하였습니다."); } } } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } window.onload = function() { // 주식호가 등록 버튼 처리 document.getElementById("hokaregButton1").onclick = function() { var stockcode_tmp = document.getElementById("inputMessage1").value; if (stockcode_tmp == stockcode2 || stockcode_tmp == stockcode1) { alert("이미 등록된 종목코드 입니다."); } else { stockcode1 = stockcode_tmp; var result = '{"header": {"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"1","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STASP0","tr_key":"'+stockcode1+'"}}}'; log3("[SEND] : 주식호가1등록요청"); console.log("[SEND] > ["+result.length+"] "+result); //stockcode1=""; try { w.send(result); } catch(e) { log3(e); } } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식호가 등록해제1 버튼 처리 document.getElementById("hokaderegButton1").onclick = function() { stockcode1 = document.getElementById("inputMessage1").value; var result = '{"header": {"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"2","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STASP0","tr_key":"'+stockcode1+'"}}}'; stockcode1 = "" log3("[SEND] : 주식호가1등록해지요청"); console.log("[SEND] > ["+result.length+"] "+result); try { w.send(result); } catch(e) { log3(e); } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식호가 등록2 버튼 처리 document.getElementById("hokaregButton2").onclick = function() { var stockcode_tmp = document.getElementById("inputMessage2").value; if (stockcode_tmp == stockcode2 || stockcode_tmp == stockcode1) { alert("이미 등록된 종목코드 입니다."); } else { stockcode2 = stockcode_tmp; var result = '{"header": {"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"1","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STASP0","tr_key":"'+stockcode2+'"}}}'; log3("[SEND] : 주식호가2등록요청"); console.log("[SEND] > ["+result.length+"] "+result); try { w.send(result); } catch(e) { log3(e); } } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식호가 등록해제2 버튼 처리 document.getElementById("hokaderegButton2").onclick = function() { stockcode2 = document.getElementById("inputMessage2").value; var result = '{"header": {"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"2","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STASP0","tr_key":"'+stockcode2+'"}}}'; stockcode2 = "" log3("[SEND] : 주식호가2등록해지요청"); console.log("[SEND] > ["+result.length+"] "+result); try { w.send(result); } catch(e) { log3(e); } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식체결1 등록 버튼 처리 document.getElementById("bidregButton1").onclick = function() { //stockcode3 = document.getElementById("inputMessage3").value; stockcode1 = document.getElementById("inputMessage1").value; var result = '{"header":{"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"1","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STCNT0","tr_key":"'+stockcode1+'"}}}'; log3("[SEND] : 주식체결등록요청"); console.log("[SEND] > ["+result.length+"] "+result); //stockcode1=""; try { w.send(result); } catch(e) { log3(e); } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식체결1 등록해제 버튼 처리 document.getElementById("bidderegButton1").onclick = function() { //stockcode3 = document.getElementById("inputMessage3").value; stockcode1 = document.getElementById("inputMessage1").value; var result = '{"header":{"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"2","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STCNT0","tr_key":"'+stockcode1+'"}}}'; log3("[SEND] : 주식체결등록해지요청"); stockcode1=""; console.log("[SEND] > ["+result.length+"] "+result); try { w.send(result); } catch(e) { log3(e); } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식체결2 등록 버튼 처리 document.getElementById("bidregButton2").onclick = function() { stockcode2 = document.getElementById("inputMessage2").value; var result = '{"header":{"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"1","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STCNT0","tr_key":"'+stockcode2+'"}}}'; log3("[SEND] : 주식체결등록요청"); console.log("[SEND] > ["+result.length+"] "+result); try { w.send(result); } catch(e) { log3(e); } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식체결2 등록해제 버튼 처리 document.getElementById("bidderegButton2").onclick = function() { stockcode2 = document.getElementById("inputMessage2").value; var result = '{"header":{"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"2","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STCNT0","tr_key":"'+stockcode2+'"}}}'; log3("[SEND] : 주식체결등록해지요청"); console.log("[SEND] > ["+result.length+"] "+result); stockcode2=""; try { w.send(result); } catch(e) { log3(e); } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식체결통보 등록 버튼 처리 document.getElementById("bidalamButton").onclick = function() { htsid = document.getElementById("inputMessage_htsid").value; var result = '{"header": {"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"1","content-type":"utf-8"},"body": {"input": {"tr_id":"K0STCNI0","tr_key":"'+htsid+'"}}}'; log3("[SEND] : HTS ID ["+htsid+"] 주식체결통보등록요청"); console.log("[SEND] > ["+result.length+"] "+result); try { w.send(result); } catch(e) { log3(e); } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식체결통보 등록해제 버튼 처리 document.getElementById("xbidalamButton").onclick = function() { var result = '{"header": {"authoriztion":"","appkey":"'+g_app_key+'","appsecret":"'+g_appsecret+'","personalseckey":"'+g_personalseckey+'","custtype":"P","tr_type":"2","content-type":"utf-8"},"body": {"input": {"tr_id":"H0STCNI0","tr_key":"'+htsid+'"}}}'; log3("[SEND] : HTS ID ["+htsid+"] 주식체결등록통보해지요청"); console.log("[SEND] > ["+result.length+"] "+result); try { w.send(result); } catch(e) { log3(e); } document.getElementById("output3").scrollTop = document.getElementById("output3").scrollHeight; } // 주식체결통보 등록해제 버튼 처리 document.getElementById("closeButton").onclick = function() { w.close(); } // 에러 메세지 처리 w.onerror = function(e) { log3(e); } } </script> <!-- 화면분할을 위한 div 처리 --> <!-- output3, command box --> <div style="background-color:#EEEEEE"> <pre id="output3" style="width: 100%; height: 10%; overflow: auto;"></pre> </div> <!-- output, 주식호가1 box --> <div class="left" style="background-color:#FFF5EE"> <input type="text" id="inputMessage1" style="width: 180px; height: 20px" value="005930"><br> <button id="hokaregButton1" style="width: 80px; height: 20px; font-size: 12px">주식호가</button><button id="hokaderegButton1" style="width: 100px; height: 20px; font-size: 12px">주식호가해제</button><button id="closeButton" style="width: 100px; height: 20px; font-size: 12px">연결해제</button> <pre id="output" style="width: 100%; height: 100%; overflow: auto;"></pre> </div> <!-- output, 주식체결1 box --> <div class="right" style="background-color:#FFFFFF"> <!-- <input type="text" id="inputMessage3" value="005930"> --> <br> <button id="bidregButton1" style="width: 80px; height: 20px; font-size: 12px">주식체결</button><button id="bidderegButton1" style="width: 100px; height: 20px; font-size: 12px">주식체결해제</button> <pre id="output2" style="width: 100%; height: 100%; overflow: auto;"></pre> </div> <!-- output, 주식호가2 box --> <div class="left" style="background-color:#FFF5EE"> <input type="text" id="inputMessage2" style="width: 180px; height: 20px font-size: 12px" value="000660"><br> <button id="hokaregButton2" style="width: 80px; height: 20px; font-size: 12px">주식호가</button><button id="hokaderegButton2" style="width: 100px; height: 20px; font-size: 12px">주식호가해제</button> <pre id="output_1" style="width: 100%; height: 100%; overflow: auto;"></pre> </div> <!-- output, 주식체결2 box --> <div class="right" style="background-color:#FFFFFF"> <!-- <input type="text" id="inputMessage4" value="000660"> --><br> <button id="bidregButton2" style="width: 80px; height: 20px; font-size: 12px">주식체결</button><button id="bidderegButton2" style="width: 100px; height: 20px; font-size: 12px">주식체결해제</button> <pre id="output2_1" style="width: 100%; height: 100%; overflow: auto;"></pre> </div> <!-- output, 주식체결통보 box --> <div class="middle"> <input type="text" id="inputMessage_htsid" style="width: 180px; height: 20px" value="101334"><br> <button id="bidalamButton" style="width: 100px; height: 20px; font-size: 12px">주식체결통보</button><button id="xbidalamButton" style="width: 120px; height: 20px; font-size: 12px">주식체결통보해제</button> <pre id="output1" style="width: 100%; height: 100%; overflow: auto;"></pre> </div>