Skip to main content

Programgarden Finance

Programgarden Finance는 AI 시대에 맞춰 파이썬을 모르는 투자자도 개인화된 시스템 트레이딩을 자동으로 수행할 수 있게 돕는 오픈소스입니다. 본 라이브러리는 LS증권 OpenAPI를 간소화하여 국내 주식, 해외 주식, 해외 선물옵션 거래를 쉽게 자동화할 수 있도록 설계되었습니다.

비전공 투자자도 사용하기 쉽도록 설계되었으며, 동시성, 증권 데이터 업데이트 등의 백그라운드 작업은 Program Garden에서 관리하고 있으므로 투자자는 손쉽게 사용만 하면 됩니다.

주요 특징

  • 간편한 LS증권 API 통합: LS증권 OpenAPI의 복잡한 스펙을 간소화하여 몇 줄의 코드로 시작 가능
  • 국내 주식 · 해외 주식 · 선물옵션 지원: 국내 주식(88 TR), 해외 주식, 해외 선물옵션 시장의 실시간 데이터 조회, 주문, 잔고 관리 등 통합 지원
  • 실시간 WebSocket 스트리밍: 실시간 시세, 체결, 호가 데이터를 WebSocket으로 간편하게 구독 가능
  • 비동기 처리: 모든 API 요청은 비동기와 동기로 분리하여 처리해서 높은 성능과 동시성 제공
  • 토큰 자동 관리: OAuth 토큰 발급 및 갱신을 자동으로 처리하여 인증 관리 부담 최소화
  • 타입 안전성: Pydantic 기반의 타입 검증으로 IDE 친화적이고 안전한 코드 작성 지원
  • 풍부한 예제: example/ 폴더에 국내 주식, 해외 주식, 선물옵션 각 기능별 실행 가능한 예제 제공

설치

Stock account tracking retains a separate, complete COSOQ00201 valuation snapshot with gains, losses and net PnL by currency. This uses the existing balance refresh; broker amounts remain separate from mutable tick estimates and realized trades.

Futures account PnL now carries explicit currency, gross-estimate basis and availability. Broker-reported amounts are retained separately; mixed or unsupported scalar totals are nullable. See the futures PnL currency contract for the USD estimator compatibility boundary and consumer requirements.

The CIDBQ03000 snapshot reference records the supplied field metadata and two actual paper balance reads, including their date and accounting limits. Reported equity and its P&L/fee components must not be added twice.

Futures tracking also retains a whitelisted per-currency account snapshot from that same query, including owner-confirmed daily net cash flows. Missing evidence and broker dates stay unknown; aggregate targets remain separate. This is a collection contract, not a published adjusted-return series.

Domestic source-contract update: every CSPAQ12300OutBlock2 field is not provided, including explicit zero/empty broker placeholders. Its schema and response.block2_status expose that restriction. Use separately observed position evidence, preserve average-versus-BEP request basis and field presence, and consult the CSPAQ12300 contract. The FOCCQ33600 reference retains official example discrepancies and actual dated observations without assuming product coverage, current-day availability or an undocumented return formula.

# PyPI에 게시된 경우
pip install programgarden-finance

# Poetry 사용 시 (개발 환경)
poetry add programgarden-finance

요구 사항: Python 3.12+

빠른 시작

1. 토큰 발급

LS증권 API를 사용하려면 먼저 OAuth 토큰을 발급받아야 합니다.

import asyncio
from programgarden_finance import LS
from programgarden_finance.ls.oauth.generate_token import GenerateToken
from programgarden_finance.ls.oauth.generate_token.token.blocks import TokenInBlock

async def get_token():
    response = GenerateToken().token(
        TokenInBlock(
            appkey="YOUR_APPKEY",
            appsecretkey="YOUR_APPSECRET",
        )
    )
    result = await response.req_async()
    print(f"Access Token: {result.block.access_token}")

asyncio.run(get_token())

2. 해외 주식 현재가 조회

import asyncio
from programgarden_finance import LS, g3101

async def get_stock_price():
    ls = LS()

    # 로그인 (발급받은 App Key / App Secret 입력)
    if not ls.login(
        appkey="발급받은 App Key",
        appsecretkey="발급받은 App Secret"
    ):
        print("로그인 실패")
        return

    # TSLA 현재가 조회
    result = ls.overseas_stock().market().현재가조회(
        g3101.G3101InBlock(
            delaygb="R",
            keysymbol="82TSLA",
            exchcd="82",
            symbol="TSLA"
        )
    )

    response = await result.req_async()
    print(f"TSLA 현재가: {response}")

