tfukaza / harvest

Simple and intuitive Python framework for algorithmic trading. Easily create bots to live and paper trade stocks, crypto, and options!
https://tfukaza.github.io/harvest-website
MIT License
124 stars 26 forks source link

[🪲BUG] Cannot get it to work with alpaca #300

Open Immortality-IMT opened 5 months ago

Immortality-IMT commented 5 months ago

Describe the bug I think the alpaca.py needs a few updates

To Reproduce Try and run a script with alpaca exchange

Expected behavior Strategy to run...

Below is the code I used. I think the API has been updated and alpaca .py regarding several aspects. My attempt was to paper trade, run the code to see the bug.I think the API has been slightly updated to version 2 and the function need an extra parameter...

# !pip install alpaca-py
# Updated imports to use PaperTrader instead of LiveTrader
from harvest.trader import PaperTrader
from harvest.api.alpaca import Alpaca
from harvest.algo import BaseAlgo
# Import necessary modules
from alpaca.data.timeframe import TimeFrame, TimeFrameUnit
from harvest.algo import Interval  # Make sure to import Interval from harvest.algo

# Mapping from Interval enum values to corresponding TimeFrameUnit objects
interval_to_timeframe = {
    Interval.MIN_1: TimeFrameUnit.Minute,
    Interval.MIN_5: TimeFrameUnit.Minute,
    Interval.MIN_15: TimeFrameUnit.Minute,
    Interval.MIN_30: TimeFrameUnit.Minute,
    Interval.HR_1: TimeFrameUnit.Hour,
    Interval.DAY_1: TimeFrameUnit.Day
}

class MyAlgo(BaseAlgo):
    def config(self):
        self.watchlist = ["TLSA"]
        self.interval = "5MIN"

    def main(self):
        short_avg = self.sma(period=20)
        long_avg = self.sma(period=50)

        if self.crossover(short_avg, long_avg):
            self.sell()
        elif self.crossover(long_avg, short_avg):
            self.buy()

if __name__ == "__main__":
    # Set your Alpaca API keys here
    alpaca_api_key = "P..0"
    alpaca_secret_key = "r..Y"

    # Initialize the Alpaca broker
    alpaca_broker = Alpaca(
        path=None,
        is_basic_account=False,
        paper_trader=True
    )

    # Manually set the API keys
    alpaca_api_key = "P................U"
    alpaca_secret_key = "r................h"

    # Ensure the streamer and broker strings are correctly set
    streamer_name = "alpaca"
    broker_name = "alpaca"

    # Initialize the trader with the appropriate string identifiers
    # Use PaperTrader instead of LiveTrader
    t = PaperTrader(streamer=streamer_name, storage="base", debug=True)

    # Set the algorithm
    t.set_algo(MyAlgo())

    # Run the trader
    t.start(interval="5MIN", sync=True, server=False, all_history=True)