alpacahq / alpaca-py

The Official Python SDK for Alpaca API
https://alpaca.markets/sdks/python/getting_started.html
Apache License 2.0
568 stars 140 forks source link

[Question]: How can I inherit the sdk's classes e.g. TradingClient? #355

Closed dskarbrevik closed 1 year ago

dskarbrevik commented 1 year ago

Question form pre-submit checklist.

Question

I'm trying to extend the capabilities of alpaca.trading.client.TradingClient

I tried to start a very simple example by creating a subclass like this:

class StockTrader(TradingClient):
    def __init__(self, api_key, secret_key, paper):
        super().__init__(api_key=api_key, secret_key=secret_key, paper=paper)

    def get_account(self):
        return super().get_account()

However when I try to use this class:

trader = StockTrader(api_key,secret_key,paper)
trader.get_account()

I get the following error:

TypeError: TradingClient.get_account() missing 1 required positional argument: 'self'

Is there an obvious reason why inheriting from TradingClient like this can't work?

hiohiohio commented 1 year ago

@dskarbrevik I can not replicate this issue in my local environment and also Google Colab. Can you please provide more information to replicate this issue such as version of alpaca-py and Python .

Below is the code I have tested in my end with alpaca-py v0.11.0 and Python 3.10.12 / Python 3.11.5.

from alpaca.trading.client import TradingClient

class StockTrader(TradingClient):
    def __init__(self, api_key, secret_key, paper):
        super().__init__(api_key=api_key, secret_key=secret_key, paper=paper)

    def get_account(self):
        return super().get_account()

api_key=<PAPER API KEY>
secret_key=<PAPER API SECRET>
paper = True

trader = StockTrader(api_key, secret_key, paper)
trader.get_account()
alessiocastrica commented 1 year ago

IMO generally this method:

def get_account(self):
        return super().get_account()

should actually be:

def custom_get_account(self):
        account =  self.get_account()
        # do something else here
        return account

or even better you shouldn't re-define the same method if you're not doing anything else apart from calling the method of the parent class and returning it. You can find more info in the python docs.

dskarbrevik commented 1 year ago

Thank you both for the replies... I was just being dumb and trying to run StockTrader.get_account() instead of the code I actually posted...