# Alpaca API Client in Rust This is an unofficial SDK for the Alpaca API written in Rust. Alpaca is a trading platform for developers and app makers, and they provide various endpoints to access over http. The goal of this package is to provide the basic functionality for using the Alpaca API. This is a work in progress, and will need contributors to take this all the way. **Still a Work In Progress** Recommended for Paper Accounts only. ![Build Status](https://img.shields.io/badge/build-passing-green.svg) ![Version 0.6.0](https://img.shields.io/badge/version-0.6.0-blue.svg) ## Installation ```bash cargo add alpaca_api_client ``` We use dotenvy to pull in the API keys. Add your API keys to an .env file in the root of your directory with these names. ```bash /.env APCA_API_KEY_ID= APCA_API_SECRET_KEY= ``` Or find some other way to feed them into the environment. ## Features Currently, this package only provides the ability to interact with the Market Data and Trading APIs. The Broker API is not yet supported. ### Market Data Link to the documentation -> [Alpaca API Docs](https://docs.alpaca.markets/docs/about-market-data-api) - Stocks - Crypto - News - Options - Screener ### Trading Link to the documentation -> [Alpaca API Docs](https://docs.alpaca.markets/docs/trading-api) - Account - Activities - Assets - Calendar - Clock - Order - Positions - Portfolio ## Usage [RS Docs](https://docs.rs/alpaca_api_client/0.6.0/alpaca_api_client/) | [Examples](https://github.com/jonkarrer/alpaca_api_client/tree/main/examples) The Alpaca api is mostly designed to be manipulated through query parameters. There are some cases where they want a body in the request with our desired queries. In either case, this library operates by allowing users to manage their queries with a builder pattern. Essentially, the query params map to setters on the query builder. Here are a few examples. ### Historical Bars ```rust use alpaca_api_client::{market_data::stocks::HistoricalBarsQuery, TimeFrame}; let query = HistoricalBarsQuery::new(vec!["AAPL", "TSLA"], TimeFrame::OneDay) .start("2022-02-01") // date to start .end("2022-02-10") // date to end .feed("iex") // feed to use (iex is free, sip is premium). See Alpaca docs for more info .send() // this finalizes the query and send it off .unwrap(); dbg!(&query); ```
See output
```rust { "TSLA": [ StockBar { t: "2022-02-01T05:00:00Z", o: 934.4, h: 943.35, l: 905.02, c: 930.48, v: 651095.0, n: 17534, vw: 926.5979, }, StockBar { t: "2022-02-02T05:00:00Z", o: 926.58, h: 931.35, l: 889.48, c: 905.64, v: 542975.0, n: 14412, vw: 908.74176, }, ], "AAPL": [ StockBar { t: "2022-02-01T05:00:00Z", o: 174.0, h: 174.78, l: 172.36, c: 174.54, v: 1094581.0, n: 10621, vw: 173.47993, }, StockBar { t: "2022-02-02T05:00:00Z", o: 174.82, h: 175.88, l: 173.33, c: 175.58, v: 1304266.0, n: 11695, vw: 174.82686, }, ], } ```
### News ```rust use alpaca_api_client::market_data::news::NewsQuery; let query = NewsQuery::new(vec!["AAPL"]) .include_content(true) // include content in the response .exclude_contentless(true) // exclude content less articles .limit(2) // limit the number of articles to 2 .sort_desc() // sort the articles in descending order .send() // this finalizes the query and send it off .unwrap(); dbg!(&query); ```
See output
```rust [ NewsArticle { author: "The Arora Report", content: "
\"\"/
\n\n\n\n

To gain an edge, this is what you need to know today.

\n\n\n\n

Nuclear Power Revival

\n\n\n\n

Please click here for an enlarged chart of Constellation Energy Corp (NASDAQ:CEG).

\n\n\n\n

Note the following:

\n\n\n\n
    \n
  • This article is about the big picture, not an individual stock.  The chart of CEG is being used to illustrate the point.
  • \n\n\n\n
  • To feed the power hungry AI data centers, Microsoft Corp (NASDAQ:MSFT) is signing a power purchase agreement with CEG.
  • \n\n\n\n
  • The chart shows the gap up on CEG news.
  • \n\n\n\n
  • The chart shows that CEG is in the resistance zone.
  • \n\n\n\n
  • RSI on the chart shows that CEG is very overbought.  An overbought stock tends to pullback.
  • \n\n\n\n
  • Based on the quantitative screen of The Arora Report's ZYX Change Method, CEG is way overvalued at this time.  However, CEG will benefit from AI, and as such, it is on our radar to give a signal when it is appropriate.
  • \n\n\n\n
  • To provide the power, CEG will restart Three Mile Island Unit 1.  This reactor was shut down about five years ago due to economic reasons.  Three Mile Island Unit 2 is famous for a partial melt down, which caused the most serious nuclear accident on U.S. soil.  In addition to CEG, there are opportunities in other energy producers that will help meet the massive power demand for AI.\n
      \n
    • Quanta Services Inc (NYSE:PWR) is a contractor to electric utilities and is benefiting from the AI power demand.  As full disclosure, PWR is in The Arora Report’s ZYX Buy Core Model Portfolio. PWR is long from $37. 
    • \n\n\n\n
    • First Solar Inc (NASDAQ:FSLR), which provides solar power to data centers. As full disclosure, FSLR is in The Arora Report’s ZYX Buy Core Model Portfolio.
    • \n\n\n\n
    • A new name that is on The Arora Report’s radar is Vistra Corp (NYSE:VST). As full disclosure, a signal may be given when appropriate.
    • \n
    \n
  • \n\n\n\n
  • We shared with readers yesterday that quad witching was to the upside.\n
      \n
    • A part of the strength in the stock market yesterday was due to quad witching and not due to the Fed's 50 bps interest rate cut.
    • \n\n\n\n
    • About $5 trillion notional value of stock derivatives are expiring today.  This is a huge amount but not a record.
    • \n\n\n\n
    • This morning, expiring futures are exerting downward pressure on the market after yesterday's runup.  Futures are expiring this morning.
    • \n\n\n\n
    • Options will expire in the afternoon.
    • \n
    \n
  • \n\n\n\n
  • Historically, gains due to quad witching tend to reverse in the following week and sometimes even on the expiration day.
  • \n
\n\n\n\n

Japan

\n\n\n\n

In a relief to U.S. stock investors, the Bank of Japan (BOJ) left interest rates unchanged.

\n\n\n\n

Magnificent Seven Money Flows

\n\n\n\n

In the early trade, money flows are positive in Alphabet Inc Class C (NASDAQ:GOOG).

\n\n\n\n

In the early trade, money flows are neutral in Apple Inc (NASDAQ:AAPL), Amazon.com, Inc. (NASDAQ:AMZN), Meta Platforms Inc (NASDAQ:META), and MSFT.

\n\n\n\n

In the early trade, money flows are negative in NVIDIA Corp (NASDAQ:NVDA), and Tesla Inc (NASDAQ:TSLA).

\n\n\n\n

In the early trade, money flows are negative in SPDR S&P 500 ETF Trust (NYSE:SPY) and Invesco QQQ Trust Series 1 (NASDAQ:QQQ).

\n\n\n\n

Momo Crowd And Smart Money In Stocks

\n\n\n\n

Investors can gain an edge by knowing money flows in SPY and QQQ.\u{a0} Investors can get a bigger edge by knowing when smart money is buying stocks, gold, and oil.\u{a0} The most popular ETF for gold is SPDR Gold Trust (NYSE:GLD).\u{a0} The most popular ETF for silver is iShares Silver Trust (NYSE:SLV).\u{a0} The most popular ETF for oil is United States Oil ETF (NYSE:USO).

\n\n\n\n

Bitcoin

\n\n\n\n

Trump's advocacy continues to bring buying into Bitcoin (CRYPTO: BTC). Here is the key question: Will bitcoin whales take advantage of the strength to sell as is their pattern?

\n\n\n\n

Protection Band And What To Do Now

\n\n\n\n

It is important for investors to look ahead and not in the rearview mirror.

\n\n\n\n

Consider continuing to hold good, very long term, existing positions. Based on individual risk preference, consider a protection band consisting of cash or Treasury bills or short-term tactical trades as well as short to medium term hedges and short term hedges. This is a good way to protect yourself and participate in the upside at the same time.

\n\n\n\n

You can determine your protection bands by adding cash to hedges.  The high band of the protection is appropriate for those who are older or conservative. The low band of the protection is appropriate for those who are younger or aggressive.  If you do not hedge, the total cash level should be more than stated above but significantly less than cash plus hedges.

\n\n\n\n

A protection band of 0% would be very bullish and would indicate full investment with 0% in cash.  A protection band of 100% would be very bearish and would indicate a need for aggressive protection with cash and hedges or aggressive short selling.

\n\n\n\n

It is worth reminding that you cannot take advantage of new upcoming opportunities if you are not holding enough cash.  When adjusting hedge levels, consider adjusting partial stop quantities for stock positions (non ETF); consider using wider stops on remaining quantities and also allowing more room for high beta stocks.  High beta stocks are the ones that move more than the market.

\n\n\n\n

Traditional 60/40 Portfolio

\n\n\n\n

Probability based risk reward adjusted for inflation does not favor long duration strategic bond allocation at this time.

\n\n\n\n

Those who want to stick to traditional 60% allocation to stocks and 40% to bonds may consider focusing on only high quality bonds and bonds of five year duration or less.  Those willing to bring sophistication to their investing may consider using bond ETFs as tactical positions and not strategic positions at this time.

\n\n\n\n

The Arora Report is known for its accurate calls. The Arora Report correctly called the big artificial intelligence rally before anyone else, the new bull market of 2023, the bear market of 2022, new stock market highs right after the virus low in 2020, the virus drop in 2020, the DJIA rally to 30,000 when it was trading at 16,000, the start of a mega bull market in 2009, and the financial crash of 2008. Please click here to sign up for a free forever Generate Wealth Newsletter.

", created_at: "2024-09-20T14:28:58Z", headline: "$5 Trillion Worth Of Quad Witching, AI Leading To Revivial Of Nuclear Power", id: 40959279, images: [ NewsImage { url: "https://cdn.benzinga.com/files/imagecache/2048x1536xUP/images/story/2024/09/20/analyst-ratings-image-8736.jpeg", size: "large", }, NewsImage { url: "https://cdn.benzinga.com/files/imagecache/1024x768xUP/images/story/2024/09/20/analyst-ratings-image-8736.jpeg", size: "small", }, NewsImage { url: "https://cdn.benzinga.com/files/imagecache/250x187xUP/images/story/2024/09/20/analyst-ratings-image-8736.jpeg", size: "thumb", }, ], source: "benzinga", summary: "\n\n\n\nTo gain an edge, this is what you need to know today.", symbols: [ "AAPL", "AMZN", "BTCUSD", "CEG", "FSLR", "GLD", "GOOG", "META", "MSFT", "NVDA", "PWR", "QQQ", "SLV", "SPY", "TSLA", "USO", "VST", ], updated_at: "2024-09-20T14:29:00Z", url: "https://www.benzinga.com/24/09/40959279/5-trillion-worth-of-quad-witching-ai-leading-to-revivial-of-nuclear-power", }, NewsArticle { author: "Chris Katje", content: "

Apple Inc (NASDAQ:AAPL) is one of the stocks that could be volatile Friday with S&P 500 and several market indexes rebalancing along with the quarterly triple witching event that sees the expiration of stock options, index futures and index options.

\n\n\n\n

What Happened: The S&P 500, tracked\u{a0}by the\u{a0}SPDR S&P 500 ETF Trust\u{a0}(NYSE:SPY), will complete a quarterly rebalance on Friday. This task is traditionally done on the third Friday of March, June, September, and December.

\n\n\n\n

Apple could be one of the biggest beneficiaries of the rebalancing by the S&P 500 and other market indexes.

\n\n\n\n

The technology giant is currently the second-largest holding in the SPY, with 6.7% of assets and trailing Microsoft Corporation (NASDAQ:MSFT) at 6.8%.

\n\n\n\n

The rebalance will see Apple take the lead in the holdings, as the company's market capitalization of $3.48 trillion is ahead of Microsoft at $3.26 trillion.

\n\n\n\n

Friday's new rebalancing will coincide with upcoming S&P index-capping rules that will adjust how allocations for the largest companies are determined, according to Bloomberg.

\n\n\n\n

The reshuffling of $250 billion in shares in index-tracking funds is expected to benefit the technology sector and companies like Apple the most, the report said.

\n\n\n\n

Piper Sandler estimates that the technology sector will see $40 billion in net buying, as the only sector with a net gain, according to the Bloomberg report.

\n\n\n\n

Apple will account for a large portion of the $40 billion in net buying thanks to its market capitalization, new rules, and recent sales by Warren Buffett and Berkshire Hathaway.

\n\n\n\n

The sale by Berkshire Hathaway has changed the float of Apple stock, with more shares available to investors. Rules from indexes, in some cases, use float-adjusted market capitalizations, which take into account large stakes held by fund managers.

\n\n\n\n

Did You Know?

\n\n\n\n\n\n\n\n

Why It's Important: Apple and Microsoft have battled back and forth over the last several years as the world's most valuable company. Both companies were briefly passed by Nvidia earlier this year.

\n\n\n\n

Friday's rebalancing is expected to bring market volatility and reshape many index funds moving forward.

\n\n\n\n

For Apple, the event comes as the iPhone 16 is publicly released. Investors and analysts are expressing concerns as consumers grapple with whether the new features and the rollout of Apple Intelligence are worth\u{a0}the upgrade from their existing device.

\n\n\n\n

AAPL Price Action: Apple stock trades at $229.02 versus a 52-week trading range of $164.08 to $237.23. Apple stock is up 23% year-to-date in 2024.

\n\n\n\n

Read Next:

\n\n\n\n\n\n\n\n

Photo: Shutterstock

", created_at: "2024-09-20T13:48:39Z", headline: "How Apple Stock Could Gain From Friday's S&P 500 Rebalancing: What Investors Should Know", id: 40958207, images: [ NewsImage { url: "https://cdn.benzinga.com/files/imagecache/2048x1536xUP/images/story/2024/09/20/Major-Stake-In-Apple.jpeg", size: "large", }, NewsImage { url: "https://cdn.benzinga.com/files/imagecache/1024x768xUP/images/story/2024/09/20/Major-Stake-In-Apple.jpeg", size: "small", }, NewsImage { url: "https://cdn.benzinga.com/files/imagecache/250x187xUP/images/story/2024/09/20/Major-Stake-In-Apple.jpeg", size: "thumb", }, ], source: "benzinga", summary: "Apple stock could come away a winner after Friday's quarterly rebalancing for index funds.", symbols: [ "AAPL", "MSFT", "SPY", ], updated_at: "2024-09-20T13:48:40Z", url: "https://www.benzinga.com/news/24/09/40958207/how-apple-stock-could-gain-from-fridays-s-p-500-rebalancing-what-investors-should-know", }, ] ```
### Market Order ```rust CreateOrderQuery::new("AAPL", OrderSide::Buy, OrderType::Market, TimeInForce::Day) .qty("1") .send(AccountType::Paper) .unwrap(); ``` ### Trailing Stop Order ```rust CreateOrderQuery::new( "AAPL", OrderSide::Buy, OrderType::TrailingStop, TimeInForce::GoodTilCanceled, ) .qty("1") .trail_percent("10") .send(AccountType::Paper) .unwrap(); ``` ### One Cancels the Other Order ```rust CreateOrderQuery::new( "AAPL", OrderSide::Buy, OrderType::Limit, TimeInForce::GoodTilCanceled, ) .qty("1") .order_class(OrderClass::OneCancelsOther) .take_profit(TakeProfit::new("199")) .stop_loss(StopLoss::new("200", "201")) .send(AccountType::Paper) .unwrap(); ``` ### Bracket Order ```rust CreateOrderQuery::new( "AAPL", OrderSide::Buy, OrderType::Market, TimeInForce::GoodTilCanceled, ) .qty("1") .order_class(OrderClass::Bracket) .take_profit(TakeProfit::new("300")) .stop_loss(StopLoss::new("200", "199")) .send(AccountType::Paper) .unwrap(); ``` ## Contribution If you would like to contribute to the project, PR's are welcome. The Broker API is primarily where the help would be needed. ## License This project is licensed under the MIT and APACHE License.