Giter Club home page Giter Club logo

alpaca-py's Introduction

Alpaca-py

Downloads Python Versions GitHub PyPI

Table of Contents

About

Alpaca-py provides an interface for interacting with the API products Alpaca offers. These API products are provided as various REST, WebSocket and SSE endpoints that allow you to do everything from streaming market data to creating your own investment apps.

Learn more about the API products Alpaca offers at https://alpaca.markets.

Documentation

Alpaca-py has a supplementary documentation site which contains references for all clients, methods and models found in this codebase. The documentation also contains examples to get started with alpaca-py.

You can find the documentation site here: https://docs.alpaca.markets/docs/getting-started-1

Installation

Alpaca-py is supported on Python 3.7+. You can install Alpaca-py using pip.

Run the following command in your terminal.

  pip install alpaca-py

Update

If you already have Alpaca-py installed, and would like to use the latest version available...

Run the following command in your terminal:

  pip install alpaca-py --upgrade

What’s New?

If you’ve used the previous python SDK alpaca-trade-api, there are a few key differences to be aware of.

Broker API

Alpaca-py lets you use Broker API to start building your investment apps! Learn more at the Broker page.

OOP Design

Alpaca-py uses a more OOP approach to submitting requests compared to the previous SDK. To submit a request, you will most likely need to create a request object containing the desired request data. Generally, there is a unique request model for each method.

Some examples of request models corresponding to methods:

  • GetOrdersRequest for TradingClient.get_orders()
  • CryptoLatestOrderbookRequest for CryptoHistoricalDataClient.get_crypto_latest_orderbook()

Request Models Usage Example

To get historical bar data for crypto, you will need to provide a CryptoBarsRequest object.

from alpaca.data.historical import CryptoHistoricalDataClient
from alpaca.data.requests import CryptoBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime

# no keys required for crypto data
client = CryptoHistoricalDataClient()

request_params = CryptoBarsRequest(
                        symbol_or_symbols=["BTC/USD", "ETH/USD"],
                        timeframe=TimeFrame.Day,
                        start=datetime(2022, 7, 1)
                 )

bars = client.get_crypto_bars(request_params)

Data Validation

Alpaca-py uses pydantic to validate data models at run-time. This means if you are receiving request data via JSON from a client. You can handle parsing and validation through Alpaca’s request models. All request models can be instantiated by passing in data in dictionary format.

Here is a rough example of what is possible.

 @app.route('/post_json', methods=['POST'])
 def do_trade():
     # ...

     order_data_json = request.get_json()

     # validate data
     MarketOrderRequest(**order_data_json)

     # ...

Many Clients

Alpaca-py has a lot of client classes. There is a client for each API and even asset class specific clients (StockHistoricalDataClient, CryptoDataStream, OptionHistoricalDataClient). This requires you to pick and choose clients based on your needs.

Broker API: BrokerClient

Trading API: TradingClient

Market Data API: StockHistoricalDataClient, CryptoHistoricalDataClient, OptionHistoricalDataClient, CryptoDataStream, StockDataStream, OptionDataStream

API Keys

Trading and Market Data API

In order to use Alpaca’s services you’ll need to sign up for an Alpaca account and retrieve your API keys. Signing up is completely free and takes only a few minutes. Sandbox environments are available to test out the API. To use the sandbox environment, you will need to provide sandbox/paper keys. API keys are passed into Alpaca-py through either TradingClient, StockHistoricalDataClient, CryptoHistoricalDataClient, OptionHistoricalDataClient. StockDataStream, CryptoDataStream, or OptionDataStream.

Broker API

To use the Broker API, you will need to sign up for a broker account and retrieve your Broker API keys. The API keys can be found on the dashboard once you’ve logged in. Alpaca also provides a sandbox environment to test out Broker API. To use the sandbox mode, provide your sandbox keys. Once you have your keys, you can pass them into BrokerClient to get started.

Usage

Alpaca’s APIs allow you to do everything from building algorithmic trading strategies to building a full brokerage experience for your own end users. Here are some things you can do with Alpaca-py.

To view full descriptions and examples view the documentation page.

Market Data API: Access live and historical market data for 5000+ stocks, 20+ crypto, and options(beta).

