Hi there, I am trying to set up a multileg order submission function. So far I have no problem creating a multileg option order. However, if I want to include stock into the leg to create, for example, a covered call structure, then it always throw the following error:
equity legs are allowed only with a corresponding amount of call contracts. This error persists no matter what I change about the method (changing ratio quantity, closing an existing position instead of opening, etc.)
Any insights on how to set it up?
import requests
def option_test():
short_symbol='SPY260821C00743000'
stock_symbol='SPY'
quantity=1
limit_price=720
global api_key,secret_key
if not api_key or not secret_key:
raise ValueError("API keys missing!")
url = "https://paper-api.alpaca.markets/v2/orders"
headers = {
"accept": "application/json",
"content-type": "application/json",
"APCA-API-KEY-ID": api_key,
"APCA-API-SECRET-KEY": secret_key
}
payload = {
"order_class": "mleg",
"type": "limit",
"limit_price": str(limit_price),
"time_in_force": "day",
"qty": str(quantity),
"legs": [
{
"symbol": short_symbol,
"side": "sell",
"ratio_qty": "1",
"position_intent": "sell_to_open"
},
{
"symbol": stock_symbol,
"side": "buy",
"ratio_qty": "1",
"position_intent": "buy_to_open"
}
]
}
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
order_data = response.json()
print(f"Successfully submitted live close order via REST API. Order ID: {order_data.get('id')}")
return order_data
except requests.exceptions.HTTPError as http_err:
try:
error_msg = response.json()
except Exception:
error_msg = response.text
print(f"Alpaca API Error: {error_msg}")
raise http_err
except Exception as e:
print(f"Failed to submit live order: {e}")
raise e