question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

alpaca.getBarsV2 is not a function

See original GitHub issue

following the Documentation:

getBarsV2(
  symbol,
  
  {
    limit: number,
    start: date isoformat string yyyy-mm-ddThh:MM:ss-04:00,
    end: date isoformat string yyyy-mm-ddThh:MM:ss-04:00,
    timeframe: "1Min" | "1Hour" | "1Day"
  }
) => Promise<BarsObject>

Here is my code:

const alpaca = new Alpaca({
    keyId: process.env.ALPACA_API_KEY_ID,
    secretKey: process.env.ALPACA_API_SECRET_KEY,
    paper: true,
    usePolygon: false
  })

alpaca.getBarsV2('GME', {
    limit: 100,
    start: new Date(Date.now() - 30 * 60 * 60 * 24 * 1000).toISOString(), // 30 days ago
    end: new Date().toISOString(),
    timeframe: '1Day',
})

Expected to get Bars. Got alpaca.getBarsV2 is not a function

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:17 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
hudsonblcommented, May 26, 2021

For the time being if you’re using node.js. Here is my current solution. I decided to do the call manually.

const getHistoricalTradeData = async (symbol) => {
    
    // This gets the date time from wherever the server is located
    const { startDate, endDate } = getDateForHistoricalData(30);
    console.log("Start: ", startDate)
    console.log("End: ", endDate);
    const url = `https://data.alpaca.markets/v2/stocks/${symbol}/trades`
    const options = {
        headers: {
           'APCA-API-KEY-ID': process.env.API_KEY,
           'APCA-API-SECRET-KEY': process.env.API_SECRET
        },
        params: {
            start: startDate,
            end: endDate,
            limit: 1000,
        }
    }
    return new Promise(async (resolve, reject) => {
        await axios.get(url, options)
        .then((response) => {
            // Map response to my data format
            const result = response.data.trades.map((asset, idx) => [Date.parse(asset.t), asset.p])
            resolve(result);
        })
        .catch((err) => {
            console.log("err: ", err);
            reject([]);
        });
    })
}

an example value for startDate would be ‘2021-05-23’

0reactions
michaeljwrightcommented, May 10, 2022

It still doesn’t appear to work properly (or as documented). Certainly doesn’t work close to the V1. I had to solve it via a direct API call to your V2 endpoint and then parse the response data accordingly.

Call to API endpoint (V2):

const stocks = ["AAPL", "TSL"];
let until = new Date()
let start = new Date();
    await fetch(
      "https://data.alpaca.markets/v2/stocks/bars?symbols=" +
        stocks.toString() +
        "&start=" +
        start.toISOString().split('T')[0] +
        "T00:00:00Z&end=" +
        until.toISOString().split("T")[0] +
        "T11:59:00Z&timeframe=1Min",
      {
        method: "GET",
        headers: {
          "Apca-Api-Key-Id": process.env.API_KEY,
          "Apca-Api-Secret-Key": process.env.SECRET_API_KEY,
        },
      }
    )
      .then((response) => {
        if (response.status >= 400) {
          console.log("ERROR: AlpacaMarketDataV2");
        }
        return response.json();
      })
      .then(async (response) => {
        if (response) {
          // do something with response and parse the response data to how you need it
        }
      })
      .catch(function (err) {
        console.log("ERROR: AlpacaMarketDataV2");
        console.error(err);
      });

Example of how to parse the response data:

const stocks = ["AAPL", "TSL"];
let stockData = [];
  let openValues = [];
  let closeValues = [];
  let highValues = [];
  let lowValues = [];
  let volumeValues = [];

  _.forOwn(stocks, (stock) => {
    if (!isBacktest) {
      openValues = _.map(response.bars[stock], (bar) => bar.o);
      closeValues = _.map(response.bars[stock], (bar) => bar.c);
      highValues = _.map(response.bars[stock], (bar) => bar.h);
      lowValues = _.map(response.bars[stock], (bar) => bar.l);
      volumeValues = _.map(response.bars[stock], (bar) => bar.v);
    }

    stockData.push({
      symbol: stock,
      subject: stock,
      lastOrder: lastOrder,
      signals: [], // list of signals (buy/sell) based on algos
      closeValues: closeValues,
      openValues: openValues,
      highValues: highValues,
      lowValues: lowValues,
      volumeValues: volumeValues,
      price: 0,
    });
  });

For more fun with trading bots, please visit https://github.com/michaeljwright/robobull-trading-bot

Read more comments on GitHub >

github_iconTop Results From Across the Web

getBar and getAggregate api are missing on alpaca js object
Below are the errors, i am getting… How to fix it? TypeError: alpaca.getBars is not a function at Object. (D:\myproj\stockscreener\testalpaca.js ...
Read more >
@neeschit/alpaca-trade-api - npm
Javascript library for the Alpaca Trade API. Latest version: 2.6.0, last published: a year ago. Start using @neeschit/alpaca-trade-api in ...
Read more >
node-red-contrib-alpaca (node)
Added websocket v2 node (this one works!) Added Get Trade and Get Quote (aka "Get Last Trade/Quote") functions to main Alpaca node; Added...
Read more >
npm:@alpacahq/alpaca-trade-api | Skypack
Javascript library for the Alpaca Trade API. ... As a general rule, required method parameters are passed as plain function arguments, and the...
Read more >
ALPACA Error when try to load a page - Stack Overflow
Uncaught TypeError : $(...).alpaca is not a function(…) I AM GETTING AN ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found