Trading API: Trade stock and crypto with lightning fast execution speeds.

Broker API & Connect: Build investment apps - from robo-advisors to brokerages.

Broker API Example

Listing All Accounts

The BrokerClient.list_accounts method allows you to list all the brokerage accounts under your management. The method takes an optional parameter search_parameters which requires a ListAccountsRequest object. This parameter allows you to filter the list of accounts returned.

from alpaca.broker.client import BrokerClient
from alpaca.broker.requests import ListAccountsRequest
from alpaca.broker.enums import AccountEntities

broker_client = BrokerClient('api-key', 'secret-key')

# search for accounts created after January 30th 2022.
# Response should contain Contact and Identity fields for each account.
filter = ListAccountsRequest(
                    created_after=datetime.datetime.strptime("2022-01-30", "%Y-%m-%d"),
                    entities=[AccountEntities.CONTACT, AccountEntities.IDENTITY]
                    )

accounts = broker_client.list_accounts(search_parameters=filter)

Trading API Example

Submitting an Order

To create an order on Alpaca-py you must use an OrderRequest object. There are different OrderRequest objects based on the type of order you want to make. For market orders, there is MarketOrderRequest, limit orders have LimitOrderRequest, stop orders StopOrderRequest, and trailing stop orders have TrailingStopOrderRequest. Each order type have their own required parameters for a successful order.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

trading_client = TradingClient('api-key', 'secret-key')


# preparing order data
market_order_data = MarketOrderRequest(
                      symbol="BTC/USD",
                      qty=0.0001,
                      side=OrderSide.BUY,
                      time_in_force=TimeInForce.DAY
                  )

# Market order
market_order = trading_client.submit_order(
                order_data=market_order_data
                )

Market Data API Example

Querying Historical Bar Data

You can request bar data via the HistoricalDataClients. In this example, we query daily bar data for “BTC/USD” and “ETH/USD” since July 1st 2022. You can convert the response to a multi-index pandas dataframe using the .df property.

from alpaca.data.historical import CryptoHistoricalDataClient
from alpaca.data.requests import CryptoBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime

# no keys required for crypto data
client = CryptoHistoricalDataClient()

request_params = CryptoBarsRequest(
                        symbol_or_symbols=["BTC/USD", "ETH/USD"],
                        timeframe=TimeFrame.Day,
                        start=datetime.strptime("2022-07-01", '%Y-%m-%d')
                        )

bars = client.get_crypto_bars(request_params)

# convert to dataframe
bars.df

Options Trading (Beta)

We're excited to support options trading! Use this section to read up on Alpaca's Beta trading capabilities. For more details, please refer to our documentation page for options trading

Options trading is in BETA. Only BETA users are able to access options endpoints. We will continue to update our documentation as we collect your valuable feedback.

There is an example jupyter notebook to explain methods of alpaca-py for options trading.

Jupyter Notebook Library

We have put together some examples in jupyter notebooks so that you can start developing today with alpaca-py right away!

alpaca-py's People

Contributors

alessiocastrica avatar alexandroskyriakakis avatar andrewwoood avatar bradgaddis avatar brunerm99 avatar cemlyn007 avatar dependabot[bot] avatar dev-il avatar drew887 avatar fernando-az-alpaca avatar gageorsburn avatar ggrace01 avatar gnvk avatar gsmadi avatar haxdds avatar hiohiohio avatar jjmaxwell4 avatar joepatmckenna avatar jonathanrayner avatar mahveotm avatar matebudai avatar olegra avatar omahs avatar ryansdowning avatar sai-g avatar sfhemstreet avatar sshcli avatar toddpi314 avatar victorouse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alpaca-py's Issues

Broker API: Trading - Watchlists

Implement the watchlists routes as seen here in the docs

Should add the following to BrokerClient:

def get_watchlists_for_account(
        self,
        account_id: Union[UUID, str],
) -> List[Watchlist]:
    pass

def get_watchlist_for_account_by_id(
        self,
        account_id: Union[UUID, str],
        watchlist_id: Union[UUID, str],
) -> Watchlist:
    pass
        
