Back to Catalog

Automated stock trading with AI: integrating Alpaca and Google Sheets

Raz HadasRaz Hadas
22531 views
2/3/2026
Official Page

Description

Transform your investment strategy with a fully automated, AI-driven trading bot. This workflow bridges the gap between AI-powered market insights and real-world trading by executing buy and sell orders directly through the Alpaca paper trading API.

Designed to work in tandem with the Automated Stock Sentiment Analysis workflow, this solution takes the top-performing stocks based on daily news sentiment and automatically rebalances your portfolio. It's perfect for algorithmic traders, data-driven investors, and n8n enthusiasts who want to see their AI analysis translate into tangible actions, all while maintaining a comprehensive log of every transaction in Google Sheets.

Key Features & Benefits

  • Automated Trading Execution: Automatically places buy and sell orders on the Alpaca paper trading platform without manual intervention.
  • Sentiment-Driven Decisions: Leverages the output from the sentiment analysis workflow to make informed decisions, selling positions with waning sentiment and buying into those with high positive sentiment.
  • Dynamic Portfolio Rebalancing: Intelligently calculates which positions to close and how to allocate the resulting funds into new, high-potential stocks.
  • Paper Trading Ready: Safely test and refine your trading strategies in a risk-free environment using Alpaca's paper trading API.
  • Daily Performance Tracking: Automatically logs your account equity and daily percentage change to a Google Sheet, giving you a clear view of your portfolio's performance.
  • Detailed Trade Logging: Every buy and sell order is meticulously recorded in a Google Sheet for easy review and historical analysis.
  • Scheduled and Autonomous: The entire process runs on a daily schedule, making it a "set and forget" solution for systematic trading.

How It Works

This workflow executes a sophisticated, automated trading strategy in a few key stages:

  1. Daily Kick-off & Snapshot: The workflow triggers on a daily schedule, first fetching your current Alpaca account balance and logging it to a Google Sheet to track daily performance.
  2. Strategy Formulation: It then reads the daily sentiment scores produced by the accompanying "Stock Sentiment Analysis" workflow. A Code node filters these results to identify the top four stocks with the highest positive sentiment.
  3. The Decision Engine: The core of the workflow is a custom Code node that acts as the trading brain. It:
    • Retrieves your currently open positions from Alpaca.
    • Compares your holdings against the day's top four sentiment stocks.
    • Generates a "sell list" of positions you hold that are no longer in the top four.
    • Generates a "buy list" of top-sentiment stocks that you don't yet own.
    • Calculates the total cash value from the "sell list" and determines the exact notional value to invest in each stock on the "buy list."
  4. Trade Execution:
    • The workflow first iterates through the "sell list" and executes a DELETE request to Alpaca for each, closing the positions.
    • A Wait node pauses the workflow for two minutes to ensure the sell orders are filled and the account balance is updated.
    • It then iterates through the "buy list," executing POST requests to Alpaca to purchase the new assets with the calculated funds.
  5. Record Keeping: All executed orders (both buys and sells) are merged and logged in a dedicated Google Sheet, giving you a permanent and detailed transaction history.

Nodes Used

  • Schedule Trigger
  • HttpRequest (Alpaca API)
  • Google Sheets
  • Code (JavaScript)
  • SplitOut
  • Wait
  • Merge

This workflow is the perfect next step for anyone looking to take their AI analysis to the next level. Take the emotion out of your trading and let this bot systematically execute your data-driven strategy.

Automated Stock Trading with AI: Integrating Alpaca and Google Sheets

This n8n workflow automates the process of executing stock trades based on signals from a Google Sheet, integrating with the Alpaca trading API. It allows users to define trading parameters in a spreadsheet and have the workflow automatically place buy or sell orders.

What it does

This workflow streamlines your trading strategy by:

  1. Triggering on a Schedule: The workflow is designed to run at regular intervals (e.g., daily, hourly) to check for new trading signals.
  2. Reading Trading Signals from Google Sheets: It connects to a specified Google Sheet to read rows containing trading instructions (e.g., stock symbol, action, quantity).
  3. Processing Each Trading Signal: For each row read from Google Sheets, the workflow processes it individually.
  4. Executing Trades via Alpaca API: It makes an HTTP request to the Alpaca API to place buy or sell orders based on the data from Google Sheets.
  5. Introducing a Delay Between Trades: A short pause is introduced between each trade execution to prevent overwhelming the API or hitting rate limits.

Prerequisites/Requirements

To use this workflow, you will need:

  • n8n Instance: A running instance of n8n.
  • Google Account: Access to Google Sheets with a spreadsheet containing your trading signals.
  • Alpaca Account: An Alpaca trading account with API keys (Paper or Live).
  • n8n Credentials:
    • Google Sheets API Credential: Configured in n8n to allow access to your Google Sheets.
    • Alpaca API Credential: Configured in n8n to authenticate with the Alpaca trading platform.

