Alpaca Basic Trading Bot Based On Time

This is the first post in a series to show working examples of trading bots using Alpaca.

A link to the notebook can be found on GitHub.

First I am going to provide a high level overview of the bot and then show a few key parts of the code. The bot does the following:

  • For an array of assets (3 crypto assets in my example)
  • Buy each asset every x seconds
  • Repeat that buying process some number of times
  • After repeating the buying process some number of times, liquidate all positions
  • Repeat everything

Assets, Buy Wait Time, Cycles

assets_to_buy = ["BTC/USD", "ETH/USD", 'LTC/USD']  # Replace with the assets you want to trade

# Additional Parameters
cycles = 3 # number of buy cycles before liquidating
buy_wait_time = 5 # wait time between buy cycles

Code: Run All, Trading Strategy (ie when to buy), & Liquidate

async def run_all():
    while True:  # Outer loop to continue after liquidation
        i = 0.01 # this is so I can see different qtys
        for _ in range(cycles):
            buy_qty = 0.2 + i # this is so I can see different qtys
            i += 0.01 # this is so I can see different qtys
            await trading_strategy(buy_qty)
            # Wait x seconds before the next buying cycle
            await asyncio.sleep(buy_wait_time)
        
        await liquidate_positions()


async def trading_strategy(buy_qty):
    # Buy buy_qty shares of each asset every minute
    for asset in assets_to_buy:
        try:
            # Place a market order to buy the specified quantity of the asset
            api.submit_order(
                symbol=asset,
                qty=buy_qty,
                side='buy',
                type='market',
                time_in_force='gtc'
            )
            print(f"Bought {buy_qty} unit of {asset}")
        except Exception as e:
            print(f"Failed to buy {asset}: {e}")


async def liquidate_positions():
    # Liquidate all positions (including any bought outside of code)
    positions = api.list_positions()
    for position in positions:
        try:
            # Place a market order to sell the entire position
            api.submit_order(
                symbol=position.symbol,
                qty=position.qty,
                side='sell',
                type='market',
                time_in_force='gtc'
            )
            print(f"Liquidated {position.qty} units of {position.symbol}")
        except Exception as e:
            print(f"Failed to liquidate {position.symbol}: {e}")

Output In Terminal

Historical Orders In Alpaca

Sharing

Related Articles

  • All Post
  • Articles
  • Blog Post
  • General Business Automation
  • Portfolio
  • Stock Market & Finance