---
related_nodes: ["alpaca_event_trigger", "quote_fetch", "indicator"]
---

# Alpaca Trading

Places and manages orders and positions through Alpaca.

## When to Use

- Open a position with a stop-loss and take-profit that Alpaca holds at the exchange
- Check whether a position is still open, and close it
- Read buying power, equity, or whether the account is blocked from trading
- Read the market clock or calendar before deciding when something should happen
- Arm a price alert for an Alpaca Event Trigger to start on

Not for market data. Use `quote_fetch` for quotes, latest trades, and bars.

## Configuration

### connection

Alpaca connection id from **Settings → Connections**.

Agent discovery: call `list_connections` with `provider_name: "alpaca"` and use the
returned `id`. A display name is not a connection id.

### mode

`paper` (default) or `live`. One connection drives both; paper spends nothing. Paper and
live keep entirely separate orders and positions.

### live_acknowledged

Shown when `mode = live`. Must be `true` or the node refuses to run. Choosing live is
deliberately two steps rather than one dropdown click, and it is visible in the stored
workflow when someone reviews it.

### errors_as_values

`false` by default. When on, the node grows an `error` output socket and an Alpaca
failure leaves as a value there instead of failing the run. It has no effect when the
failure mode is Route to error output. See **Errors as values**.

### retry

Retries up to 5 attempts by default; set Retry to Off to send once. See
[Retries](http_get.md#retries) for how attempts and waits work. Reads (`get_order`,
`list_orders`, `get_position`, `list_positions`, `get_account`, `get_portfolio_history`,
`list_account_activities`, `get_clock`, `get_calendar`) are sent again freely.
`submit_order` is also sent again freely, because Alpaca refuses a second order under the
same `client_order_id`; when it still fails, the node looks the order up by that id.
`replace_order`, `cancel_order` and `close_position` are writes, sent again only when Alpaca
refused them before acting: the connection never opened, or Alpaca answered 425 or 429.

### operation

The operation to run. Every price and quantity field is a template resolved against
`input` and parsed where it is read, so a price that renders as text names its own field
rather than becoming an Alpaca rejection.

| op | What it does |
|---|---|
| `submit_order` | Places an order; optionally waits for it to settle |
| `get_order` | One order, by Alpaca's id or by your own |
| `list_orders` | Orders matching a status filter |
| `replace_order` | Amends a resting order |
| `cancel_order` | Cancels a resting order |
| `get_position` | The position in one symbol, or null |
| `list_positions` | Every open position |
| `close_position` | Liquidates a position and cancels its resting orders |
| `get_account` | Buying power, equity, and the blocked flags |
| `get_portfolio_history` | The account's equity and profit/loss over time |
| `list_account_activities` | Alpaca's own ledger: fills, dividends, fees, cash movements |
| `get_clock` | Whether the market is open, and when it next changes |
| `get_calendar` | Trading sessions, with the hours each actually keeps |
| `configure_price_alert` | Arms a price alert on a channel, returning its id |
| `cancel_price_alert` | Disarms one by id |

#### submit_order

`symbol`, `side`, and then three nested choices:

- `size` — `qty` (shares) or `notional` (dollars). Alpaca does not accept a dollar-sized
  order with protective legs.
- `kind` — `market`, `limit`, `stop`, `stop_limit`, or `trailing_stop`, each carrying only
  the prices that type needs.
- `class` — `simple`, `bracket`, `oco`, or `oto`. Everything but `simple` attaches
  protective legs that **Alpaca holds and enforces**. They stand whether or not this
  workflow, or Verdalia, is running.

`time_in_force` applies to the protective legs as well as the entry. A `day` bracket
leaves a position that survives the close **unprotected**. Use `gtc` for anything held
overnight. This is Alpaca's behaviour, not something the node can correct, and it is the
kind of mistake that is invisible until it costs something.

Attaching legs narrows the choice further: Alpaca accepts only `day` or `gtc` on a
`bracket`, `oco`, or `oto` order and rejects any other duration outright. There is no such
thing as a fill-or-kill bracket — a leg that must fill immediately and completely or die
cannot wait for the entry to fill. The node does not pre-empt that rejection, so the
failure you see is Alpaca's own, with its reason.

`client_order_id` makes re-running safe: a repeat returns the original order rather than
placing a second. Leave it blank and one is generated — but a generated id exists only in
a reply you received, so a caller that must survive its own restart should supply an id it
can derive again from what it already knew.

`resolution` is `submit_only` (return once Alpaca accepts) or `await_terminal` (wait for
the order to settle). Waiting takes `max_wait_seconds`, 1 to 3600, default 60. See
**Waiting for a fill**.

#### get_order