def create_watchlist_for_account(
        self,
        account_id: Union[UUID, str],
        watchlist_data: CreateWatchlistRequest
) -> Watchlist:
    pass

def update_watchlist_for_account_by_id(
        self,
        # Might be worth taking a union of this an Watchlist itself; but then we should make a change like that SDK wide. Probably a good 0.2.x change
        watchlist_data: CreateWatchlistRequest 
) -> Watchlist:
    pass
        
def add_asset_to_watchlist_for_account_by_id(
        self,
        account_id: Union[UUID, str],
        watchlist_id: Union[UUID, str],
        symbol_or_asset_id: Union[UUID, str]
) -> Watchlist:
    pass

def delete_watchlist_from_account_by_id(
        self,
        account_id: Union[UUID, str],
        watchlist_id: Union[UUID, str],
) -> None:
    pass

def remove_asset_from_watchlist_for_account_by_id(
        self,
        account_id: Union[UUID, str],
        watchlist_id: Union[UUID, str],
        symbol_or_asset_id: Union[UUID, str]
) -> Watchlist:
    pass

Broker API: Trading - Positions

Implement the Positions related routes as seen here in the docs

Should add the following to BrokerClient:

Note the symbol_or_asset_id will need different UUID validation than what we currently use since it might be a symbol name. I think we'd be good enough to just check if UUID already and if not use it verbatim

def get_all_positions_for_account(
        self,
        account_id: Union[UUID, str],
) -> List[Position]:
    pass
        
def get_open_position_for_account(
        self,
        account_id: Union[UUID, str],
        symbol_or_asset_id: Union[UUID, str]
) -> Position:
    pass

def close_all_positions_for_account(
        self,
        account_id: Union[UUID, str],
        cancel_orders: bool
) -> List[ClosePositionReponse]: 
    pass
    
def close_position_for_account_by_id(
        self,
        account_id: Union[UUID, str],
        symbol_or_asset_id: Union[UUID, str],
        close_options: Optional[ClosePositionRequest] = None
) -> Order:
    pass

Broker API: Trading - Orders

Implement the Order related routes as seen here in the docs

Should add the following to BrokerClient:

def create_order_for_account(
        self,
        account_id: Union[UUID, str],
        order: CreateOrderRequest
) -> Order:
    pass

def get_orders_for_account(
        self,
        account_id: Union[UUID, str],
        order_filter: GetOrdersRequest
) -> List[Order]:
    pass

def get_order_for_account_by_id(
        self,
        account_id: Union[UUID, str],
        order_id: Union[UUID, str],
        nested: Optional[bool] = None,
) -> Order:
    pass

def get_order_for_account_by_client_order_id(
        self,
        account_id: Union[UUID, str],
        client_order_id: Union[UUID, str],
        nested: Optional[bool] = None,
) -> Order:
    pass

def replace_order_for_account_by_id(
        self,
        account_id: Union[UUID, str],
        order_id: Union[UUID, str],
        replace_data: ReplaceOrderRequest,
) -> Order:
    pass

def close_all_open_orders_for_account(
        self,
        account_id: Union[UUID, str],
) -> List[OrderCancelationResponse]:
    pass
        
def close_order_for_account_by_id(
        self,
        account_id: Union[UUID, str],
        order_id: Union[UUID, str],
) -> None:
    pass
        

All Clients: Rename methods to follow a common signature

Currently during the alpha phase we are testing out different naming schemes to see what sticks. This ticket is to finalize on a naming scheme and rename all the methods to match.

Also need to once finalized update the CONTRIBUTING file with the new naming scheme

Broker API: Clock & Calendar

Implement the Clock and Calendar routes from the docs.

Should add the following to BrokerClient:

def get_clock(self) -> Clock:
    pass

def get_calendar(
        self,
        filters: Optional[GetCalendarRequest] = None
) -> List[Calendar]:
    pass
        

Broker API: Funding - ACH Relationships

This is to implement the routes found here in the docs