asyncio.run(get_stock_price())

3. 실시간 시세 구독 (WebSocket)

import asyncio
from programgarden_finance import LS

async def subscribe_realtime():
    ls = LS()

    if not ls.login(
        appkey="발급받은 App Key",
        appsecretkey="발급받은 App Secret"
    ):
        print("로그인 실패")
        return

    # 실시간 데이터 콜백
    def on_message(resp):
        print(f"실시간 데이터: {resp}")

    # WebSocket 연결
    client = ls.overseas_stock().real()
    await client.connect()

    # GSC(해외주식 실시간 시세) 구독
    gsc = client.GSC()
    gsc.add_gsc_symbols(symbols=["81SOXL", "82TSLA"])
    gsc.on_gsc_message(on_message)

asyncio.run(subscribe_realtime())

4. 해외 선물옵션 마스터 조회

import asyncio
from programgarden_finance import LS, o3101

async def get_futures_master():
    ls = LS()

    if not ls.login(
        appkey="발급받은 App Key (선물용)",
        appsecretkey="발급받은 App Secret (선물용)"
    ):
        print("로그인 실패")
        return

    # 해외선물 마스터 조회
    result = ls.overseas_futureoption().market().해외선물마스터조회(
        body=o3101.O3101InBlock(gubun="1")
    )

    response = await result.req_async()
    print(response)

asyncio.run(get_futures_master())

5. 국내 주식 현재가 조회

import asyncio
from programgarden_finance import LS, t1102

async def get_korea_stock_price():
    ls = LS()

    if not ls.login(
        appkey="발급받은 App Key",
        appsecretkey="발급받은 App Secret"
    ):
        print("로그인 실패")
        return

    # 삼성전자 현재가 조회
    result = ls.korea_stock().market().주식현재가(
        t1102.T1102InBlock(shcode="005930")
    )

    response = await result.req_async()
    print(f"삼성전자 현재가: {response}")

asyncio.run(get_korea_stock_price())

주요 모듈 구조

LS 클래스

LS증권 API의 진입점이 되는 메인 클래스입니다.

from programgarden_finance import LS

ls = LS()
ls.login(appkey="...", appsecretkey="...")

# 국내 주식 API
korea = ls.korea_stock()
korea.market()    # 시장 정보 조회
korea.chart()     # 차트 데이터 조회
korea.accno()     # 계좌 정보 조회
korea.order()     # 주문 처리
korea.real()      # 실시간 데이터

# 해외 주식 API
stock = ls.overseas_stock()
stock.market()    # 시장 정보 조회
stock.chart()     # 차트 데이터 조회
stock.accno()     # 계좌 정보 조회
stock.order()     # 주문 처리
stock.real()      # 실시간 데이터

# 해외 선물옵션 API
futures = ls.overseas_futureoption()
futures.market()  # 시장 정보 조회
futures.chart()   # 차트 데이터 조회
futures.accno()   # 계좌 정보 조회
futures.order()   # 주문 처리
futures.real()    # 실시간 데이터

제공되는 주요 TR 코드

국내 주식 (88 TR)

  • 시장 정보: t9945(마스터), t8450(호가), t1101(호가), t1102(현재가), t1104(현재가시세메모), t1105(피봇/디마크), t1301(체결), t1302(분별주가), t1305(기간별주가), t1308(시간대별체결챠트), t1310(당일전일분틱), t1410(초저유동성), t1427(상/하한가직전), t1449(가격대별매매비중), t1471(시간별체결), t1475(체결), t1486(시간별예상체결가), t1488(예상체결가등락율상위), t8407(복수종목시세), t8454(멀티현재가), t1404/t1405(프로그램매매), t1422/t1442(관리/이상종목)
  • 계좌: CSPAQ22200(예수금), CSPAQ12200(잔고), CSPAQ12300(잔고상세), CSPAQ13700(order/execution history), CDPCQ04700(투자가능금액), FOCCQ33600(증거금), CSPAQ00600(credit/margin limits), CSPBQ00200(평가손익), t0424(잔고2), t0425(종목별잔고)
  • 주문: CSPAT00601(현물주문), CSPAT00701(정정), CSPAT00801(취소)
  • 랭킹: t1441(등락률), t1444(시가총액), t1452(거래량), t1463(거래대금), t1466(전일동시간비), t1481(급등락), t1482(신고/신저)
  • 차트: t8451(일주월년봉), t8452(분봉), t8453(틱봉), t1665(종합차트)
  • 업종(indtp): 시세 t1511(업종현재가), t1514(업종기간별추이), t1516(업종별종목시세)(/indtp/market-data) + 차트 t8408(업종차트틱), t8409(업종차트분)(/indtp/chart) — ls.indtp()/ls.업종()으로 이전
  • 테마: t1531(테마별종목), t1532(종목별테마), t1537(테마종목별시세) — ls.국내주식().업종테마()(/stock/sector)
  • 투자자: t1601~t1621(투자자매매동향), t1664(투자자매매추이), t1702(외인/기관)
  • ETF: t1901(ETF시세), t1903(ETF일별추이), t1904(ETF구성종목)
  • 기타: t1403(신규상장), t1638(신용거래), t1927(공매도), t1941(종목별프로그램)
  • 실시간: S3_(체결), K3_(KOSDAQ체결), H1_(호가), HA_(KOSDAQ호가), NH1(NXT호가), IJ_(업종지수), DVI/NVI(VI발동해제), SC0~SC4(주문접수/체결/정정/취소/거부)

