Create Rules and Alerts Using the API#

Here we’ll demonstrate creating a rule using the API. We’ll start with a code example that creates a rule using the POST /rules/create method. The method request body specifies the rule. We’ll examine each part of the request body and explain where to find supported values.

Prerequisite

IEX Cloud Apperate Account - Create an account here.

Example Rule Code#

Here’s example JavaScript code that creates a rule.

'use strict';

const Request = require('request-promise-native');

function connect() {
  Request({
    method: 'POST',
    url: 'https://api.iex.cloud/v1/rules/create',
    json: {
      token: 'YOUR_TOKEN',
      ruleName: "Simple Rule",
      type: "any",
      index: [ "CORE:STOCK:AAPL:latestPrice", "CORE:STOCK:AAPL:peRatio" ],
      conditions: [
        ["$index[0]",">",150],
        ["$index[1]","<",20]
      ],
      outputs: [
        {
          method: "email",
          to: "person@company.com",
          subject: "Rule alert!",
          message: "Here's the alert message.",
          frequency: 60
        }
      ],
      additionalIndex: [
        "CORE:STOCK:MSFT:high",
        "CORE:STOCK:AMZN:high"
      ]
    },
  }).then((body) => {
    console.log(body);
  }).catch((err) => {
    console.log("Error in request", err);
  });
}
​
connect();

The code creates a rule by making an HTTP POST to the https://api.iex.cloud/v1/rules/create endpoint.

The above rule triggers on either of the following events:

  • Apple’s stock is above 150

  • Apple’s price-to-earnings ratio is below 20

When the rule triggers, it emails person@company.com the event facts (i.e., Apple’s latest price and P/E ratio) and the additional indexes (i.e., Microsoft’s high for the day and Twitter’s high for the day).

See also

See the POST /rules/create method reference documentation for endpoint details.

Running the Example#

  1. Copy the example code into your own .js file.

  2. Replace YOUR_TOKEN with your secret API token value. Important: Never share your secret token publicly.

  3. Replace the email address with your email address.

  4. You can use Node.js to install the dependencies and run the example.

    node your-file.js
    

The call to POST /rules/create creates a rule and activates it.

When any of the rule’s conditions are true, the rule sends the above mentioned indexes and additional indexes in an email.

Important

New rules are automatically activated by default. When you’re done using a rule, you can deactivate it by calling the POST /rules/pause/:ruleId or by clicking the rule’s pause button in the rules dashboard.

Creating a Rule#

Let’s examine how to create a rule like the example rule above. We’ll focus on the parameter values passed to the POST /rules/create method.

Parameter summary:

  • token: Secret API token with permission to create rules. See Step 2.

  • ruleName: Arbitrary rule name. See Step 2.

  • type: Whether any or all the conditions must be true for the Rule to take action. See Step 3.

  • index: Facts to use in the conditions. See Step 4.

  • conditions: Fact conditions to check. See Step 5.

  • outputs: Destinations for outputing the index facts and additionalIndex facts. See Step 6.

  • additionalIndex: Additional facts to include in the output. See Step 7.

Start with entering your HTTP method and endpoint URL.

Step 1: Enter the Method and URL#

The example code makes the HTTP request using the request-promise-native module’s connect() method. It takes an HTTP method and a URL via the respective method and url parameters.

The example code:

method: 'POST',
url: 'https://api.iex.cloud/v1/rules/create',

Note

You can use whatever HTTP request module you like.

Step 2: Start Setting POST Parameters#

The POST parameters are specified using a JSON object.

The example code:

json: {
  token: 'YOUR_TOKEN',
  ruleName: "Simple Rule",
  // more parameters
}

For the remaining steps, we’ll specify parameters by adding them as attributes of the above JSON object.

The token and ruleName parameters are easy to specify. Enter your secret key as the token and an arbitrary rule name as the ruleName.

Next, it’s good to decide whether your rule should require any or all of its conditions to be true.

Step 3: Decide if Any or All Conditions Must Be True#

If you want your rule to send outputs on any of its conditions being true, then set type: "any". If you want all conditions to be met, set type: "all".

type

Description

any

Any true condition triggers the rule to send notifications.

all

All conditions must be true to trigger the rule to send notifications.

The example code:

type: "any"

The example code sets the rule to output if any conditions are true.

Step 4: Enter Facts to Filter On#

Rule conditions operate on facts specified via the index array parameter. A fact is an attribute of a given event. Each fact can be specified as a string or an object. Rules can filter on these fact types:

  • Core stock facts

  • Core market facts

  • Your own private data facts

Rule conditions (demonstrated in the next step) compare facts with specified values.

The example code:

index: [ "CORE:STOCK:AAPL:latestPrice", "CORE:STOCK:AAPL:peRatio" ],

The example code uses two facts: Apple’s latest price and Apple’s current price-to-earnings ratio.

Important

A condition’s facts must be specified via the rule’s index parameter.

Fact Characteristics#

Facts have four parts.

Fact Parts

Fact Part

Description

workspace

