Hello everyone,
I am new here and trying to build a trading bot utilizing Alpaca’s API capabilities and keep getting this error while trying to place a trade: “ERROR:root:Error executing trade: Error placing order: 422 Client Error: Unprocessable Entity for url: https://paper-api.alpaca.markets/v2/orders”
I am not familiar with Python at all and absolutely no background in trading or using APIs but I can’t quite understand this. Am I not allowed to use a stop_loss parameter while trying to submit a regular market order or is it more related to how it is formatted and whether it is accepted at all in the current place/submit order API call?
def execute_trade(self, alert, account_balance):
symbol = alert.get("ticker")
action = alert.get("action").upper()
price = float(alert.get("price"))
logging.info(f"Processing trade alert: {alert}")
historical_data = self.fetch_historical_data(symbol)
if historical_data is None:
raise ValueError(f"Unable to fetch historical data for {symbol}.")
stop_loss_price = self.calculate_stop_loss(historical_data, action, symbol)
logging.info(
f"Trade details: Symbol={symbol}, Action={action}, Price={price}, Stop-Loss={stop_loss_price}, Position Size={position_size}"
)
try:
order = self.alpaca_client.place_order(
symbol=symbol,
qty=position_size,
side="buy" if action == "BUY" else "sell",
type="market",
time_in_force="gtc",
stop_loss=dict(stop_price=stop_loss_price),
)
logging.info(f"Trade executed successfully: {order}")
except Exception as e:
logging.error(f"Error executing trade: {e}")
def place_order(self, symbol, qty, side, type, time_in_force, stop_loss):
"""Place an order through Alpaca's trading API."""
url = f"{self.base_url}/v2/orders"
order_data = {
"symbol": symbol,
"qty": qty,
"side": side,
"type": type,
"time_in_force": time_in_force,
}
if stop_loss:
order_data["stop_loss"] = {"stop_price": stop_loss["stop_price"]}
try:
response = requests.post(url, headers=self.headers, json=order_data)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
raise ValueError(f"Error placing order: {e}")
stop_loss is formatted as such: $128.31 - two decimal places and exactly (from what I understand) how the API call expects it.
Could someone point me in the right direction here? What am I missing?
Thank you in advance.