Alpaca Trading logo

Alpaca Trading

Community
gauss314
alpaca-trading

Trading API de Alpaca: órdenes, posiciones, cuenta. Paper trading y live trading de acciones, crypto y opciones.

Overview

Publishergauss314
Repositoryskills
Skill namealpaca-trading
Stars
250
Forks
35
Bundled files
3
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 3 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by gauss314 on GitHub. Read the source before you install it.

Installation

Install the Alpaca Trading AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/gauss314/skills/tree/main/skills/alpaca-trading
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/gauss314/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/skills/alpaca-trading .claude/skills/alpaca-trading
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Alpaca Trading in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Alpaca Trading on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Alpaca Trading is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Alpaca Trading — Trading API

API para trading de acciones, crypto y opciones. Soporta paper trading (gratis) y live trading.

Base URLs:

  • Paper: https://paper-api.alpaca.markets
  • Live: https://api.alpaca.markets
  • SDK: pip install alpaca-py

Docs: docs.alpaca.markets


Autenticación

Obtener API Keys

  1. Ir a app.alpaca.markets
  2. Crear cuenta (paper trading es gratis)
  3. Ir a "API Keys" → Generate New Keys

Configuración

python
import os
from alpaca.trading.client import TradingClient

# Para paper trading
API_KEY = os.getenv("APCA_API_KEY_ID")
SECRET_KEY = os.getenv("APCA_API_SECRET_KEY")
BASE_URL = "https://paper-api.alpaca.markets"  # Paper

# Para live trading
# BASE_URL = "https://api.alpaca.markets"

client = TradingClient(API_KEY, SECRET_KEY, paper=True)

⚠️ NUNCA hardcodear keys. Usar variables de entorno.


Rate Limits

APILímite
Orders200 requests/min
Account/Positions200 requests/min
Account Activities200 requests/min

Recomendaciones

  • Usar WebSocket para updates en tiempo real — más eficiente que polling
  • Cachear account/positions — no consultar constantemente
  • Implementar retry con exponential backoff para 429 errors

Account

Obtener Información de Cuenta

python
account = client.get_account()
print(f"Buying Power: ${account.buying_power}")
print(f"Cash: ${account.cash}")
print(f"Portfolio Value: ${account.portfolio_value}")
print(f"Status: {account.status}")

Configuración de Cuenta

python
from alpaca.trading.requests import AccountConfigurationsRequest

config_request = AccountConfigurationsRequest(
    trade_confirmation_email=True,
    susi_transfer_email=True
)
client.update_account_configuration(config_request)

Assets

Listar Todos los Assets

python
from alpaca.trading.requests import GetAssetsRequest
from alpaca.trading.enums import AssetClass, AssetStatus

request = GetAssetsRequest(
    asset_class=AssetClass.US_EQUITY,
    status=AssetStatus.ACTIVE
)

assets = client.get_all_assets(request)

# Filtrar symbols tradables
tradable = [a for a in assets if a.tradable]
print(f"Assets tradables: {len(tradable)}")

Obtener Asset Específico

python
asset = client.get_asset("AAPL")
print(f"AAPL tradable: {asset.tradable}")
print(f"AAPL class: {asset.asset_class}")

Orders

Tipos de Órdenes

TipoDescripción
marketEjecuta al precio actual
limitPrecio máximo (buy) o mínimo (sell)
stopActiva orden de mercado cuando alcanza stop_price
stop_limitCombina stop + limit
trailing_stopStop relativo al precio

Time in Force

TIFDescripción
daySolo para día actual
gtcGood Till Cancelled
opgOpen at market open
clsClose at market close
iocImmediate Or Cancel
fokFill Or Kill

Crear Orden de Market

python
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

order_request = MarketOrderRequest(
    symbol="AAPL",
    qty=10,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY
)

order = client.submit_order(order_request)
print(f"Order ID: {order.id}")
print(f"Status: {order.status}")

Crear Orden Limit

python
from alpaca.trading.requests import LimitOrderRequest

order_request = LimitOrderRequest(
    symbol="AAPL",
    qty=10,
    side=OrderSide.BUY,
    limit_price=150.00,  # Máximo a pagar
    time_in_force=TimeInForce.GTC
)

order = client.submit_order(order_request)

Crear Orden Stop

python
from alpaca.trading.requests import StopOrderRequest

order_request = StopOrderRequest(
    symbol="AAPL",
    qty=10,
    side=OrderSide.SELL,
    stop_price=145.00,  # Vende cuando caiga a este precio
    time_in_force=TimeInForce.GTC
)

Obtener Órdenes

python
# Todas las órdenes abiertas
open_orders = client.get_orders(status="open")
print(f"Órdenes abiertas: {len(open_orders)}")

# Órdenes filladas hoy
from datetime import datetime
filled_orders = client.get_orders(
    status="fill",
    start=datetime(2024, 1, 15)
)

# Orden por ID
order = client.get_order_by_id(order_id)

Cancelar Órdenes

python
# Cancelar una orden
client.cancel_order(order_id)

# Cancelar todas las órdenes abiertas
client.cancel_orders()

Reemplazar Orden

python
from alpaca.trading.requests import ReplaceOrderRequest

