← Square + Alpaca integrations

List Orders with Alpaca API on New Order Created from Square API

Pipedream makes it easy to connect APIs for Alpaca, Square and 3,000+ other apps remarkably fast.

Trigger workflow on
New Order Created from the Square API
Next, do this
List Orders with the Alpaca API
No credit card required
Intro to Pipedream
Watch us build a workflow
Watch us build a workflow
8 min
Watch now ➜

Trusted by 1,000,000+ developers from startups to Fortune 500 companies

Adyen logo
Appcues logo
Bandwidth logo
Checkr logo
ChartMogul logo
Dataminr logo
Gopuff logo
Gorgias logo
LinkedIn logo
Logitech logo
Replicated logo
Rudderstack logo
SAS logo
Scale AI logo
Webflow logo
Warner Bros. logo
Adyen logo
Appcues logo
Bandwidth logo
Checkr logo
ChartMogul logo
Dataminr logo
Gopuff logo
Gorgias logo
LinkedIn logo
Logitech logo
Replicated logo
Rudderstack logo
SAS logo
Scale AI logo
Webflow logo
Warner Bros. logo

Developers Pipedream

Getting Started

This integration creates a workflow with a Square trigger and Alpaca action. When you configure and deploy the workflow, it will run on Pipedream's servers 24x7 for free.

  1. Select this integration
  2. Configure the New Order Created trigger
    1. Connect your Square account
    2. Configure timer
    3. Select a Location
  3. Configure the List Orders action
    1. Connect your Alpaca account
    2. Optional- Configure Paper API
    3. Optional- Configure Symbols
    4. Optional- Select a Side
    5. Optional- Select a Status
    6. Optional- Configure After
    7. Optional- Configure Until
    8. Optional- Configure Nested
  4. Deploy the workflow
  5. Send a test event to validate your setup
  6. Turn on the trigger

Details

This integration uses pre-built, source-available components from Pipedream's GitHub repo. These components are developed by Pipedream and the community, and verified and maintained by Pipedream.

To contribute an update to an existing component or create a new component, create a PR on GitHub. If you're new to Pipedream component development, you can start with quickstarts for trigger span and action development, and then review the component API reference.

Trigger