Setup/Usage

  1. Import the Workflow:
    • Download the provided JSON file.
    • In your n8n instance, go to "Workflows" and click "New".
    • Click the "Import from JSON" button and paste the workflow JSON or upload the file.
  2. Configure Credentials:
    • Locate the "Google Sheets" node (ID: 18) and configure your Google Sheets API credential. Ensure it has access to the spreadsheet you intend to use.
    • Locate the "HTTP Request" node (ID: 19) which interacts with Alpaca. You will need to set up an HTTP Basic Auth or API Key credential for Alpaca, using your Alpaca API Key ID and Secret Key.
  3. Specify Google Sheet Details:
    • In the "Google Sheets" node (ID: 18), specify the "Spreadsheet ID" and "Sheet Name" where your trading signals are located.
  4. Customize Alpaca API Call:
    • In the "HTTP Request" node (ID: 19), review the URL, HTTP Method (likely POST), and Body content. This is where you'll map the data from your Google Sheet to the Alpaca API's order placement parameters (e.g., symbol, qty, side, type, time_in_force).
  5. Set Schedule:
    • Configure the "Schedule Trigger" node (ID: 839) to your desired frequency (e.g., every 5 minutes, once a day).
  6. Activate the Workflow:
    • Save the workflow and toggle it "Active" to start automated trading.

Important Note: Trading involves significant risk. Always test with a paper trading account (Alpaca offers this) before using live funds. Review the "Code" node (ID: 834) and "Sticky Note" (ID: 565) for any specific instructions or logic embedded by the original author, as they often contain critical details or custom transformations. The "Wait" node (ID: 514) is crucial for rate limiting and should be configured appropriately for the Alpaca API.

Related Templates

AI multi-agent executive team for entrepreneurs with Gemini, Perplexity and WhatsApp

This workflow is an AI-powered multi-agent system built for startup founders and small business owners who want to automate decision-making, accountability, research, and communication, all through WhatsApp. The β€œvirtual executive team,” is designed to help small teams to work smarter. This workflow sends you market analysis, market and sales tips, It can also monitor what your competitors are doing using perplexity (Research agent) and help you stay a head, or make better decisions. And when you feeling stuck with your start-up accountability director is creative enough to break the barrier 🎯 Core Features πŸ§‘β€πŸ’Ό 1. President (Super Agent) Acts as the main controller that coordinates all sub-agents. Routes messages, assigns tasks, and ensures workflow synchronization between the AI Directors. πŸ“Š 2. Sales & Marketing Director Uses SerpAPI to search for market opportunities, leads, and trends. Suggests marketing campaigns, keywords, or outreach ideas. Can analyze current engagement metrics to adjust content strategy. πŸ•΅οΈβ€β™€οΈ 3. Business Research Director Powered by Perplexity AI for competitive and market analysis. Monitors competitor moves, social media engagement, and product changes. Provides concise insights to help the founder adapt and stay ahead. ⏰ 4. Accountability Director Keeps the founder and executive team on track. Sends motivational nudges, task reminders, and progress reports. Promotes consistency and discipline β€” key traits for early-stage success. πŸ—“οΈ 5. Executive Secretary Handles scheduling, email drafting, and reminders. Connects with Google Calendar, Gmail, and Sheets through OAuth. Automates follow-ups, meeting summaries, and notifications directly via WhatsApp. πŸ’¬ WhatsApp as the Main Interface Interact naturally with your AI team through WhatsApp Business API. All responses, updates, and summaries are delivered to your chat. Ideal for founders who want to manage operations on the go. βš™οΈ How It Works Trigger: The workflow starts from a WhatsApp Trigger node (via Meta Developer Account). Routing: The President agent analyzes the incoming message and determines which Director should handle it. Processing: Marketing or sales queries go to the Sales & Marketing Director. Research questions are handled by the Business Research Director. Accountability tasks are assigned to the Accountability Director. Scheduling or communication requests are managed by the Secretary. Collaboration: Each sub-agent returns results to the President, who summarizes and sends the reply back via WhatsApp. Memory: Context is maintained between sessions, ensuring personalized and coherent communication. 🧩 Integrations Required Gemini API – for general intelligence and task reasoning Supabase- for RAG and postgres persistent memory Perplexity API – for business and competitor analysis SerpAPI – for market research and opportunity scouting Google OAuth – to connect Sheets, Calendar, and Gmail WhatsApp Business API – for message triggers and responses πŸš€ Benefits Acts like a team of tireless employees available 24/7. Saves time by automating research, reminders, and communication. Enhances accountability and strategy consistency for founders. Keeps operations centralized in a simple WhatsApp interface. 🧰 Setup Steps Create API credentials for: WhatsApp (via Meta Developer Account) Gemini, Perplexity, and SerpAPI Google OAuth (Sheets, Calendar, Gmail) Create a supabase account at supabase Add the credentials in the corresponding n8n nodes. Customize the system prompts for each Director based on your startup’s needs. Activate and start interacting with your virtual executive team on WhatsApp. Use Case You are a small organisation or start-up that can not afford hiring; marketing department, research department and secretar office, then this workflow is for you πŸ’‘ Need Customization? Want to tailor it for your startup or integrate with CRM tools like Notion or HubSpot? You can easily extend the workflow or contact the creator for personalized support. Consider adjusting the system prompt to suite your business

