Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.9 kB
1
Indexable
Never
import alpaca_trade_api as tradeapi
import time

# Alpaca API key and secret (replace with your own)
API_KEY = 'your_api_key'
API_SECRET = 'your_api_secret'
BASE_URL = 'https://paper-api.alpaca.markets'  # For paper trading

# Initialize Alpaca API
api = tradeapi.REST(API_KEY, API_SECRET, base_url=BASE_URL, api_version='v2')

# Define trading parameters
symbol = 'AAPL'
quantity = 1

# Main trading loop
while True:
    # Get current account information
    account = api.get_account()

    # Get current stock price
    stock_info = api.get_last_trade(symbol)
    stock_price = stock_info.price

    # Check if account is active for trading
    if account.trading_blocked:
        print("Account is currently restricted from trading.")
    else:
        # Implement your trading strategy here
        # For example, buy if the stock price is below a certain threshold
        if stock_price < 150.0:
            api.submit_order(
                symbol=symbol,
                qty=quantity,
                side='buy',
                type='limit',
                time_in_force='gtc',
                limit_price=stock_price
            )
            print(f"Buy order placed for {quantity} shares of {symbol} at ${stock_price}.")

        # Implement your selling strategy here
        # For example, sell if the stock price reaches a certain target
        elif stock_price > 170.0:
            api.submit_order(
                symbol=symbol,
                qty=quantity,
                side='sell',
                type='limit',
                time_in_force='gtc',
                limit_price=stock_price
            )
            print(f"Sell order placed for {quantity} shares of {symbol} at ${stock_price}.")

    # Sleep for a specified interval (e.g., 1 minute)
    time.sleep(60)
Leave a Comment