CORE workspace has stock facts and market facts.Core stock facts are in the CORE workspace.
YOUR_WORKSPACE (your workspace name in caps) has your workspace rule-registered dataset facts.

Important: The CORE workspace facts are based on data that makes sense to use in conditions–not all data is useful for conditions. Your workspace facts are based on all your private data–you can use whichever private data facts you find useful.

namespace

STOCK namespace has Core stock facts.
MARKET namespace has Core market facts.
DATASETS namespace has your workspace rule-registered dataset facts.

entity

Core stock facts use a stock symbol.
Core market facts use the region entity US.
Private data facts use a dataset name. You can use a GET /rules/schema command like the one below to list all rule-registered datasets

curl -X GET "https://api.iex.cloud/v1/rules/schema?token=YOUR_SECRET_TOKEN" | jq '.schema.workspaces[] | select(.workspace=="YOUR_WORKSPACE").namespaces[] | select(.namespace=="DATASET").entities[].entity'

fact

Each fact is an attribute of its entity. You can use commands like the ones below to get facts.

curl -X GET "https://api.iex.cloud/v1/rules/schema?token=YOUR_SECRET_TOKEN" | jq '.schema.workspaces[] | select(.workspace=="CORE").namespaces[] | select(.namespace=="STOCK").entities[] | select(.entity=="SYMBOL").facts[]'

curl -X GET "https://api.iex.cloud/v1/rules/schema?token=YOUR_SECRET_TOKEN" | jq '.schema.workspaces[] | select(.workspace=="CORE").namespaces[] | select(.namespace=="MARKET").entities[] | select(.entity=="REGION").facts[]'

curl -X GET "https://api.iex.cloud/v1/rules/schema?token=YOUR_SECRET_TOKEN" | jq '.schema.workspaces[] | select(.workspace=="YOUR_WORKSPACE").namespaces[] | select(.namespace=="DATASET").entities[]'

Tip

See GET /rules/schema for more example commands to look up workspaces, namespaces, entities, and facts.

You can specify facts using a string format or object format. The string format is easiest.

Fact string format:

WORKSPACE:NAMESPACE:ENTITY:FACT

Fact object format:

{"workspace": "SOME_WORKSPACE", "namespace": "SOME_NAMESPACE", "entity": "SOME_ENTITY", "fact": "SOME_FACT"}

Fact Examples#

Here are some example facts:

  • Apple stock high price: "CORE:STOCK:AAPL:high"

  • US market crude oil price: "CORE:MARKET:US:DCOILWTICO"

  • Customer first name in private data: "MY_WORKSPACE:DATASET:MY_EXISTING_USERS:firstname"

Add Your Facts to the index Array#

The index parameter takes an array of facts, in either string format and/or object format.

Here’s an index parameter with a Core stock fact, a Core market fact, and a private dataset fact:

index: [ "CORE:STOCK:AAPL:high", "CORE:MARKET:US:DCOILWTICO", "MY_WORKSPACE:DATASET:MY_EXISTING_USERS:firstname" ]

Next, set fact conditions to trigger your rule.

Step 5: Declare Your Conditions#

Your conditions determine when your rule fires.

The example code:

conditions: [
  ["$index[0]",">",150],
  ["$index[1]","<",20]
],

The example code has two conditions. If any of the conditions are true (remember type: "any" for the example), the rule fires. The first condition checks if the first index value (Apple’s latest price) is greater than 150. The second checks if the second index value (Apple’s P/E ratio) is below 20.

Each condition has a left side, middle, and right side parts:

  • left side: An index reference

  • middle: An operator

  • right side: A literal value or a referenced index value

Condition Operators:

Operator

Description

>

Is above/after

>=

Is above/after or equal to

<

Is below/before

<=

Is below/before or equal to

==

Is or equals

!=

Is not or is not equal to

Each condition must compare at least one of your index values with either a literal value or the value of another index.

Example comparing two indexes:

["$index[0]","<","$index[1]"]

Step 6: Specify Outputs#

When your rule fires, it can send output/notifications to several types of destinations, including these:

The outputs parameter is an array of output objects.

The example code:

outputs: [
  {
    method: "email",
    to: "person@company.com",
    subject: "Rule alert!",
    message: "Here's the alert message.",
    frequency: 60
  }
]

The example code specifies an email address to notify.

See also

The Rules API output reference pages describe the output types.

Step 7: Include Additional Facts#

Rules output the index fact values by default. They can also include other fact values via the additionalIndex parameter. This enables you to output helpful facts that aren’t part of your conditions.

The example code:

additionalIndex: [
  "CORE:STOCK:MSFT:high",
  "CORE:STOCK:AMZN:high"
]

The example code specifies Microsoft’s high stock price and Amazon’s high stock price for output.

Conclusion#

Congratulations! Now you know how to programatically create a rule. You can adjust this example code to create rules using JavaScript or call the POST /rules/create REST method using a different HTTP request module or language.

Important

New rules are automatically activated by default. When you’re done using a rule, you can deactivate it by clicking the rule’s pause button in the rules dashboard in the console.