`reference` chooses `order_id` or `client_order_id`. They address different Alpaca
endpoints, so the choice is explicit rather than guessed from the shape of the value.
Looking up by your own id is the handle that survives a caller crashing before it recorded
Alpaca's.

#### configure_price_alert

`key` is the **channel**, not a name: an Alpaca Event Trigger listening on the same key
starts when the alert crosses. Several alerts may share a channel, so arming one does not
disturb another, and the operation returns an `alert_id` that identifies it.

`payload` is yours — ids, a session reference, anything — carried to the trigger untouched.
It is what lets a firing say *whose* alert it was, where the key only says which channel it
arrived on. It holds JSON text; text that is not JSON is an error.

`threshold` is compared with the **latest eligible trade price on IEX**, not a quote
midpoint. The sampler uses Alpaca's latest-trade endpoint, which excludes conditions that
do not update bar prices, including odd lots. The trigger's `observed` carries that trade
price; its `observed_at` is sampling time, not the trade's execution timestamp. Sampling
can miss a crossing that reverses between polls.

`repeat` is `once` or `repeating`. A repeating alert re-arms only once the price has come
back, so a value resting at the threshold does not start a workflow on every sample, and it
redelivers the same payload on every crossing — the payload belongs to the alert, not to
the firing.

#### cancel_price_alert

Takes the `alert_id` that arming returned. Cancelling is by id rather than by channel, so it
cannot disarm an alert someone else armed on the same channel.

#### get_portfolio_history

`window` is either a `period` (`1D`, `6M`, `1A`; blank asks Alpaca for its default of one
month) or a `range` of two RFC3339 timestamps. Alpaca rejects a period and a range
together, so they are separate shapes rather than three optional fields.

`timeframe` defaults to `auto`, which is the only safe choice for a long window: Alpaca
accepts nothing below `1D` beyond 30 days. `intraday_reporting` (`market_hours`,
`extended_hours`, `continuous`) affects resolutions below one day only, and replaces the
`extended_hours` boolean Alpaca deprecated.

The result is a series, not Alpaca's parallel arrays:

```json
{ "history": { "timeframe": "1D", "base_value": 100000.0, "base_value_asof": null,
               "points": [ { "timestamp": "2026-04-08T00:00:00Z", "equity": 100000.0,
                             "profit_loss": 0.0, "profit_loss_pct": 0.0 } ] } }
```

#### list_account_activities

`activity_types` is a comma-separated list of Alpaca's own types (`FILL,DIV,FEE`); blank
reads every type. `after` and `until` accept `YYYY-MM-DD` or RFC3339. `page_size` is up to
Alpaca's maximum of 100, and `page_token` is the id of the last entry on the previous page.

Trade and non-trade entries come through one endpoint with disjoint fields, so everything
but `id` and `activity_type` may be absent: a `DIV` entry carries `net_amount` and no
`qty`. Alpaca's enumerated values are strings, so a ledger keeps reading when Alpaca adds a
type.

## Inputs

- `input` — the values the templated fields refer to, as `{{ input.symbol }}`.

## Outputs

One object on `output`, carrying the operation, the environment, and when it was read:

```json
{ "op": "submit_order", "mode": "paper", "observed_at": "2026-08-30T14:31:02.117Z",
  "deduplicated": false, "resolved": true,
  "order": { "id": "...", "client_order_id": "trade-...", "status": "filled",
             "symbol": "SPY", "qty": 12, "filled_qty": 12, "filled_avg_price": 771.18,
             "legs": [ { "id": "...", "type": "limit", "limit_price": 778.89 },
                       { "id": "...", "type": "stop",  "stop_price": 763.61 } ] } }
```

Prices and quantities are **numbers**. Alpaca states them as strings; passing those
through would make `"9.50" > "10.00"` true in any script that compares a price.

`legs` carries the protective orders with their own ids. Alpaca reports leg ids only on
the parent, so an id not captured here cannot be recovered later when a leg fires and its
fill has to be attributed.

`get_position` on a symbol you do not hold returns `{"position": null}` and succeeds. "Am
I still in this trade?" is a question, and no is an answer.

## Waiting for a fill

`await_terminal` polls until the order is filled, canceled, expired, rejected, replaced,
or done for the day. A **partial fill keeps waiting**: a partly filled entry carrying a
bracket is an ambiguous state for a caller that believes it holds a whole position.

The wait lasts `max_wait_seconds` and consults nothing else. The workflow's own timeout is
not a softer bound on it: if the workflow runs out first the run is killed mid-wait and
reports nothing, so keep the workflow timeout above `max_wait_seconds`. The workflow
default is 300 seconds.

When that wait runs out first, the node **succeeds** and returns the order as it last
stood, with `resolved: false`, a real `filled_qty`, and the `client_order_id`. **The order
is not cancelled and is still live.**