Need to add in the following methods to BrokerClient:

  def create_ach_relationship_for_account(
        self,
        account_id: Union[UUID, str],
        ach_data: Union[CreateACHRelationshipRequest, CreatePlaidRelationshipRequest],
  ) -> ACHRelationship:
      pass
    # needs to handle both flows of creating with raw ACH data as well as with a Plaid Token.
  
  def get_ach_relationships_for_account(
            self,
            account_id: Union[UUID, str],
            statuses: Optional[List[ACHRelationshipStatus]] = None,
  ) -> List[ACHRelationship]:
      pass

  def delete_ach_relationship_for_account(
        self,
        account_id: Union[UUID, str],
        ach_relationship_id: Union[UUID, str],
  ) -> None:
      pass

[Question]: Why do you require pandas 1.3.5?

Question form pre-submit checklist.

  • I have searched the existing issues to ensure there isn't already an issue about this question.
  • My question has to do with the Python SDK and isn't a general question about the API. (If it is please open your issue here)
  • My question isn't about how to do a specific algorithm or asking for trade advice (answers to these are outside the scope of this repo).

Question

Is there a reason (a good reason) why this SDK requires pandas version 1.3.5?

I installed it yesterday to slowly ease into the new SDK. During installation, pandas was downgraded from 1.4.X to 1.3.5

This change broke my code. Turns out there are major improvements made to pandas since 1.3.5

[Bug]: TradingStream import missing in alpaca.trading.__init__

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

TradingStream cannot be import due to a missing import in alpaca.trading.init

Expected Behavior

No response

SDK Version I encountered this issue in

alpaca-py version: 0.5.2

Steps To Reproduce

Try importing trading stream:
from alpaca.trading.stream import TradingStream

Filled out the Steps to Reproduce section?

  • I have entered valid steps to reproduce my issue or have attached a minimally reproducible case in code that shows my issue happening; and understand that without this my issue will be flagged as invalid and closed after 30 days.

Anything else?

No response

Automated PyPi Releases

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Currently releases to PyPi must be done manually through poetry build & poetry publish.

Describe the solution you'd like.

Use GitHub actions to publish to PyPi

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

[Feature Request} Cancel all orders for specific symbol

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Yes.
Support Request Ticket Number: 60289

Right now, there is no way to cancel all orders for specific symbol.
You can only cancel all orders api.cancel_all_orders()

Describe the solution you'd like.

We need something like this:
api.cancel_orders('AAPL')

or something like this:
api.cancel_all_orders('AAPL')

or something like this:
api.cancel_all_orders(symbol='AAPL')

Describe an alternate solution.

Keep it simple.

Anything else? (Additional Context)

Keep it simple.

Update Request Model Naming Conventions

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

AccountCreationRequest, AccountUpdateRequest should follow similar naming to other request models.

Describe the solution you'd like.

rename AccountCreationRequest to CreateAccountRequest
rename AccountUpdateRequest to UpdateAccountRequest
rename OrderRequest to GetOrderRequest

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Trading API: Orders

Implement routes found in docs here

def get_orders(self, request: GetOrdersRequest) -> List[Order]:
    pass

def get_order_by_id(self, order_id: UUID, request: GetOrderByIdRequest) -> Order:
    pass


def get_order_by_client_id(self, client_id: UUID, request: GetOrderByClientIdRequest) -> Order:
    pass

def submit_order(self, request: OrderSubmissionRequest) -> Order:
   pass
   
def cancel_order_by_id(self, order_id: UUID) -> None:
  pass

def replace_order_by_id(self, order_id: UUID, request: ReplaceOrderRequest) -> None:
  pass

def cancel_orders(self) -> None:
  pass

Support Raw Data Responses in Trading API

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Trading API currently always wraps API responses in object models. It does not allow the ability to return raw responses.

Describe the solution you'd like.

The ability to return responses as given by API before wrapping in object models.

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Support Raw Data Responses For Historical Market Data API

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Similar to #129 and #128

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Implement Default TimeInForce

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

The API currently defaults the time in force to day if not provided since it is the most common time in force. The OrderRequest model should reflect this by setting the default value for time_in_force to TimeInForce.DAY.

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Common Trading Models Should Be Inside the Trading Module

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

All the trading models are inside of the common module. This makes sense in practice since these trading models are shared by the broker module and trading module. But this leaves the trading module empty. Instead, it may make sense to keep all trading related models within the trading module for better organization.

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Trading API: Account Activities

