Stock Trading Bots: 5 Things to Know Before You Start

🌐 한국어

Search "automated stock trading" and you mostly get strategy talk. But run a bot for real and you hit walls well before strategy: where to open the account, how to test, whether anything survives the fees.

Here are five things, in order, that I wish I'd known before starting.

1. Choose the Broker API First — Before the Strategy

Automated equity trading starts with opening an account at a broker that offers an API. Not every broker does. Three criteria are enough to decide.

  • REST or installed client?: a REST approach (plain HTTP requests) runs on a Linux server and works from Python, Go, whatever. The older OCX/COM-based approach requires installing software on Windows and pins you to a 32-bit environment. If you're starting now, go REST.
  • Does it support paper trading?: without it, your first test happens with real money. Confirm this before anything else.
  • Are there docs and examples?: with poor API documentation, getting a single request to succeed can eat days.

In Korea, the Korea Investment Securities (KIS) OpenAPI is popular among individual developers because it's REST-based and supports paper trading. You apply, receive an appkey and appsecret, and use those to issue an access token.

import requests

BASE_URL = "https://openapi.koreainvestment.com:9443"  # live

# Paper trading uses a separate domain (check the docs)

def issue_token(app_key, app_secret):

    """Issue an access token — typically expires on a daily cycle"""

    res = requests.post(

        f"{BASE_URL}/oauth2/tokenP",

        json={

            "grant_type": "client_credentials",

            "appkey":     app_key,      # real values belong in config/env vars

            "appsecret":  app_secret,

        },

        timeout=10,

    )

    res.raise_for_status()

    return "Bearer " + res.json()["access_token"]

Tokens aren't permanent. Store the expiry time and build automatic reissue before expiry in from day one. Skip it and your bot will be quietly dead the next morning.

2. Run at Least Two Weeks on Paper Trading

A paper trading account is the real API with fake money. Beginners resent this stage the most, and it's actually the one with the highest payoff.

What you're checking here is not returns. It's things like:

  • Does the bot wake up correctly at the open? (Korean market hours are 09:00–15:30, with separate call auction windows)
  • Does it do something strange on market holidays?
  • Does the token auto-refresh when it expires?
  • When an order is rejected, does retrying produce a duplicate order?
  • When the network drops and reconnects, does it lose track of its position?

Losses in live trading come from this kind of operational bug far more often than from a wrong strategy. Duplicate orders in particular are expensive when they fire. Get in the habit of giving every order a unique key and checking whether it's already been sent.

class OrderGuard:

    """Minimal guard against sending duplicate orders on the same symbol"""

    def __init__(self):

        self.pending = {}          # symbol -> order timestamp

    def can_order(self, symbol, cooldown=60):

        last = self.pending.get(symbol)

        if last and (time.time() - last) < cooldown:

            return False           # still within cooldown, ignore

        self.pending[symbol] = time.time()

        return True

3. Calculate Fees and Taxes First

Automated trading means a lot of trades, which makes fees decisive. For Korean equities, roughly:

  • Brokerage commission: varies by broker, but around 0.01% of trade value online. Charged on both the buy and the sell.
  • Securities transaction tax: levied on sales. The rate depends on the market (KOSPI, Korea's main board / KOSDAQ, its growth board) and on the year, so always check the current figure.
  • Capital gains tax: for domestic listed shares this generally doesn't apply unless you meet the major-shareholder threshold, but foreign shares are treated differently. Tax law changes often, so checking the National Tax Service's current guidance is the safe move.

The important part is putting these costs into your backtest. A remarkable number of strategies lose their entire edge to fees.

FEE_RATE = 0.00015     # brokerage commission (replace with your broker's actual rate)

TAX_RATE = 0.0018      # transaction tax on sales (verify the current rate)

def net_profit(buy_price, sell_price, qty):

    buy_cost  = buy_price * qty * (1 + FEE_RATE)

    sell_gain = sell_price * qty * (1 - FEE_RATE - TAX_RATE)

    return sell_gain - buy_cost

# Price rose 1% — what do you actually keep?

print(net_profit(10000, 10100, 100))   # net of fees and tax

Add slippage — the gap between the price you ordered at and the price you filled at — to get closer to reality. Buy at market and filling at a worse level in the order book is normal. Assume in your backtest that everything fills at the close and the results come out far too flattering.

4. Legal Lines Not to Cross

An individual running automated trades on their own account is fine in itself. But there are boundaries.

  • Don't manage other people's money: pooling and managing funds from others moves you into territory that requires a license under Korea's Financial Investment Services and Capital Markets Act. "Let's split the profits" is risky too.
  • No orders that distort prices: posting and pulling quotes with no intent to fill, or trading back and forth between your own accounts, can be judged as market manipulation. Automation makes the volume higher and the pattern more visible.
  • Follow the API terms of service: brokers specify per-second call limits and prohibited behavior. Hammer the API and your account gets restricted.
  • No redistribution of market data: republishing the quotes you receive as a public service generally violates the terms.

When in doubt, check the broker's terms and the Financial Supervisory Service's guidance. "I didn't know" doesn't work here.

5. Start Small, and Keep Logs

Go live with an amount whose loss wouldn't affect your life. And record every decision the bot makes: why it bought, what the price was, what the order response said.

import json, logging

def log_decision(symbol, action, price, reason, response=None):

    logging.info(json.dumps({

        "symbol":   symbol,

        "action":   action,        # BUY / SELL / SKIP

        "price":    price,

        "reason":   reason,        # e.g. "crossed above 5-day MA"

        "response": response,

    }, ensure_ascii=False))

A month in, these logs become your most valuable asset — the only basis you have for telling "the strategy was wrong" apart from "the implementation was wrong" when you lose money. A month run without logs is a month with nothing learned.

Summary

In order: an account at a broker with an API → two weeks of paper trading → a backtest with fees and taxes included → a legal check → small live positions with logging. It isn't glamorous, but the people who skip this sequence are the ones who get badly hurt in month one.

The real advantage of automation isn't "making a lot of money," it's following rules without emotion. If those rules haven't been validated, automation just repeats bad judgment faster.

This article is for educational and informational purposes and is not investment advice. Automated stock trading carries a risk of principal loss. Fees, tax rates, and regulations change over time, so always verify against current official sources. All decisions and consequences are your own.

댓글

이 블로그의 인기 게시물

한국투자증권 KIS API로 실시간 시세 받기 (WebSocket 실전)

파이썬으로 업비트 API 연동하기 — 시세 조회부터 주문까지 기초

Go로 자동매매 신호봇 프레임워크 설계하기