Last active
August 14, 2024 17:38
-
-
Save vitorcalvi/30806b5c5898f76d72dadd9139dff7b0 to your computer and use it in GitHub Desktop.
Python Script for Opening and Closing Positions in Alpaca
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from alpaca_trade_api.rest import REST | |
# Set your Alpaca API credentials | |
ALPACA_API_KEY = 'PK1BN6P47Q9J5GMPJSXY' | |
ALPACA_SECRET_KEY = 'k1sXSgCkrpWSqQ3wyuKqwMT9H7q3hFLEAiVL0lif' | |
ALPACA_BASE_URL = 'https://paper-api.alpaca.markets' | |
# Initialize the Alpaca API | |
api = REST(ALPACA_API_KEY, ALPACA_SECRET_KEY, base_url=ALPACA_BASE_URL) | |
# 1. Placing an Order | |
def place_order(symbol, qty, side): | |
try: | |
order = api.submit_order( | |
symbol=symbol, # Symbol with '/' | |
qty=qty, # Quantity | |
side=side, # "buy" or "sell" | |
type="market", | |
time_in_force="gtc" | |
) | |
print(f"Order submitted successfully: {order}") | |
return order | |
except Exception as e: | |
print(f"Error placing order: {e}") | |
return None | |
# 2. Monitoring the Order | |
def monitor_order(order_id): | |
retries = 5 | |
delay = 2 # seconds | |
for attempt in range(retries): | |
try: | |
order_status = api.get_order(order_id) | |
print("Order status:", order_status) | |
return order_status | |
except Exception as e: | |
print(f"Error monitoring order, attempt {attempt + 1}: {e}") | |
time.sleep(delay) # Wait before trying again | |
print("Failed to retrieve the order status after several attempts.") | |
return None | |
# 3. Query BTC Balance | |
def get_available_balance(symbol): | |
time.sleep(2) # Add a delay to allow positions to update | |
try: | |
positions = api.list_positions() | |
# Check both formats of the symbol | |
for position in positions: | |
if position.symbol == symbol or position.symbol.replace('/', '') == symbol.replace('/', ''): | |
return float(position.qty) | |
print(f"No positions found for {symbol}.") | |
return 0.0 | |
except Exception as e: | |
print(f"Error retrieving balance: {e}") | |
return 0.0 | |
# 4. Closing the Order | |
def close_order(symbol): | |
try: | |
available_qty = get_available_balance(symbol) | |
if available_qty > 0: | |
close_order = api.submit_order( | |
symbol=symbol, # Symbol with '/' | |
qty=available_qty, # Sell only the available quantity | |
side="sell", | |
type="market", | |
time_in_force="gtc" | |
) | |
print("Close order submitted:", close_order) | |
return close_order | |
else: | |
print("No available balance to sell.") | |
return None | |
except Exception as e: | |
print("Error closing order:", e) | |
return None | |
# Execute the workflow | |
if __name__ == "__main__": | |
symbol = "BTC/USD" | |
qty = 0.001 # Example quantity to buy | |
print("Placing order...") | |
placed_order = place_order(symbol, qty, "buy") | |
if placed_order: | |
print("\nMonitoring order...") | |
monitored_order = monitor_order(placed_order.id) # Use the order's unique ID | |
if monitored_order: | |
print("\nClosing order...") | |
closed_order = close_order(symbol) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Python script interacts with the Alpaca trading API to automate the process of opening and closing a position in cryptocurrency trading.
Key Steps:
Place an Order: Submits a market buy order for a specified cryptocurrency (e.g., BTC/USD).
Monitor the Order: Checks and confirms when the buy order has been filled.
Query Balance: Retrieves the available balance of the purchased cryptocurrency after the buy order is filled.
Close the Position: Submits a market sell order to close the position using the exact available balance, ensuring no errors due to insufficient funds.