해외 주식

  • 시장 정보: g3101(현재가), g3102(해외지수), g3104(거래소마스터), g3106(환율), g3190(뉴스)
  • 차트: g3103(일별), g3202(분봉), g3203(틱봉), g3204(시간외)
  • 계좌: COSAQ00102(주문체결내역), COSAQ01400(예약주문처리결과), COSOQ00201(종합잔고평가), COSOQ02701(외화예수금/주문가능금액)
  • 주문: COSAT00301(정정주문), COSAT00311(신규주문), COSMT00300(취소주문), COSAT00400(예약주문)
  • 실시간: GSC(체결), GSH(호가), AS0~AS4(각종 실시간 시세)

해외 선물옵션

  • 시장 정보: o3101(선물마스터), o3104o3107(거래소/통화/가격단위/정산환율), o3116(옵션마스터), o3121o3128(각종 시장 정보), o3136, o3137(추가 시장 정보)
  • 차트: o3103(일별), o3108(분봉), o3117(틱봉), o3139(시간외)
  • 계좌: CIDBQ01400(orderable quantity), CIDBQ01500(잔고), CIDBQ01800(체결내역), CIDBQ02400(order execution detail), CIDBQ03000(deposit/balance status), CIDBQ05300(evaluated deposit totals), CIDEQ00800(예탁증거금)
  • 주문: CIDBT00100(신규), CIDBT00900(정정), CIDBT01000(취소)
  • 실시간: OVC(체결), OVH(호가), TC1~TC3, WOC, WOH(각종 실시간 데이터)

응답 코드 참조

Observed overseas futures paper responses

The local execution parser separates positive CIDBQ02400 execution observations from unresolved source issues, preserving independent dates and milliseconds without an implicit timezone.

The CIDBQ02400 field contract records the supplied LS execution-detail table: blank dates for same-day queries, ExecDttm as the execution timestamp, dated order identity, field lengths/scales, and the published table/example inconsistencies. It preserves unknown codes without inventing accounting behavior.

CIDBT00100 returned HTTP 200 / 01425 with the original message 모의투자 주문가능금액이 부족합니다. and no order identifier during a 2026-09-09 paper order. See observed broker responses for the exact request context, message provenance, and subsequent CIDBQ01400.OrdAbleQty observations. These are TR/account-specific observations, not a universal success-code rule or a fill guarantee.

국내 주식 주문 (CSPAT00601 / CSPAT00701 / CSPAT00801)

rsp_cd 의미 분류
00040 매수주문 정상 접수 (모의/실전) 성공 (매수 전용)
00039 매도주문 정상 접수 (모의/실전) 성공 (매도 전용)
01478 매도가능수량 부족 거부 (LS 측 잔고 검증)
IGW00201 호출 거래건수 초과 시스템 (재시도 가능)

Response codes are TR-specific: the domestic new-order example below expects 00040 for buys and 00039 for sells, while the observed paper CIDBQ01400 quantity query returned 00136 with valid output. Do not use rsp_cd == "00000" as a universal success rule or reuse this new-order example to classify modification/cancellation responses. Check the expected response blocks and identifiers as well as the code and original message.

# 권장 주문 성공 판정
expected = "00040" if is_buy else "00039"
if (resp.error_msg is None
    and resp.status_code == 200
    and resp.rsp_cd == expected
    and resp.block2 is not None
    and resp.block2.OrdNo > 0):
    # 성공 — resp.block2.OrdNo (int) 를 str 캐스팅하여 SC1.body.ordno 와 매칭
    track_order(str(resp.block2.OrdNo))