replace_request = ReplaceOrderRequest(
    limit_price=155.00,  # Nuevo precio límite
    qty=15               # Nueva cantidad
)
client.replace_order(order_id, replace_request)

Positions

Obtener Posiciones Abiertas

python
positions = client.get_all_positions()

for pos in positions:
    print(f"{pos.symbol}: {pos.qty} shares")
    print(f"  Avg Entry: ${pos.avg_entry_price}")
    print(f"  Market Value: ${pos.market_value}")
    print(f"  P/L: ${pos.unrealized_pl}")

Obtener Posición Específica

python
position = client.get_position("AAPL")
print(f"AAPL: {position.qty} shares @ ${position.avg_entry_price}")

Cerrar Posición

python
# Cerrar toda la posición
client.close_position("AAPL")

# Cerrar posición parcialmente (qty=5)
client.close_position("AAPL", qty=5)

Cerrar Todas las Posiciones

python
client.close_all_positions()

Options Trading

Trading Levels

LevelDescripción
0Sin trading de opciones
1Covered calls, cash-secured puts
2Buy/sell calls y puts
3Spreads

Obtener Option Contracts

python
from alpaca.trading.requests import GetOptionContractsRequest
from datetime import datetime, timedelta

request = GetOptionContractsRequest(
    underlying_symbols=["AAPL"],
    expiration_date_gte=datetime.now().strftime("%Y-%m-%d"),
    expiration_date_lte=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),
    strike_price_gte=100,
    strike_price_lte=200,
    limit=100
)

contracts = client.get_option_contracts(request)
contract = contracts.option_contracts[0]

# Trade con contract ID
order_request = MarketOrderRequest(
    symbol=contract.id,  # Usar ID del contract
    qty=1,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY
)

Ejercitar Opción

python
# Ejercer una posición de opción
client.exercise_options(position_id)

Crypto Trading

Listar Symbols Disponibles

python
from alpaca.trading.enums import AssetClass

crypto_assets = client.get_all_assets(asset_class=AssetClass.CRYPTO)
crypto = [a for a in crypto_assets if a.tradable]
print(f"Crypto tradables: {[a.symbol for a in crypto[:10]]}")

Órdenes de Crypto

python
order_request = MarketOrderRequest(
    symbol="BTC/USD",
    qty=0.1,  # Fracciones permitidas
    side=OrderSide.BUY,
    time_in_force=TimeInForce.GTC
)
client.submit_order(order_request)

Market Hours

Obtener Clock

python
clock = client.get_clock()
print(f"Market open: {clock.is_open}")
print(f"Next open: {clock.next_open}")
print(f"Next close: {clock.next_close}")

Verificar si Mercado está Abierto

python
if clock.is_open:
    print("Mercado abierto - puedes tradear")
else:
    print("Mercado cerrado")

Portfolio History

python
from datetime import datetime

history = client.get_account_portfolio_history(
    date_start=datetime(2024, 1, 1),
    timeframe="1D"
)

print(f"Equity: {history.equity}")
print(f"Profit/Loss: {history.profit_loss}")

Watchlists

python
from alpaca.trading.requests import CreateWatchlistRequest

# Crear watchlist
watchlist = client.create_watchlist(
    CreateWatchlistRequest(name="Tech Stocks")
)

# Agregar símbolo
client.add_to_watchlist(watchlist.id, "AAPL")

# Obtener watchlists
watchlists = client.get_watchlists()

WebSocket Streaming

python
from alpaca.trading.stream import TradingStream

async def handle_trade_update(data):
    print(f"Update: {data}")

stream = TradingStream(API_KEY, SECRET_KEY, paper=True)

stream.subscribe_trade_updates(handle_trade_update)
stream.run()

Scripts de Ejemplo

Ver ./scripts/:

bash
# Ver cuenta
python ./scripts/check_account.py

# Ver posiciones
python ./scripts/check_positions.py

# Enviar orden de prueba
python ./scripts/place_order.py --symbol AAPL --qty 10 --side buy --type market

Errores Comunes

ErrorCausaSolución
403 ForbiddenKeys inválidasVerificar API keys
403Sin permisosHabilitar en dashboard
400 Bad RequestParámetros inválidosVer docs de orden
403 Trading HaltedTrading pausadoEsperar o verificar
403 No Buying PowerSin fondosDepositar dinero
422Symbol no tradableVerificar symbol
429 Too Many RequestsRate limitImplementar backoff

Comparación: Paper vs Live

AspectoPaperLive
URLpaper-api.alpaca.marketsapi.alpaca.markets
Dinero real❌ No✅ Sí
Órdenes reales❌ Simuladas✅ Reales
Datos de mercado✅ Reales✅ Reales
Para testing✅ Ideal❌ No

Siempre probar en paper primero.

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Alpaca Trading AI skill do?

Trading API de Alpaca: órdenes, posiciones, cuenta. Paper trading y live trading de acciones, crypto y opciones.

Why use Alpaca Trading on TypingMind?

Because you install it once and use it with any model. Alpaca Trading is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Alpaca Trading in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/gauss314/skills/tree/main/skills/alpaca-trading. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Alpaca Trading?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Alpaca Trading?

As many as you like. As long as a model supports skills, you can use Alpaca Trading with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Alpaca Trading AI skill free?

Yes. It is published on GitHub by gauss314 under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