Implement routes defined in Trading API account activities docs.

def get_account_activities_by_type(self, type: ActivityType, request: GetAccountActivitiesByTypeRequest) -> List[AccountActivity]:
   pass

def get_account_activities(self, request: GetAccountActivitiesRequest) -> List[AccountActivity]:
   pass

[Question]: Need example on how to get stock bars

Question form pre-submit checklist.

  • I have searched the existing issues to ensure there isn't already an issue about this question.
  • My question has to do with the Python SDK and isn't a general question about the API. (If it is please open your issue here)
  • My question isn't about how to do a specific algorithm or asking for trade advice (answers to these are outside the scope of this repo).

Question

I have searched in Google and documentation page:
https://alpaca.markets/docs/python-sdk/market_data.html

I couldn't find an example on how to get the stock bars with alpaca-py 0.5.4
Only example for crypto bars is provided.

With alpaca-trade-api 2.3.0 is as simple as this: api.get_bars("AAPL", '1Min')

Thanks in advance for your response.

Regards,

Ability to convert list types (Assets, Positions, Orders, etc) into DataFrames

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Being able to convert to dataframes greatly improve ability to view and manipulate data.

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Support Raw Data Responses in Broker API

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Broker API does not support returning raw responses. It currently always wraps the responses in object models.

Describe the solution you'd like.

Ability to return response as given by API.

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Enhancement: `_one_request` should return raw response

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

_one_request in common/rest.py returns response.json() when response.text is not empty. However, this can lead to issues when implementing routes that require the raw response. Furthermore, for empty responses (response.text = ""), a NoneType is returned which does not contain status code information.

The methods affected are

download_trade_document_for_account_by_id in broker/client

cancel_order_by_id in trading/client

cancel_journal in broker/client

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Broker API: Trading - Trading Account Configuration

Implement the routes from the docs here

Also missing from the docs is a GET route for /v1/trading/accounts/{account_id}/account/configurations that we should implement here

Should add the following interface to BrokerClient:

  def get_trade_configuration_for_account(
          self,
          account_id: Union[UUID, str]
  ): -> TradeAccountConfiguration:
      pass

  def update_trade_configuration_for_account(
          self,
          account_id: Union[UUID, str],
          config: UpdateTradeConfigurationRequest
  )-> TradeAccountConfiguration:
      pass

TImeFrame should be within Market Data module

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

TimeFrame only exists within the context of market data but it is currently in the common module. Instead, it should belong in market data.

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

[Question]: Example to cancel one single order

Question form pre-submit checklist.

  • I have searched the existing issues to ensure there isn't already an issue about this question.
  • My question has to do with the Python SDK and isn't a general question about the API. (If it is please open your issue here)
  • My question isn't about how to do a specific algorithm or asking for trade advice (answers to these are outside the scope of this repo).

Question

I have searched in Google and documentation page:
https://alpaca.markets/docs/python-sdk/trading.html

I couldn't find an example on how to cancel a single order with alpaca-py 0.5.4
You only provide an example to cancel all orders

With alpaca-trade-api 2.3.0 is as simple as this: api.cancel_order('3e4aab784-5965-491b-aedd-ba31b4dd0d59')

Thanks in advance for your response.

Regards,

[Question]: Lack of latest trade example in docs

Question form pre-submit checklist.

  • I have searched the existing issues to ensure there isn't already an issue about this question.
  • My question has to do with the Python SDK and isn't a general question about the API. (If it is please open your issue here)
  • My question isn't about how to do a specific algorithm or asking for trade advice (answers to these are outside the scope of this repo).

Question

I have searched in Google and documentation page:
https://alpaca.markets/docs/python-sdk/market_data.html

I couldn't find an example on how to get the latest trade with alpaca-py 0.5.3

With alpaca-trade-api 2.3.0 is as simple as this: api.get_latest_trade("AAPL")

Thanks in advance for your response.

Regards,

Trading API: Positions

Implement routes found in the Trading API positions docs.

def get_positions(self) -> List[Position]:
   pass

def get_position_by_symbol(self, symbol: str) -> Position:
   pass