성공 시 resp.block2.OrdNo 를 SC1 (주식주문체결) 실시간 이벤트로 추적합니다. 예제: example/korea_stock/run_CSPAT00601_with_SC1.py.

호출 한도 응답 (IGW00201)

라이브러리는 예외 대신 다음 필드로 반환합니다:

필드 정상 (HTTP 200) 한도 초과 빈 데이터
status_code 200 500 200
rsp_cd "00000" "IGW00201" "00000"
error_msg None "HTTP 500: ..." None
block1 data [] []

→ "빈 데이터" 와 "한도 초과" 는 status_code / error_msg 로 구분합니다. 모든 Korea Stock TR 은 라이브러리 내부 on_rate_limit="wait" + 공유 rate_limit_key 로 자동 throttle 되므로, 사용자가 직접 LS 한도를 초과하는 매우 드문 경우에만 IGW00201 이 노출됩니다.

예제 코드

example/ 폴더에 다양한 실행 가능한 예제가 포함되어 있습니다.

예제 폴더 구조

example/
├── token/                      # OAuth 토큰 발급 예제
│   └── run_token.py
├── korea_stock/                # 국내 주식 예제
│   ├── run_t1102.py           # 현재가 조회
│   ├── run_CSPAT00601.py      # 현물 주문
│   ├── run_CSPAQ12200.py      # 잔고 조회
│   ├── real_S3_.py            # 실시간 체결 (KOSPI)
│   ├── real_SC1.py            # 실시간 주문 체결
│   ├── run_account_tracker.py # 계좌 추적 통합
│   └── ...                    # 총 74개 예제
├── overseas_stock/             # 해외 주식 예제
│   ├── run_g3101.py           # 현재가 조회
│   ├── run_g3102.py           # 해외지수 조회
│   ├── run_COSAT00311.py      # 신규주문
│   ├── real_GSC.py            # 실시간 체결 구독
│   ├── real_GSH.py            # 실시간 호가 구독
│   └── ...
└── overseas_futureoption/      # 해외 선물옵션 예제
    ├── run_o3101.py           # 선물마스터 조회
    ├── run_CIDBT00100.py      # 신규주문
    ├── real_OVC.py            # 실시간 체결 구독
    ├── real_OVH.py            # 실시간 호가 구독
    └── ...

예제 실행 방법

  1. LS증권에서 API 키(App Key, App Secret)를 발급받습니다.
  2. 각 예제 파일의 appkey, appsecretkey 부분에 발급받은 키를 입력합니다.
  3. 예제를 실행합니다:
# 국내 주식 현재가 조회
python example/korea_stock/run_t1102.py

# 해외 주식 현재가 조회
python example/overseas_stock/run_g3101.py

# 해외 선물 마스터 조회
python example/overseas_futureoption/run_o3101.py

# 실시간 시세 구독
python example/overseas_stock/real_GSC.py

API 참조

패키지 루트에서 주요 심볼들을 재노출합니다:

from programgarden_finance import (
    # 메인 클래스
    LS,

    # 모듈
    oauth,
    TokenManager,
    overseas_stock,
    overseas_futureoption,
    korea_stock,

    # 국내 주식 TR
    t9945, t8450, t1101, t1102, t1301,         # 시장 정보
    t1471, t1475, t8407, t8454,                 # 시장 정보
    t1403, t1404, t1405, t1422, t1442,         # 시장 정보
    CSPAQ22200, CSPAQ12200, CSPAQ12300,        # 계좌
    CSPAQ13700, CDPCQ04700, FOCCQ33600,        # 계좌
    CSPAQ00600, CSPBQ00200, t0424, t0425,      # 계좌
    CSPAT00601, CSPAT00701, CSPAT00801,        # 주문
    t1441, t1444, t1452, t1463, t1466,         # 랭킹
    t1481, t1482,                               # 랭킹
    t8451, t8452, t8453, t1665,                 # 차트
    t1511, t1514, t1516, t8408, t8409,          # 업종(indtp, ls.업종())
    t1531, t1532, t1537,                        # 테마(ls.국내주식().업종테마())
    t1601, t1602, t1603, t1617, t1621, t1664,  # 투자자
    t1702,                                      # 외인/기관
    t1901, t1903, t1904,                        # ETF
    t1638, t1927, t1941,                        # 기타
    S3_, K3_, H1_, HA_, NH1, IJ_,              # 실시간 시세
    DVI, NVI,                                   # 실시간 VI
    SC0, SC1, SC2, SC3, SC4,                   # 실시간 주문

    # 해외 주식 TR
    g3101, g3102, g3103, g3104, g3106, g3190,  # 시장/차트
    g3202, g3203, g3204,                        # 차트
    COSAQ00102, COSAQ01400,                     # 주문체결/예약주문
    COSOQ00201, COSOQ02701,                     # 종합잔고/외화예수금
    COSAT00301, COSAT00311,                     # 주문
    COSMT00300, COSAT00400,                     # 취소/예약
    GSC, GSH, AS0, AS1, AS2, AS3, AS4,         # 실시간

    # 해외 선물옵션 TR
    o3101, o3104, o3105, o3106, o3107,         # 시장 정보
    o3116, o3121, o3123, o3125, o3126,         # 시장 정보
    o3127, o3128, o3136, o3137,                # 시장 정보
    o3103, o3108, o3117, o3139,                # 차트
    CIDBQ01400, CIDBQ01500, CIDBQ01800,        # 계좌
    CIDBQ02400, CIDBQ03000, CIDBQ05300,        # 계좌
    CIDEQ00800,                                 # 계좌
    CIDBT00100, CIDBT00900, CIDBT01000,        # 주문
    OVC, OVH, TC1, TC2, TC3, WOC, WOH,         # 실시간

    # 예외 처리
    exceptions,
)

