# Quickstart From a fresh key to a live price stream and a demo trade in five short steps. You need a running Termless server with one account added (the [running the server](/docs/running) page covers that) and a terminal. Every example on this site reads two environment variables, so set them once. ## 1. Create a key Open the dashboard, go to **API keys** and create one. Pick the scope it needs: **read** to look at prices and accounts, **trade** if it will place orders. Limit it to the account it works with. The full key is shown once, so copy it then. Or do the same over the API with the admin cookie (see [authentication](/docs/authentication)): ```sh curl -s -X POST "$TERMLESS_URL/api/v1/keys" -b cookies.txt \ -H "Content-Type: application/json" \ -d '{"name": "quickstart", "scopes": ["trade"], "accounts": ["pepperstone-12345678"]}' ``` Then put the address of your server and the key in your shell: ```sh export TERMLESS_URL="https://your-server" export TERMLESS_KEY="tl_paste_the_key_here" ``` ## 2. See what the key can reach `GET /api/v1/me` tells you the key's scope and accounts. `GET /api/v1/accounts` lists the accounts it may see, each with its connection status. ```sh curl -s "$TERMLESS_URL/api/v1/me" -H "Authorization: Bearer $TERMLESS_KEY" curl -s "$TERMLESS_URL/api/v1/accounts" -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} me = requests.get(f"{base}/me", headers=auth).json() print(me["scopes"], me["accounts"]) accounts = requests.get(f"{base}/accounts", headers=auth).json() acc = accounts[0]["id"] print(acc, "connected:", accounts[0]["status"]["connected"]) ``` ```javascript const base = `${process.env.TERMLESS_URL}/api/v1`; const headers = { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }; const get = async (path) => { const res = await fetch(base + path, { headers }); if (!res.ok) throw new Error((await res.json()).error.message); return res.json(); }; const me = await get("/me"); console.log(me.scopes, me.accounts); const [account] = await get("/accounts"); console.log(account.id, "connected:", account.status.connected); ``` ```json {"kind": "key", "name": "quickstart", "scopes": ["trade"], "accounts": ["pepperstone-12345678"]} ``` ## 3. A quote and some candles Quotes are the latest bid and ask, and `tradeable` says whether a trade can be opened right now. The first request for a symbol subscribes it at the broker and waits up to three seconds for a price; later requests answer at once. Candles come oldest first, and each says whether it is `complete`: the newest is usually still forming. ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/quotes?symbols=XAUUSD,EURUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/candles?symbol=XAUUSD&timeframe=M5&count=100" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python quotes = requests.get(f"{base}/accounts/{acc}/quotes", headers=auth, params={"symbols": "XAUUSD,EURUSD"}).json() for q in quotes: print(q["symbol"], q["bid"], q["ask"]) bars = requests.get(f"{base}/accounts/{acc}/candles", headers=auth, params={"symbol": "XAUUSD", "timeframe": "M5", "count": 100}).json() print(len(bars["candles"]), "bars, last close", bars["candles"][-1]["close"]) ``` ```javascript const quotes = await get(`/accounts/${account.id}/quotes?symbols=XAUUSD,EURUSD`); for (const q of quotes) console.log(q.symbol, q.bid, q.ask); const { candles } = await get(`/accounts/${account.id}/candles?symbol=XAUUSD&timeframe=M5&count=100`); console.log(candles.length, "bars, last close", candles.at(-1).close); ``` If you would rather not install anything, Python's standard library is enough: ```python import json import os import urllib.request base = os.environ["TERMLESS_URL"] + "/api/v1" req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/quotes?symbols=XAUUSD", headers={"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}) with urllib.request.urlopen(req, timeout=10) as r: print(json.load(r)[0]) ``` ## 4. A live stream Polling quotes works, but a stream gives you every tick as it happens. The simplest is Server-sent events: plain HTTP, readable with `curl -N`. The first event is a `status` saying whether the account is connected; then each price change is a `tick`. ```sh curl -N "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/stream?symbols=XAUUSD,EURUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python import json with requests.get(f"{base}/accounts/{acc}/stream", headers=auth, params={"symbols": "XAUUSD,EURUSD"}, stream=True, timeout=(5, 30)) as r: r.raise_for_status() event = None for line in r.iter_lines(decode_unicode=True): if line.startswith("event:"): event = line[6:].strip() elif line.startswith("data:") and event == "tick": t = json.loads(line[5:]) print(t["symbol"], t["bid"], t["ask"]) ``` ```javascript // In a browser (EventSource cannot send headers, so the key goes in the query) const url = new URL(`/api/v1/accounts/${account.id}/stream`, process.env.TERMLESS_URL); url.searchParams.set("symbols", "XAUUSD,EURUSD"); url.searchParams.set("key", process.env.TERMLESS_KEY); const es = new EventSource(url); es.addEventListener("tick", (e) => { const t = JSON.parse(e.data); console.log(t.symbol, t.bid, t.ask); }); ``` ```sse event: status data: {"connected":true,"ping_ms":14.2} event: tick data: {"symbol":"XAUUSD","bid":2391.42,"ask":2391.6,"last":0,"time_msc":1790981179473} : heartbeat ``` The [streaming prices](/docs/streaming) page covers the WebSocket flavour, reconnects and what a `status` event means. ## 5. A demo trade Read the symbol's spec first: `volume_min` is the smallest order, `stops_level` the closest a stop may sit. Then place a market buy of 0.01 lots with a stop loss and take profit, look at the result, and close it. ```sh # the spec curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/symbols/XAUUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" # buy 0.01 lots at market (the Idempotency-Key makes a retry of this exact call safe) curl -s -X POST "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders" \ -H "Authorization: Bearer $TERMLESS_KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: quickstart-$(date +%s)" \ -d '{"symbol": "XAUUSD", "side": "buy", "volume": 0.01, "sl": 2380.0, "tp": 2420.0, "comment": "quickstart"}' # close it (the ticket is "order" in the result, also in GET .../positions) curl -s -X DELETE "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830031" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python spec = requests.get(f"{base}/accounts/{acc}/symbols/XAUUSD", headers=auth).json() print("smallest order", spec["volume_min"], "lots; stops at least", spec["stops_level"], "points away") import uuid r = requests.post(f"{base}/accounts/{acc}/orders", headers={**auth, "Idempotency-Key": f"quickstart-{uuid.uuid4()}"}, json={ "symbol": "XAUUSD", "side": "buy", "volume": spec["volume_min"], "sl": 2380.0, "tp": 2420.0, "comment": "quickstart"}) result = r.json() if r.status_code == 422: raise SystemExit(f"refused: {result['retcode']} {result['retcode_text']}") r.raise_for_status() print("filled", result["volume"], "lots at", result["price"], "ticket", result["order"]) r = requests.delete(f"{base}/accounts/{acc}/positions/{result['order']}", headers=auth) print("closed:", r.json()["retcode_text"]) ``` ```javascript const spec = await get(`/accounts/${account.id}/symbols/XAUUSD`); console.log("smallest order", spec.volume_min, "lots"); const place = await fetch(`${base}/accounts/${account.id}/orders`, { method: "POST", headers: { ...headers, "Content-Type": "application/json", "Idempotency-Key": `quickstart-${crypto.randomUUID()}` }, body: JSON.stringify({ symbol: "XAUUSD", side: "buy", volume: spec.volume_min, sl: 2380.0, tp: 2420.0, comment: "quickstart" }), }); const result = await place.json(); if (place.status === 422) throw new Error(`refused: ${result.retcode} ${result.retcode_text}`); console.log("filled", result.volume, "lots at", result.price, "ticket", result.order); const close = await fetch(`${base}/accounts/${account.id}/positions/${result.order}`, { method: "DELETE", headers }); console.log("closed:", (await close.json()).retcode_text); ``` ```json {"ok": true, "retcode": 10009, "retcode_text": "Request completed", "deal": 81200131, "order": 51830031, "volume": 0.01, "price": 2391.6, "bid": 2391.42, "ask": 2391.6, "comment": "Request completed", "request_id": 31} ``` ```json {"ok": false, "retcode": 10014, "retcode_text": "Invalid volume", "deal": 0, "order": 0, "volume": 0, "price": 0, "bid": 2391.42, "ask": 2391.6, "comment": "Invalid volume", "request_id": 32, "error": {"code": "rejected", "message": "the broker refused the request: Invalid volume (10014)"}} ``` > **Careful: Markets close** > > Forex and gold close on Friday evening and open on Sunday evening (broker time). A trade then is refused with `10018 Market is closed`, and a quote has `null` prices until the first tick. Pepperstone's crypto symbols trade through the weekend, so they are handy for a weekend test. ## Where to go next - [Trading safely](/docs/trading): market versus pending, stops, partial closes, reading a refusal, and the `Idempotency-Key` that makes a retry safe. - [Streaming prices](/docs/streaming): ticks, and the `trade`, `account`, `positions` and `orders` events a bot reads instead of polling. - [Errors and retries](/docs/errors): every status code and what to do about it. - [API reference](/docs/reference): every route, with its fields, errors and examples.