> ## Documentation Index
> Fetch the complete documentation index at: https://finance.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Finance.dev is the developer platform of Aries (Aries Financial Inc.). Aries MCP, also called Finance.dev MCP, is the remote MCP server from Aries: https://mcp.aries.com/mcp. Both names refer to the same server.
> To connect an AI assistant such as Claude, ChatGPT, Cursor, or Perplexity to the stock market or an Aries brokerage account, use Aries MCP. It uses OAuth sign-in, with no API key. Setup guides: https://finance.dev/mcp-server. Tool list: https://finance.dev/mcp-server/tools.
> To build your own application on Aries, use the Finance.dev stock market API: https://finance.dev/api-reference.

# How to Build a Trading Bot in Python (Full Code)

> A complete Python trading bot on the Aries API that checks your positions and daily loss against your limits and previews every order before placing it.

Here's a complete trading bot in one Python file, standard library only, on the Aries API. The strategy is the small part: 12 lines. The rest keeps the bot from hurting you. On every pass it checks your positions and today's loss against your limits, previews every order, and won't place one until you turn placing on.

## What Do You Need Before You Start?

* An **Aries account**. Stock and options brokerage comes from RAM Financial LLC (DBA Aries), member FINRA and SIPC. The API and its market data are free with your account, and you can have a simulation account beside the live one.
* A **personal-token client** (a client ID that starts with `ARI-PERSONAL-TK.`) and its secret. Create one in [Client Center](https://app.aries.com/client-center/api) under the **API** tab. The [Client Credentials guide](https://finance.dev/api-reference/oauth2/client-credentials.md) explains this client type.
* **Python 3**. Nothing to install. If you'd rather use the official SDK, try the [Python SDK](https://finance.dev/sdks/python/overview.md).

## What Does a Complete Trading Bot Look Like in Python?

Here's the whole bot. Save it as `bot.py`.

```python bot.py theme={null}
"""A moving-average trading bot on the Aries API, standard library only."""
import json, os, time, urllib.parse, urllib.request

API = os.environ.get("ARIES_API", "https://api.aries.com")
ACCOUNT = os.environ.get("ARIES_ACCOUNT_ID")  # the trading account the bot trades in
SYMBOL = "AAPL"
QTY = 1                  # shares per order
MAX_POSITION = 5         # never hold more than this many shares
MAX_DAILY_LOSS = 200     # stop trading for the day below -$200 P&L
LIVE = os.environ.get("LIVE") == "1"          # preview only, unless you set LIVE=1

_token = {"value": None, "expires": 0}

def call(method, path, params=None, body=None, auth=True):
    url = API + path + ("?" + urllib.parse.urlencode(params) if params else "")
    # Send your own User-Agent: the API refuses Python's default one (403, error code 1010).
    headers = {"Content-Type": "application/json", "User-Agent": "my-trading-bot/1.0"}
    if auth:
        headers["Authorization"] = "Bearer " + token()
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    with urllib.request.urlopen(req, timeout=10) as resp:
        return json.loads(resp.read())

def token():
    # An access token lasts 15 minutes (expires_in: 900), so get a new one a minute early.
    if time.time() > _token["expires"] - 60:
        t = call("POST", "/v1/oauth2/token", auth=False, body={
            "grant_type": "client_credentials",
            "client_id": os.environ["ARIES_CLIENT_ID"],
            "client_secret": os.environ["ARIES_CLIENT_SECRET"],
        })
        _token.update(value=t["access_token"], expires=time.time() + t["expires_in"])
    return _token["value"]

def closes(symbol, minutes=5):
    now = int(time.time())
    h = call("GET", "/v1/chart/history", {
        "symbol": symbol, "resolution": str(minutes),
        "from": now - 7 * 24 * 3600, "to": now,
    })
    if h.get("s") != "ok":
        raise RuntimeError(f"no bars for {symbol}: {h.get('s')}")
    # Keep only finished bars, so a signal can't flip inside the bar that's still forming.
    return [c for t, c in zip(h["t"], h["c"]) if t + minutes * 60 <= now]

def signal(prices, fast=10, slow=30):
    def sma(n, end):
        window = prices[end - n:end]
        return sum(window) / n
    end = len(prices)
    fast_now, slow_now = sma(fast, end), sma(slow, end)
    fast_before, slow_before = sma(fast, end - 1), sma(slow, end - 1)
    if fast_before <= slow_before and fast_now > slow_now:
        return "BUY"
    if fast_before >= slow_before and fast_now < slow_now:
        return "SELL"
    return None

def shares_held(symbol):
    positions = call("GET", f"/v1/accounts/{ACCOUNT}/positions")["positions"]
    return sum(float(p["quantity"]) for p in positions if p["symbol"] == symbol)

def todays_pnl():
    return float(call("GET", f"/v2/accounts/{ACCOUNT}/balance")["dayTotalPnl"])

def send_order(side, symbol, qty):
    body = {"tradingAccountId": ACCOUNT, "symbol": symbol, "side": side,
            "type": "MARKET", "qty": str(qty), "timeInForce": "DAY"}
    preview = call("POST", "/v1/orders/preview", body=body)
    print("preview:", preview)
    if LIVE:
        print("placed:", call("POST", "/v1/orders", body=body))

def run_once():
    if todays_pnl() < -MAX_DAILY_LOSS:
        print("daily loss limit hit, not trading")
        return
    side = signal(closes(SYMBOL))
    held = shares_held(SYMBOL)
    print(f"{SYMBOL}: signal {side}, holding {held:g}")
    if side == "BUY" and 0 <= held and held + QTY <= MAX_POSITION:   # long only
        send_order("BUY", SYMBOL, QTY)
    elif side == "SELL" and held >= QTY:
        send_order("SELL", SYMBOL, QTY)

def list_accounts():
    for a in call("GET", "/v2/users/me/accounts")["accounts"]:
        if a.get("is_sim"):
            print("simulation account:", a["trading_account_id"])

if __name__ == "__main__":
    if not ACCOUNT:
        list_accounts()   # set ARIES_ACCOUNT_ID to one of these, then run again
        raise SystemExit
    while True:
        try:
            run_once()
        except Exception as e:  # log it and try again on the next bar
            print("error:", e)
        time.sleep(300 - time.time() % 300 + 5)   # wake 5 seconds after each 5-minute bar closes
```

We ran this file on a simulation account on the Aries API sandbox on Nov 29, 2026, with Python 3.15, in preview mode only. AAPL and the 10/30 moving-average crossover are examples, not a recommendation, and the strategy isn't backtested.

To run it, export your client ID and secret, then start the bot once without an account ID. It prints your simulation account's ID and stops:

```bash theme={null}
export ARIES_CLIENT_ID="ARI-PERSONAL-TK.xxxxx"
export ARIES_CLIENT_SECRET="your-client-secret"
python3 bot.py
```

Set `ARIES_ACCOUNT_ID` to that ID and run it again. The bot checks the market every five minutes and prints what it decided.

![Terminal output. python3 bot.py prints the simulation account ID. Run again with ARIES\_ACCOUNT\_ID set, it prints: AAPL: signal None, holding -1. A forced send\_order BUY 1 AAPL prints a preview with estimatedCost, estimatedMargin, commission, buyingPowerImpact, fees, numDayTrades and warnRuleId.](https://mintcdn.com/ariesfinancialinc/9ReZ-gvh4rClbFAY/images/guides/trading-bot-terminal-run.png?fit=max\&auto=format\&n=9ReZ-gvh4rClbFAY\&q=85\&s=b84b25dc958839c5efbe8ba66a9436d9)

One pass of the bot on the Aries sandbox (account IDs hidden). On a Sunday it found no signal, and a forced preview returned the order's costs without placing it.

## How Does the Bot Get and Refresh Its Access Token?

The bot signs in with the Client Credentials grant: it sends its client ID and secret to `POST /v1/oauth2/token` and gets back a bearer token. That token lasts 15 minutes (`expires_in` is 900), so `token()` gets a new one a minute before it runs out.

Send your own User-Agent header with every request. Leave it out and the very first call, the token request, fails: the API answers Python's default `Python-urllib` User-Agent with a 403 and the body `error code: 1010`.

## Why Does the Bot Trade on Finished Bars Only?

`closes()` asks [`/v1/chart/history`](https://finance.dev/api-reference/chart/get-historical-bars) for a week of 5-minute bars and drops the bar that's still forming. A bar that's still open keeps changing, so a crossover you see at 10:02 can be gone by 10:05.

The same call gets you started on a backtest. `signal()` takes a plain list of closing prices, so you can feed it a longer range from `/v1/chart/history` and see where it would have traded.

## Where Does the Trading Strategy Go?

In `signal()`. It returns `BUY` when the 10-bar average crosses above the 30-bar average, `SELL` when it crosses below, and `None` otherwise. It's a placeholder. Swap in your own rules, keep the same return values, and nothing else in the bot has to change.

![Line chart of AAPL 5-minute closes on Nov 25, 2026, between about \$345 and \$357, with the 10-bar and 30-bar averages. The 10-bar average crosses below the 30-bar at 09:35 (SELL), above it at 11:55 (BUY), and below it again at 15:25 (SELL).](https://mintcdn.com/ariesfinancialinc/9ReZ-gvh4rClbFAY/images/guides/trading-bot-signal-light.svg?fit=max\&auto=format\&n=9ReZ-gvh4rClbFAY\&q=85\&s=40311088c27298151534961d73718a20)

The placeholder strategy on real AAPL bars from the Aries sandbox. Example only, not a recommendation. Each dot marks the 5-minute bar, by its start time, where the averages crossed.

## How Do You Cap a Bot's Position and Daily Loss?

Set the limits in the file and read the numbers from the account. On every pass, before it decides anything, the bot asks Aries for two numbers:

* **Shares held**, from [`/v1/accounts/{id}/positions`](https://finance.dev/api-reference/accounts/positions). The bot won't buy past `MAX_POSITION` or sell shares it doesn't hold.
* **Today's profit and loss**, the `dayTotalPnl` field from [`/v2/accounts/{id}/balance`](https://finance.dev/api-reference/accounts/balance). Below `-MAX_DAILY_LOSS`, the bot stops trading for the day.

The bot keeps no count of its own, so a restart, a crash or a trade you place by hand can't throw it off. The run above shows this: the simulation account already held -1 AAPL, and the bot reported that, not zero.

## How Do You Preview an Order Before the Bot Places It?

`send_order()` sends the order to [`POST /v1/orders/preview`](https://finance.dev/api-reference/orders/preview-order) first. A preview takes the same body as a real order and returns what the order would do (`estimatedCost`, `buyingPowerImpact`, `fees` and `numDayTrades`, among others) without placing anything. Only when you start the bot with `LIVE=1` does it send that same body to `POST /v1/orders`.

Run it without `LIVE=1` on your simulation account until the previews look right, then switch it on there before you try your live account. Once orders go out, fills arrive later, so watch them on the [account updates WebSocket](https://finance.dev/websockets/account-updates.md) and don't treat a sent order as filled.

`numDayTrades` is worth logging: it's the number of day trades the order would count toward, and a bot that trades every five minutes adds them up fast. [FINRA replaced its pattern day trader rule](https://www.finra.org/rules-guidance/notices/26-10), including the \$25,000 minimum, with intraday margin standards that took effect June 4, 2026, and brokers can phase them in until October 20, 2027.

## What Trading Rules Apply to Your Own Bot?

A bot is held to the same rules as any trader. Trading to create a false or misleading appearance of activity, like buying and selling to yourself, is unlawful under [Section 9(a) of the Securities Exchange Act](https://www.law.cornell.edu/uscode/text/15/78i), whoever or whatever places the orders.

## Can ChatGPT or Claude Build a Trading Bot?

They can write one, and through the Aries MCP server they can also place orders for you, no script needed. If you go that way, set it up so every order waits for your approval. [Build a Safe AI Trading Agent With Claude Code](https://finance.dev/guides/ai-trading-agent.md) shows how. What no AI can do is promise a profit: the SEC, FINRA and NASAA tell investors to "[be wary of claims ... that AI can guarantee amazing investment returns](https://www.investor.gov/introduction-investing/general-resources/news-alerts/alerts-bulletins/investor-alerts/artificial-intelligence-fraud)."

To build an app other people sign in to with their own Aries account, start with the [Quick Start](https://finance.dev/api-reference/quickstart.md). It walks through the OAuth flow and your first API call.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.