NXT trade ticks

ls.korea_stock().real().NS3() exposes NXT quotes on the shared socket. NS3 source and availability contract and read-only example. This is quote support.

The existing CSPAT00601InBlock1.MbrNo="NXT" routes a direct SDK order to NXT. The NXT limit-order preview copies the supplied LS request and performs no login or submission when run. See the source contract for scope and response-presence rules. Workflow-node integration, live fills and SC1 venue evidence remain pending.

python example/korea_stock/run_t9945.py --nxt-only performs read-only master queries and displays observed NXT eligibility. Missing flags remain unknown; current session, halt state and executable prices require separate checks.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

programgarden_finance-1.10.0.tar.gz (499.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

programgarden_finance-1.10.0-py3-none-any.whl (1.0 MB view details)

Uploaded Python 3

File details

Details for the file programgarden_finance-1.10.0.tar.gz.

File metadata

  • Download URL: programgarden_finance-1.10.0.tar.gz
  • Upload date:
  • Size: 499.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.4.1 CPython/3.12.13 Darwin/25.6.0

File hashes

Hashes for programgarden_finance-1.10.0.tar.gz
Algorithm Hash digest
SHA256 c51c37899496f70d5de2a4f0b9c70d43016d13f57085d8919604d216a4ba2b55
MD5 c61087247d1fa0bb07ea311f365e9fbd
BLAKE2b-256 c0c13ac37320d838470ce07863d3a9250682ea06457e75ecdff28885b1c2fe58

See more details on using hashes here.

File details

Details for the file programgarden_finance-1.10.0-py3-none-any.whl.

File metadata

File hashes

Hashes for programgarden_finance-1.10.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1ce21071a834622420e14d36e9b20027513fa19084ff7e51326b6dcf853fb1ab
MD5 0de4c24b3d109fb3dc46138d449177cc
BLAKE2b-256 daea9d6179d56a2cc10db312eb028ff5252c17e44a8c347a89224aaa21715f48

See more details on using hashes here.

Release history Release notifications | RSS feed

1.10.5

2 files

1.10.3

2 files

1.10.2

2 files

1.10.1

2 files

This release

1.10.0 This release

2 files

1.9.9

2 files

1.9.8

2 files

1.9.7

2 files

1.9.6

2 files

1.9.5

2 files

1.9.4

2 files

1.9.3

2 files

1.9.2

2 files

1.9.1

2 files

1.9.0

2 files

1.8.0

2 files

1.7.0

2 files

1.6.16

2 files

1.6.15

2 files

1.6.14

2 files

1.6.13

2 files

1.6.12

2 files

1.6.11

2 files

1.6.10

2 files

1.6.9

2 files

1.6.8

2 files

1.6.7

2 files

1.6.6

2 files

1.6.5

2 files

1.6.3

2 files

1.6.1

2 files

1.6.0

2 files

1.5.1

2 files

1.5.0

2 files

1.4.4

2 files

1.4.3

2 files

1.4.2

2 files

1.4.1

2 files

1.4.0

2 files

1.3.4

2 files

1.3.3

2 files

1.3.2

2 files

1.3.1

2 files

1.3.0

2 files

1.2.0

2 files

0.1.13

2 files

0.1.12

2 files

0.1.11

2 files

0.1.10

2 files

0.1.9

2 files

0.1.8

2 files

0.1.7

2 files

0.1.6

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page