Description:Emit new event for every new order created. [See the docs](https://developer.squareup.com/reference/square/orders-api/search-orders)
Version:0.0.3
Key:square-new-order-created

Square Overview

The Square API opens up a realm of possibilities for merchants to effortlessly manage their sales, inventory, customers, and payments. With Pipedream, you can automate actions based on events in Square, such as new transactions, updated orders, or customer profile changes. Craft custom workflows that react in real-time, sync data across platforms, or streamline reporting. Through Pipedream's serverless platform, you can connect Square with countless other apps without writing extensive code, turning manual tasks into automated, efficient processes.

Trigger Code

import base from "../common/base-polling.mjs";
import constants from "../common/constants.mjs";

export default {
  ...base,
  key: "square-new-order-created",
  name: "New Order Created",
  description: "Emit new event for every new order created. [See the docs](https://developer.squareup.com/reference/square/orders-api/search-orders)",
  type: "source",
  version: "0.0.3",
  dedupe: "unique",
  props: {
    ...base.props,
    location: {
      propDefinition: [
        base.props.square,
        "location",
      ],
    },
  },
  hooks: {
    ...base.hooks,
    async deploy() {
      console.log(`Retrieving at most last ${constants.MAX_HISTORICAL_EVENTS} objects...`);
      const { order_entries: orders } = await this.square.listOrders({
        data: {
          ...this.getBaseParams(),
        },
      });
      if (!(orders?.length > 0)) {
        return;
      }
      this._setLastTs(Date.parse(orders[0].created_at));
      orders?.slice(0, constants.MAX_HISTORICAL_EVENTS)
        .reverse()
        .forEach((order) => this.$emit(order, this.generateMeta(order)));
    },
  },
  methods: {
    ...base.methods,
    getBaseParams() {
      return {
        limit: constants.MAX_LIMIT,
        location_ids: [
          this.location,
        ],
        query: {
          sort: {
            sort_field: "CREATED_AT",
            sort_order: "DESC",
          },
        },
      };
    },
    generateMeta(order) {
      return {
        id: order.id,
        summary: `Order created: ${order.id}`,
        ts: Date.parse(order.created_at),
      };
    },
  },
  async run() {
    const lastTs = this._getLastTs();
    let newLastTs;
    let cursor;
    let done = false;

    do {
      const response = await this.square.listOrders({
        data: {
          ...this.getBaseParams(),
          cursor,
        },
      });
      const { orders } = response;
      if (!(orders?.length > 0)) {
        break;
      }
      if (!newLastTs) {
        newLastTs = Date.parse(orders[0].created_at);
      }
      for (const order of orders) {
        if (Date.parse(order.created_at) <= lastTs) {
          done = true;
          break;
        }
        this.emitEvent(order);
      }
      cursor = response?.cursor;
    } while (cursor && !done);

    this._setLastTs(newLastTs);
  },
};

Trigger Configuration

This component may be configured based on the props defined in the component code. Pipedream automatically prompts for input values in the UI and CLI.
LabelPropTypeDescription
SquaresquareappThis component uses the Square app.
N/Adb$.service.dbThis component uses $.service.db to maintain state between executions.
timer$.interface.timer
LocationlocationstringSelect a value from the drop down menu.

Trigger Authentication

Square uses OAuth authentication. When you connect your Square account, Pipedream will open a popup window where you can sign into Square and grant Pipedream permission to connect to your account. Pipedream securely stores and automatically refreshes the OAuth tokens so you can easily authenticate any Square API.

Pipedream requests the following authorization scopes when you connect your account:

CUSTOMERS_READCUSTOMERS_WRITEPAYMENTS_READPAYMENTS_WRITEORDERS_READORDERS_WRITESUBSCRIPTIONS_READSUBSCRIPTIONS_WRITEITEMS_READITEMS_WRITEINVOICES_READINVOICES_WRITELOYALTY_READLOYALTY_WRITEEMPLOYEES_READEMPLOYEES_WRITEMERCHANT_PROFILE_READBANK_ACCOUNTS_READSETTLEMENTS_READDEVELOPER_APPLICATION_WEBHOOKS_WRITEAPPOINTMENTS_ALL_READAPPOINTMENTS_READ

About Square

Solutions & Tools to Grow Your Business

Action

Description:Retrieves a list of orders for the account, filtered by the supplied query parameters, if no filter given all will be returned, [See the docs](https://alpaca.markets/docs/api-references/trading-api/orders/#get-a-list-of-orders)
Version:0.0.2
Key:alpaca-list-orders

Alpaca Overview

Alpaca API allows you to harness the power of automated trading by providing an interface to manage your stock and equity portfolio through simple API calls. It's particularly suited for building trading bots, algorithmic trading strategies, or just automating interactions with your investment portfolio. Whether you're looking to place trades based on specific market conditions, automatically adjust your portfolio in response to certain triggers, or simply streamline your investment activities, Alpaca's trading API offers a robust solution.

Action Code

import app from "../../alpaca.app.mjs";
import { ConfigurationError } from "@pipedream/platform";

export default {
  type: "action",
  key: "alpaca-list-orders",
  version: "0.0.2",
  annotations: {
    destructiveHint: false,
    openWorldHint: true,
    readOnlyHint: true,
  },
  name: "List Orders",
  description: "Retrieves a list of orders for the account, filtered by the supplied query parameters, if no filter given all will be returned, [See the docs](https://alpaca.markets/docs/api-references/trading-api/orders/#get-a-list-of-orders)",
  props: {
    app,
    isPaperAPI: {
      propDefinition: [
        app,
        "isPaperAPI",
      ],
    },
    //the API does not provide pagination for symbols,
    //returns all at once and there are more than 3k symbols
    //because of these I preferred to get them from user input
    symbols: {
      type: "string[]",
      label: "Symbols",
      description: "A list of symbols to filter by (ex. `AAPL,TSLA,MSFT`). A currency pair is required for crypto orders (ex. `BTC/USD,BCH/USD,LTC/USDT,ETC/USDT`).",
      optional: true,
    },
    side: {
      propDefinition: [
        app,
        "side",
      ],
      description: "Filters down to orders that have a matching `side` field set.",
      optional: true,
    },
    status: {
      type: "string",
      label: "Status",
      description: "Order status to be queried. `open`, `closed` or `all`. Defaults to `open`.",
      optional: true,
      options: [
        "open",
        "closed",
        "all",
      ],
    },
    after: {
      type: "string",
      label: "After",
      description: "The response will include only ones submitted after this time, in ISO 8601 format, e.g. `2022-09-07` or `2022-09-07T13:26:53`",
      optional: true,
    },
    until: {
      type: "string",
      label: "Until",
      description: "The response will include only ones submitted until this time, in ISO 8601 format, e.g. `2022-09-07` or `2022-09-07T13:26:53`",
      optional: true,
    },
    nested: {
      type: "string",
      label: "Nested",
      description: "If true, the result will roll up multi-leg orders under the `legs` field of primary order.",
      optional: true,
    },
  },
  async run ({ $ }) {
    const after = this.after && Date.parse(this.after);
    if (this.after && isNaN(after))
      throw new ConfigurationError("`After` should be in ISO 8601 format!");
    const until = this.until && Date.parse(this.until);
    if (this.until && isNaN(until))
      throw new ConfigurationError("`Until` should be in ISO 8601 format!");
    let pageSize = 25, orders = [], nextAfter = after && new Date(after).toISOString();
    while (true) {
      const response = await this.app.getOrders({
        $,
        isPaperAPI: this.isPaperAPI,
        params: {
          symbols: this.symbols && this.symbols.join(),
          side: this.side,
          status: this.status,
          after: nextAfter,
          until: until && new Date(until).toISOString(),
          nested: this.nested,
          direction: "asc",
          limit: pageSize,
        },
      });
      orders.push(...response);
      if (response.length < pageSize) {
        break;
      } else {
        nextAfter = response.pop().updated_at;
      }
    }
    // eslint-disable-next-line multiline-ternary
    $.export("$summary", `${orders.length} order${orders.length == 1 ? "" : "s"} has been retrieved.`);
    return orders;
  },
};

Action Configuration

This component may be configured based on the props defined in the component code. Pipedream automatically prompts for input values in the UI.

LabelPropTypeDescription
AlpacaappappThis component uses the Alpaca app.
Paper APIisPaperAPIboolean

Set to true if Paper API is used. Default is false.

Symbolssymbolsstring[]

A list of symbols to filter by (ex. AAPL,TSLA,MSFT). A currency pair is required for crypto orders (ex. BTC/USD,BCH/USD,LTC/USDT,ETC/USDT).

SidesidestringSelect a value from the drop down menu:buysell
StatusstatusstringSelect a value from the drop down menu:openclosedall
Afterafterstring

The response will include only ones submitted after this time, in ISO 8601 format, e.g. 2022-09-07 or 2022-09-07T13:26:53

Untiluntilstring

The response will include only ones submitted until this time, in ISO 8601 format, e.g. 2022-09-07 or 2022-09-07T13:26:53

Nestednestedstring

If true, the result will roll up multi-leg orders under the legs field of primary order.

Action Authentication

Alpaca uses OAuth authentication. When you connect your Alpaca account, Pipedream will open a popup window where you can sign into Alpaca and grant Pipedream permission to connect to your account. Pipedream securely stores and automatically refreshes the OAuth tokens so you can easily authenticate any Alpaca API.

Pipedream requests the following authorization scopes when you connect your account:

account:writetradingdata

About Alpaca

Commission-Free API First Stock Brokerage

More Ways to Connect Alpaca + Square

Cancel All Orders with Alpaca API on Catalog Item Updated from Square API
Square + Alpaca
 
Try it
Cancel Order with Alpaca API on Catalog Item Updated from Square API
Square + Alpaca
 
Try it
Close All Positions with Alpaca API on Catalog Item Updated from Square API
Square + Alpaca
 
Try it
Close Position with Alpaca API on Catalog Item Updated from Square API
Square + Alpaca
 
Try it
Get Account Info with Alpaca API on Catalog Item Updated from Square API
Square + Alpaca
 
Try it
Catalog Item Updated from the Square API

Emit new event every time a catalog item is updated. See the docs

 
Try it
New Booking Created from the Square API

Emit new event for every new booking created. See the docs

 
Try it
New Customer Created from the Square API

Emit new event for every new customer created. See the docs

 
Try it
New Invoice Created from the Square API

Emit new event for every new invoice created. See the docs

 
Try it
New Order Created from the Square API

Emit new event for every new order created. See the docs

 
Try it
Create Customer with the Square API

Creates a new customer for a business. Must provide at least one of the following: Given Name, Family Name, Company Name, Email Address, or Phone Number. See the docs

 
Try it
Create Invoice with the Square API

Creates a draft invoice for an order. You must send (publish) the invoice before Square can process it. See the documentation

 
Try it
Create Order with the Square API

Creates a new order that can include information about products for purchase. See docs here

 
Try it
Send Invoice with the Square API

Publishes the latest version of a specified invoice. See the docs

 
Try it
Cancel All Orders with the Alpaca API

Attempts to cancel all open orders. A response will be provided for each order that is attempted to be cancelled. If an order is no longer cancelable, the server reject the request, See the docs

 
Try it

Explore Other Apps

1
-
24
of
3,000+
apps by most popular

Node
Node
Anything you can do with Node.js, you can do in a Pipedream workflow. This includes using most of npm's 400,000+ packages.
Python
Python
Anything you can do in Python can be done in a Pipedream Workflow. This includes using any of the 350,000+ PyPi packages available in your Python powered workflows.
Notion
Notion
Notion is a new tool that blends your everyday work apps into one. It's the all-in-one workspace for you and your team.
OpenAI (ChatGPT)
OpenAI (ChatGPT)
OpenAI is an AI research and deployment company with the mission to ensure that artificial general intelligence benefits all of humanity. They are the makers of popular models like ChatGPT, DALL-E, and Whisper.
Anthropic (Claude)
Anthropic (Claude)
AI research and products that put safety at the frontier. Introducing Claude, a next-generation AI assistant for your tasks, no matter the scale.
Google Sheets
Google Sheets
Use Google Sheets to create and edit online spreadsheets. Get insights together with secure sharing in real-time and from any device.
Telegram
Telegram
Telegram, is a cloud-based, cross-platform, encrypted instant messaging (IM) service.
Google Drive
Google Drive
Google Drive is a file storage and synchronization service which allows you to create and share your work online, and access your documents from anywhere.
HTTP / Webhook
HTTP / Webhook
Get a unique URL where you can send HTTP or webhook requests
Google Calendar
Google Calendar
With Google Calendar, you can quickly schedule meetings and events and get reminders about upcoming activities, so you always know what’s next.
Schedule
Schedule
Trigger workflows on an interval or cron schedule.
Pipedream Utils
Pipedream Utils
Utility functions to use within your Pipedream workflows
Shopify
Shopify
Shopify is a complete commerce platform that lets anyone start, manage, and grow a business. You can use Shopify to build an online store, manage sales, market to customers, and accept payments in digital and physical locations.
Supabase
Supabase
Supabase is an open source Firebase alternative.
MySQL
MySQL
MySQL is an open-source relational database management system.
PostgreSQL
PostgreSQL
PostgreSQL is a free and open-source relational database management system emphasizing extensibility and SQL compliance.
AWS
AWS
Premium
Amazon Web Services (AWS) offers reliable, scalable, and inexpensive cloud computing services.
Twilio SendGrid
Twilio SendGrid
Premium
Send marketing and transactional email through the Twilio SendGrid platform with the Email API, proprietary mail transfer agent, and infrastructure for scalable delivery.
Amazon SES
Amazon SES
Amazon SES is a cloud-based email service provider that can integrate into any application for high volume email automation
Klaviyo
Klaviyo
Premium
Klaviyo unifies your data, channels, and AI agents in one platform—text, WhatsApp, email marketing, and more—driving growth with every interaction.
Zendesk
Zendesk
Premium
Zendesk is award-winning customer service software trusted by 200K+ customers. Make customers happy via text, mobile, phone, email, live chat, social media.
ServiceNow
ServiceNow
Premium
Beta
The smarter way to workflow
Slack
Slack
Slack is the AI-powered platform for work bringing all of your conversations, apps, and customers together in one place. Around the world, Slack is helping businesses of all sizes grow and send productivity through the roof.
Microsoft Teams
Microsoft Teams
Microsoft Teams has communities, events, chats, channels, meetings, storage, tasks, and calendars in one place.