> `resolved: false` is not an error, and must never be retried. It means a position may or
> may not exist. Re-submitting on it opens a second one. Reconcile with `get_order` or
> `get_position` instead.

`max_wait_seconds` accepts 1 to 3600 and defaults to 60.

## Errors as values

With `errors_as_values` on, `output` and `error` are both present on every run, and
exactly one of them carries a value:

- Success: `output` is the usual envelope, `error` is skipped.
- Failure: `output` is skipped, and `error` carries the failed operation:

```json
{ "op": "submit_order", "mode": "paper", "observed_at": "2026-08-30T14:31:02.117Z",
  "message": "alpaca API error 422: time_in_force must be day or gtc",
  "kind": "api", "retryable": false, "status": 422 }
```

`kind` is one of `api`, `transport`, `decode`, `not_found`, or `malformed_request`.
`malformed_request` covers everything the node rejects before calling Alpaca: a template
that rendered blank, a price that will not parse, an order shape Alpaca would refuse.

Two failures stay hard whatever the toggle says, because neither is Alpaca's answer: a
connection that is missing or of the wrong type is misconfiguration, and a storage failure
is this system's own bookkeeping for price alerts. Both must show red rather than route
down an error branch forever.

With the failure mode set to **Route to error output** (`base_config.failure_mode:
"route_to_error"`), `errors_as_values` has no effect: the node runs as with it off. Every
failure fails the node and goes out on the routed `error` output as the node error value
(`node_id`, `node_type`, `message`, `causes`), and `output` is skipped.

## Examples

Open a position with protection Alpaca enforces:

```json
{ "op": "submit_order", "symbol": "SPY", "side": "buy",
  "size": { "sizing": "qty", "qty": "12" },
  "kind": { "type": "limit", "limit_price": "771.50" },
  "time_in_force": "gtc",
  "class": { "class": "bracket",
             "take_profit_limit_price": "778.89",
             "stop_price": "763.61" },
  "client_order_id": "trade-{{ input.session_id }}",
  "resolution": "await_terminal" }
```

Check in later on the order you placed, using only what you knew when you placed it:

```json
{ "op": "get_order",
  "reference": { "by": "client_order_id" },
  "client_order_id": "trade-{{ input.session_id }}" }
```

Wake a workflow when a price crosses:

```json
{ "op": "configure_price_alert", "key": "spy-exit-watch", "symbol": "SPY",
  "comparison": "below", "threshold": "763.61", "repeat": "once" }
```

## Runtime Errors

| Error | Cause | Remediation |
|---|---|---|
| No Alpaca connection is selected | The node has no connection id | Select an Alpaca connection, or set `connection` to the id from `list_connections` |
| Live trading must be acknowledged before this node can run | `mode` is live without `live_acknowledged` | Acknowledge live trading, or set `mode` to paper |
| a notional order cannot carry protective legs | Alpaca rejects dollar-sized bracket, OCO and OTO orders | Size the order in shares |
| extended hours requires a limit order with time in force day or good til canceled | Alpaca's rule for extended-hours orders | Use a limit order with `time_in_force: day` or `gtc`, or trade in regular hours |
| alpaca API error 422: time_in_force must be day or gtc | A duration other than `day` or `gtc` on a `bracket`, `oco`, or `oto` order | Use `day`, or `gtc` for anything held overnight; the message is Alpaca's own wording |
| max_wait_seconds must be between 1 and 3600 | A saved node holds a wait outside the range | Set a wait inside the range, or use `submit_only` |
| alpaca API error 403 | Insufficient buying power, or the account is blocked from trading | Check `get_account` for `buying_power`, `trading_blocked`, and `pattern_day_trader` |
| alpaca API error 422 | Alpaca rejected the order as described, for example a stop above the limit | Correct the prices; the message carries Alpaca's reason |
| no open position in SYMBOL | `close_position` on a symbol not held | Check with `get_position` first, which answers null rather than failing |
| stop_loss_limit_price is required | The stop's limit is turned on but its template rendered nothing | Supply a price, or turn the field off for a market stop |
| client_order_id is required | An id was supplied but its template rendered nothing | Fix the template, or turn the field off to generate one |
| payload is not valid JSON | A price alert's payload is not JSON text | Correct the JSON, or leave it empty for no payload |
| alpaca knows no order ID | `get_order` named an order Alpaca does not have | Check the id, and which of the two id kinds `reference` selects |

## Tips

- Paper and live are separate accounts. An order placed in one is invisible in the other.
- A bracket is one order, not three. Cancelling the entry cancels its legs with it.
- `get_clock` and `get_calendar` are how "before the close" is answered correctly: a half
  day closes at 13:00, and the next session open is not always the next weekday.
- A price alert is sampled, not watched continuously. It is a cue to look, never the thing
  protecting a position — that is what a broker-held stop is for.