def close_all_positions(self, request: CloseAllPositionsRequest) -> None:
   pass

def close_position_by_symbol(self, symbol: str, request: ClosePositionRequest) -> None:
   pass


Broker API: Funding - Banks

This is to implement the routes found here in the docs
Need to add to BrokerClient:

  def create_bank_for_account(
        self,
        account_id: Union[UUID, str],
        bank_data: CreateBankRequest,
  ) -> Bank:
      pass
  
  def get_banks_for_account(
            self,
            account_id: Union[UUID, str],
  ) -> List[Bank]:
      pass

  def delete_bank_for_account(
        self,
        account_id: Union[UUID, str],
        bank_id: Union[UUID, str],
  ) -> None:
      pass

Broker API: Funding - Transfers

This is to implement the routes found here

Need to add to BrokerClient:

  def create_transfer_for_account(
          self,
          account_id: Union[UUID, str],
          transfer_data: CreateTransferRequest,
  ) -> Transfer:
      pass
  
  def get_transfers_for_account(
          self,
          account_id: Union[UUID, str],
  ) -> List[Transfer]:
      pass

  def cancel_transfer_for_account(
          self,
          account_id: Union[UUID, str],
          transfer_id: Union[UUID, str],
  ) -> None:
      pass

Trading API: Corporate Announcements

Implement routes defined in Trading API Corporate Announcement docs.

def get_corporate_annoucements(self, request: GetCorporateAnnouncementsRequest) -> List[CorporateAnnouncement]:
    pass

def get_corporate_announcment_by_id(self, corporate_announcment_id: UUID) -> Announcement:
    pass

[Bug]: alpaca.trading.client compares list to List incorrectly

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

In alpaca.trading.client there are multiple locations where a an object of type "list" is compared to "List".
For example in get_orders:
if "symbols" in params and type(params["symbols"]) is List:
will produce False even if symbols is a list.
Instead try using one of:

  • isinstance(params["symbols"], list)
  • type(params["symbols"]) is list
  • type(params["symbols"]) == list

Expected Behavior

No response

SDK Version I encountered this issue in

0.5.2

Steps To Reproduce

Use function get_orders in alpaca.trading.client and pass a request with a list of symbols

Filled out the Steps to Reproduce section?

  • I have entered valid steps to reproduce my issue or have attached a minimally reproducible case in code that shows my issue happening; and understand that without this my issue will be flagged as invalid and closed after 30 days.

Anything else?

No response

[Bug]: CryptoDataStream.subscribe_bars missing exchange for non raw_data output

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

When I use the default non raw_data in CryptoDataStream.subscribe_bars, it is missing the field exchange. If I change it to raw_data, I can see the exchange. I believe it is missing from the data/mappings.py and the data/models/bars.py.

Expected Behavior

When I use the subscribe_bars, I expect one of the returned values for the record should indicate what exchange it is from.

SDK Version I encountered this issue in

alpaca-py v0.5.0

Steps To Reproduce

Running on macOS Monterey 12.4, Python 3.9.10.

Filled out the Steps to Reproduce section?

  • I have entered valid steps to reproduce my issue or have attached a minimally reproducible case in code that shows my issue happening; and understand that without this my issue will be flagged as invalid and closed after 30 days.

Anything else?

No response

Handle Error From Calling `close_position`

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Currently, the API will throw an error if we try to close a position that is does not exist. The SDK does not handle this error, meaning if the user calls close_position on a non-existing position, their code will throw an APIError.

Describe the solution you'd like.

Instead, the SDK should handle this error and return a FailedClosePositionDetails object,

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

[Bug]: AssetExchange Should Support Crypto Exchanges

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

Crypto exchanges not supported in AssetExchange

Expected Behavior

No response

SDK Version I encountered this issue in

0.2.0

Steps To Reproduce

data = GetAssetsRequest(asset_class=AssetClass.CRYPTO)

print(broker_client.get_all_assets(data))

throws

value is not a valid enumeration member; permitted: 'AMEX', 'ARCA', 'BATS', 'NYSE', 'NASDAQ', 'NYSEARCA'


### Filled out the Steps to Reproduce section?

