Skip to content

Guides Guides

Google Sheets with Apps Script

Add custom functions like =OPC_PRICE("AAPL") and =OPC_SPREAD_POP(...) to any spreadsheet.

  1. Open Apps Script

    In your sheet, choose Extensions → Apps Script, delete the sample code and paste this:

    Code.gs
    /**
     * Options Profit Calculator API for Google Sheets.
     * Extensions > Apps Script, paste this, then set the OPC_API_KEY script property.
     */
    const OPC_BASE = 'https://www.optionsprofitcalculator.com/api/v1';
    
    function opcCall_(method, path, body) {
      const key = PropertiesService.getScriptProperties().getProperty('OPC_API_KEY');
      // Keyless endpoints such as /quote still work before the key is saved
      const opts = { method: method, headers: key ? { Authorization: 'Bearer ' + key } : {}, muteHttpExceptions: true };
      if (body) { opts.contentType = 'application/json'; opts.payload = JSON.stringify(body); }
      const json = JSON.parse(UrlFetchApp.fetch(OPC_BASE + path, opts).getContentText());
      if (!json.success) throw new Error(json.error.message);
      return json.data;
    }
    
    /**
     * Delayed stock price. =OPC_PRICE("AAPL")
     * @customfunction
     */
    function OPC_PRICE(symbol) {
      return opcCall_('get', '/quote?symbol=' + encodeURIComponent(symbol)).price;
    }
    
    /**
     * Probability of profit of a vertical spread (0 to 1).
     * =OPC_SPREAD_POP("AAPL", "call", 345, 360, "2026-12-18")
     * @customfunction
     */
    function OPC_SPREAD_POP(symbol, type, buyStrike, sellStrike, expiry) {
      // A date cell arrives as midnight in the spreadsheet's time zone, so format it in that zone
      const tz = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
      const exp = expiry instanceof Date ? Utilities.formatDate(expiry, tz, 'yyyy-MM-dd') : expiry;
      const data = opcCall_('post', '/pop', {
        symbol: symbol,
        legs: [
          { type: type, action: 'buy', strike: buyStrike, expiry: exp },
          { type: type, action: 'sell', strike: sellStrike, expiry: exp },
        ],
      });
      return data.probabilityOfProfit;
    }
  2. Store your key

    In Apps Script, open Project Settings (the gear), scroll to Script properties and add OPC_API_KEY with your key. Storing it there keeps it out of the code and the sheet.

  3. Use the functions

    Save, go back to the sheet and type =OPC_PRICE("AAPL") in a cell. The first time, Google asks you to allow the script to connect to an external service.

Mind your quota

Each cell that recalculates makes a request. Sheets recalculates custom functions when their inputs change and when the sheet is opened, so a column of 100 formulas can use 100 requests at a time. Keep formula counts modest on the Free plan, or upgrade.

Tip

To refresh on demand instead, write a function that fills a range and run it from a menu or a time-driven trigger.