Skip to content
Course contents
Talking to the broker

Logging in without getting hacked

The first thing your program does is prove who it is, and the first way beginners get hurt is by handling that badly. This chapter walks through the login and token flow, the static-IP whitelisting the framework requires, and the non-negotiable habits: never hardcode a key, never commit a secret, keep credentials out of the code.

10 min readChapter 6 of 28
What you will learn
  • Describe a typical API login and access-token flow
  • Apply the security requirements (static-IP whitelist, secrets outside the code, least privilege)
  • Explain why a leaked key or shared session is a direct financial risk

A leaked password to your email is bad. A leaked key to a program that can place trades is worse, because it can act on your money at machine speed, in the seconds before you notice. So the login step deserves more care than any other part of your setup. Get it right once, as a set of habits, and it protects you for good.

The login and token flow

Your program logs in with a key and secret to get an access token, then makes authenticated requests. Never hardcode a key or commit a secret, and whitelist your IP.
Your program logs in with a key and secret to get an access token, then makes authenticated requests. Never hardcode a key or commit a secret, and whitelist your IP.

Real broker APIs do not want your everyday password sitting inside a script. Instead they use a two-part scheme. You are issued an API key, and often a secret, that identifies your application, and you use them to log in and receive an access token, a temporary pass that is usually good only for the trading day. Your program then presents that token on every call, and tomorrow it logs in again for a fresh one. The exact steps vary by broker, but the shape is always the same: identify the app with the key, exchange a login for a short-lived token, use the token, let it expire.

python
# A typical login flow, shown generically and NOT run. Read every secret from
# the environment, never write one into the code.
import os
from broker_sdk import BrokerClient

api_key = os.environ["BROKER_API_KEY"]
api_secret = os.environ["BROKER_API_SECRET"]

client = BrokerClient(api_key)
# After the broker's login step returns a one-time request_token:
access_token = client.generate_session(request_token, api_secret)
client.set_access_token(access_token)          # the client is now ready to use

Keep secrets out of the code

Look at where those keys came from: os.environ, the program's environment, not the source file. This is the single most important security habit, so make it a rule you never break. Never write an API key, secret, or token into your code. The reason is simple and unforgiving: code gets shared. It goes into version control, gets copied to another machine, gets pasted into a chat when you ask for help. Everywhere the code travels, a hardcoded key travels with it. Keep secrets in the environment, or in a separate configuration file that is never committed, and load them at run time.

ExampleLoad a key from the environment, and never log it in fullch06/secrets_demo.py
# The right and wrong ways to handle API credentials. This runs, but only ever
# touches a throwaway demo value from the environment, never a real secret.
import os


def redact(secret):
    """Show only the last 4 characters, so a log can never leak a full key."""
    if not secret:
        return "(missing)"
    return "*" * (len(secret) - 4) + secret[-4:]


# WRONG: a key written into the code. Anyone who reads the file has your key,
# and code has a way of ending up in shared repositories and chat messages.
# api_key = "live_key_9f83A2c1B7"          # never do this

# RIGHT: read the key from the environment, so it lives outside the code.
api_key = os.environ.get("BROKER_API_KEY")

if api_key is None:
    print("No BROKER_API_KEY found in the environment.")
    print("Set it outside your code (an environment variable, or a secrets file")
    print("that is never committed to version control), then run again.")
else:
    print(f"Loaded API key from the environment: {redact(api_key)}")
    print("The key stays out of the code, and out of the logs.")
Output
Loaded API key from the environment: ***************c1B7
The key stays out of the code, and out of the logs.

The example does two safe things at once. It reads the key from the environment, so the value is not in the file, and it prints the key only through a redact function that hides all but the last four characters. That second habit matters more than it looks. Programs write logs, and a program that logs its own key in full has leaked it to every log file. Show enough to recognise a key, never enough to use it.

The rules that wrap a trading program

The regulation chapter mentioned some of these; here they become your setup. You will usually be required to whitelist a static IP address, a fixed internet address, so the broker accepts API calls only from your known machine and a stolen key is useless from anywhere else. Grant your keys the least privilege the task needs: if a key only needs to read data, do not give it permission to place orders. And know that both your broker and the exchange can pull a kill switch to stop a misbehaving program, which is a backstop, not a substitute for your own care.

Why this is financial, not technical

It is tempting to treat all of this as dry technical hygiene. It is not. Every one of these habits maps to a way of losing money. A hardcoded key in a shared repository is an open door to your funds. A key with more privileges than it needs turns a small mistake into a large one. A session used from an unexpected place is how account takeovers happen. The security chapter is a risk chapter wearing different clothes, and the same seriousness you bring to position sizing you should bring to your credentials.

What to carry forward

Your program proves who it is with an API key and a short-lived access token, refreshed each day, and the whole scheme only protects you if you keep the secrets out of your code. Load keys from the environment or an uncommitted file, never from the source, and never log a key in full, showing only the last few characters. Whitelist a static IP so a stolen key is useless elsewhere, give each key the least privilege it needs, and treat the exchange's kill switch as a backstop. Handled carelessly, credentials are the fastest financial risk in this course. With the login made safe, the next chapter uses it for the safest possible calls: reading the account.