- [X] I have entered valid steps to reproduce my issue or have attached a minimally reproducible case in code that shows my issue happening; and understand that without this my issue will be flagged as invalid and closed after 30 days.

### Anything else?

_No response_

Add Code Coverage

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Add code coverage tests to CI. We can add a minimum code coverage to ensure higher levels of code quality.

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Broker API: Journals

This is to implement the routes found in the docs here

Need to add:

  def create_journal(
          self,
          journal_data: CreateJournalRequest,
  ) -> Journal:
      pass

  # The response format for the api for this one is a list of Journals with extra error message fields. BatchJournalResponse should just
  # handle this by encapsulating an Optional Journal in it. But I'd also be okay with a polymorphic approach of success and error results.
  def create_batch_journal(
          self,
          batch_data: CreateBatchJournalRequest,
  ) -> List[BatchJournalResponse]:
      pass

  def create_reverse_batch_journal(
          self,
          reverse_batch_data: CreateReverseBatchJournalRequest,
  ) -> List[BatchJournalResponse]:
      pass
  
  def get_journals(
          self,
          journal_filter: Optional[GetJournalsRequest] = None
  ) -> List[Journal]:
      pass

  def get_journal_by_id(
          self,
          journal_id: Union[UUID, str] = None
  ) -> Journal:
      pass

  def cancel_journal_by_id(
          self,
          journal_id: Union[UUID, str],
  ) -> None:
      pass

Trading API: Close Position should have its own Response model.

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

ClosePositionResponse is needed because the response can vary on whether there is an open position or not. Furthermore, for non-existing positions, there can be varying responses depending on whether there is an open order for that symbol.

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

Trading API: Watchlists

Implement routes defined in the Trading API watchlists docs.

def get_watchlists(self) -> List[Watchlist]:
   pass

def create_watchlist(self, request: CreateWatchlistRequest) -> Watchlist:
   pass

def get_watchlist_by_id(self, watchlist_id: UUID) -> Watchlist:
   pass

def update_watchlist_by_id(self, watchlist_id: UUID) -> Watchlist:
   pass

def add_asset_to_watchlist_by_id(self, watchlist_id: UUID, request: AddAssetToWatchlistRequest) -> Watchlist:
   pass

def delete_watchlist_by_id(self, watchlist_id: UUID) -> None:
   pass

def remove_symbol_from_watchlist_by_id(self, watchlist_id: UUID, symbol: str) -> Watchlist:
   pass

Market Data API: Add Request Models

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

Currently API parameters are passed directly into the client methods, instead we should introduce request models similar to the other API clients.

Describe the solution you'd like.

No response

Describe an alternate solution.

No response

Anything else? (Additional Context)

No response

[Bug]: Sphinx throws duplicate cross-reference for Broker and Trading Order types.

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

When we add to docs/api_reference/broker/models

Order
-----

.. autoclass:: alpaca.broker.models.trading.Order

We will get

/Users/alpaca/Development/alpaca-py/alpaca/trading/models.py:docstring of alpaca.trading.models.Order:: WARNING: more than one target found for cross-reference 'Order': alpaca.broker.models.trading.Order, alpaca.trading.models.Order

Expected Behavior

Should be no error

SDK Version I encountered this issue in

v0.3.0

Steps To Reproduce

When we add to docs/api_reference/broker/models


Order
-----

.. autoclass:: alpaca.broker.models.trading.Order

We will get

/Users/alpaca/Development/alpaca-py/alpaca/trading/models.py:docstring of alpaca.trading.models.Order:: WARNING: more than one target found for cross-reference 'Order': alpaca.broker.models.trading.Order, alpaca.trading.models.Order



### Filled out the Steps to Reproduce section?

- [X] I have entered valid steps to reproduce my issue or have attached a minimally reproducible case in code that shows my issue happening; and understand that without this my issue will be flagged as invalid and closed after 30 days.

### Anything else?

Might be Sphinx bug

Trading API: Assets

Implement routes defined the Trading API assets docs.

def get_assets(self, request: GetAssetsRequest) -> List[Asset]:
    pass

def get_asset_by_symbol(self, symbol: str) -> Asset:
   pass
   

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.