ShadrackBy Shadrack
331

Automated YouTube video uploads with 12h interval scheduling in JST

This workflow automates a batch upload of multiple videos to YouTube, spacing each upload 12 hours apart in Japan Standard Time (UTC+9) and automatically adding them to a playlist. βš™οΈ Workflow Logic Manual Trigger β€” Starts the workflow manually. List Video Files β€” Uses a shell command to find all .mp4 files under the specified directory (/opt/downloads/单词卑/A1-A2). Sort and Generate Items β€” Sorts videos by day number (dayXX) extracted from filenames and assigns a sequential order value. Calculate Publish Schedule (+12h Interval) β€” Computes the next rounded JST hour plus a configurable buffer (default 30 min). Staggers each video’s scheduled time by order Γ— 12 hours. Converts JST back to UTC for YouTube’s publishAt field. Split in Batches (1 per video) β€” Iterates over each video item. Read Video File β€” Loads the corresponding video from disk. Upload to YouTube (Scheduled) β€” Uploads the video privately with the computed publishAtUtc. Add to Playlist β€” Adds the newly uploaded video to the target playlist. πŸ•’ Highlights Timezone-safe: Pure UTC ↔ JST conversion avoids double-offset errors. Sequential scheduling: Ensures each upload is 12 hours apart to prevent clustering. Customizable: Change SPANHOURS, BUFFERMIN, or directory paths easily. Retry-ready: Each upload and playlist step has retry logic to handle transient errors. πŸ’‘ Typical Use Cases Multi-part educational video series (e.g., A1–A2 English learning). Regular content release cadence without manual scheduling. Automated YouTube publishing pipelines for pre-produced content. --- Author: Zane Category: Automation / YouTube / Scheduler Timezone: JST (UTC+09:00)

ZaneBy Zane
226

Monitor bank transactions with multi-channel alerts for accounting teams

Enhance financial oversight with this automated n8n workflow. Triggered every 5 minutes, it fetches real-time bank transactions via an API, enriches and transforms the data, and applies smart logic to detect critical, high, and medium priority alerts based on error conditions, amounts, or risk scores. It sends multi-channel notifications via email and Slack, logs all data to Google Sheets, and generates summary statistics for comprehensive tracking. πŸ’°πŸš¨ Key Features Real-time monitoring every 5 minutes for instant alerts. Smart prioritization (Critical, High, Medium) based on risk and errors. Multi-channel notifications via email and Slack. Detailed logging and summary reports in Google Sheets. How It Works Schedule Trigger: Runs every 5 minutes. Fetch Transactions: HTTP request retrieves real-time transaction data. API Error?: If condition for error logic is met, sends error alert. Enrich & Transform Data: Advanced risk calculation enhances data. Critical Alert?: If condition (50% or risk > 8) is met, raises alert. High Priority?: If condition (5% or risk > 7) is met, raises alert. Medium Priority?: If condition is met, raises alert. Log Priority to Sheet: Google Sheets appends critical, high, or medium priority data. Send Critical Email: HTML email to execute sheets append. Send High Priority Email: Email to finance team. Send High Priority Slack: Slack notification to finance team. Send Medium Priority Email: Email to finance team. Merge All Alerts: Combines all alerts for comprehensive tracking. Generate Summary Stats: Code block for analytics. Log Summary to Sheet: Summary statistics storage. Setup Instructions Import the workflow into n8n and configure the bank API credentials in "Fetch Transactions." Set up Google Sheets OAuth2 and replace the sheet ID for logging nodes. Configure Gmail API Key and Slack Bot Token for alerts. Test the workflow with sample transaction data exceeding risk or amount thresholds. Adjust priority conditions (e.g., 50%, 5%, risk > 8) based on your risk policy. Prerequisites Bank API access with real-time transaction data (e.g., https://api.bank.com) Google Sheets OAuth2 credentials Gmail API Key for email alerts Slack Bot Token (with chat:write permissions) Structured transaction data format Google Sheet Structure: Create a sheet with columns: Transaction ID Amount Date Risk Score Priority (Critical/High/Medium) Alert Sent Summary Stats Updated At Modification Options Adjust the "Schedule Trigger" interval (e.g., every 10 minutes). Modify "Critical Alert?" and "High Priority?" conditions for custom thresholds. Customize email and Slack templates with branded messaging. Integrate with fraud detection tools for enhanced risk analysis. Enhance "Generate Summary Stats" with additional metrics (e.g., average risk). Discover more workflows – Get in touch with us

Oneclick AI SquadBy Oneclick AI Squad
333