Repository navigation
Expand file tree
/
Copy pathbroker.py
More file actions
311 lines (268 loc) · 10.3 KB
/
Copy pathbroker.py
File metadata and controls
311 lines (268 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
"""Alpaca Paper Trading Broker Client.
Uses raw REST API calls via requests (no alpaca-py dependency).
Supports paper trading with 2x leverage for short selling.
"""
import logging
import time
from typing import Optional, Dict, Any, List
import requests
logger = logging.getLogger(__name__)
class AlpacaBroker:
"""Alpaca REST API client for paper trading."""
def __init__(
self,
api_key: str,
secret_key: str,
base_url: str = "https://paper-api.alpaca.markets",
data_url: str = "https://data.alpaca.markets",
):
self.api_key = api_key
self.secret_key = secret_key
self.base_url = base_url.rstrip("/")
self.data_url = data_url.rstrip("/")
self.headers = {
"APCA-API-KEY-ID": self.api_key,
"APCA-API-SECRET-KEY": self.secret_key,
"Accept": "application/json",
"Content-Type": "application/json",
}
def _request(
self,
method: str,
path: str,
json_data: Optional[Dict] = None,
params: Optional[Dict] = None,
timeout: int = 30,
use_data_url: bool = False,
) -> Dict[str, Any]:
"""Make an authenticated request to Alpaca API."""
base = self.data_url if use_data_url else self.base_url
url = f"{base}{path}"
try:
response = requests.request(
method=method,
url=url,
headers=self.headers,
json=json_data,
params=params,
timeout=timeout,
)
if response.status_code == 204:
return {}
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
error_body = {}
try:
error_body = response.json()
except Exception:
error_body = {"text": response.text}
logger.error(
"Alpaca API error: %s %s -> %s: %s",
method,
path,
response.status_code,
error_body,
)
raise AlpacaError(
status_code=response.status_code,
message=error_body.get("message", str(e)),
code=error_body.get("code", "unknown"),
) from e
except requests.exceptions.RequestException as e:
logger.error("Alpaca request failed: %s %s: %s", method, path, e)
raise
def get_account(self) -> Dict[str, Any]:
"""Get account details including equity, buying power, cash."""
return self._request("GET", "/v2/account")
def get_positions(self) -> List[Dict[str, Any]]:
"""Get all open positions."""
return self._request("GET", "/v2/positions")
def get_position(self, symbol: str) -> Dict[str, Any]:
"""Get position for a specific symbol."""
return self._request("GET", f"/v2/positions/{symbol}")
def submit_order(
self,
symbol: str,
qty: int,
side: str,
order_type: str = "market",
time_in_force: str = "day",
limit_price: Optional[float] = None,
stop_price: Optional[float] = None,
take_profit_price: Optional[float] = None,
) -> Dict[str, Any]:
"""Submit an order to Alpaca.
Args:
symbol: Stock ticker
qty: Number of shares (must be integer for Alpaca)
side: 'buy' or 'sell'
order_type: 'market', 'limit', 'stop', 'stop_limit'
time_in_force: 'day', 'gtc', 'ioc', 'fok'
limit_price: Required for limit orders
stop_price: Required for stop orders
take_profit_price: Target price for a take profit OTO order
Returns:
Order dict with id, status, fills, etc.
"""
qty = int(qty)
if qty <= 0:
raise ValueError(f"Order quantity must be positive, got {qty}")
order_data = {
"symbol": symbol.upper(),
"qty": str(qty),
"side": side.lower(),
"type": order_type.lower(),
"time_in_force": time_in_force.lower(),
}
if limit_price is not None:
order_data["limit_price"] = str(round(limit_price, 2))
if stop_price is not None:
order_data["stop_price"] = str(round(stop_price, 2))
if take_profit_price is not None:
order_data["order_class"] = "oto"
order_data["take_profit"] = {
"limit_price": str(round(take_profit_price, 2))
}
logger.info(
"Submitting order: %s %s %d %s @ %s (TP: %s)",
side.upper(),
symbol.upper(),
qty,
order_type.upper(),
f"${limit_price:.2f}" if limit_price else "MARKET",
f"${take_profit_price:.2f}" if take_profit_price else "NONE",
)
return self._request("POST", "/v2/orders", json_data=order_data)
def close_position(self, symbol: str) -> Dict[str, Any]:
"""Close entire position for a symbol.
Returns:
Order dict for the closing order.
"""
logger.info("Closing position: %s", symbol.upper())
return self._request("DELETE", f"/v2/positions/{symbol}")
def close_all_positions(self) -> List[Dict[str, Any]]:
"""Close all open positions."""
logger.info("Closing all positions")
return self._request("DELETE", "/v2/positions")
def get_order(self, order_id: str) -> Dict[str, Any]:
"""Get order status."""
return self._request("GET", f"/v2/orders/{order_id}")
def get_orders(
self,
status: Optional[str] = None,
limit: int = 50,
direction: str = "desc",
after: Optional[str] = None,
until: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Get list of orders.
Args:
status: Filter by status ('open', 'closed', 'all', 'filled', 'canceled')
after: ISO 8601 datetime - only return orders after this time
until: ISO 8601 datetime - only return orders before this time
"""
params = {"limit": limit, "direction": direction}
if status:
params["status"] = status
if after:
params["after"] = after
if until:
params["until"] = until
return self._request("GET", "/v2/orders", params=params)
def cancel_order(self, order_id: str) -> None:
"""Cancel an open order."""
self._request("DELETE", f"/v2/orders/{order_id}")
def cancel_all_orders(self) -> None:
"""Cancel all open orders."""
self._request("DELETE", "/v2/orders")
def get_latest_price(self, symbol: str) -> Optional[float]:
"""Get latest trade price for a symbol."""
try:
resp = self._request(
"GET",
f"/v2/stocks/{symbol.upper()}/trades/latest",
timeout=10,
use_data_url=True,
)
return float(resp.get("trade", {}).get("p", 0))
except Exception as e:
logger.warning("Failed to get latest price for %s: %s", symbol, e)
return None
def get_bars(
self,
symbol: str,
timeframe: str = "1Day",
limit: int = 100,
) -> List[Dict]:
"""Get historical bars for a symbol."""
params = {"timeframe": timeframe, "limit": limit, "feed": "iex"}
resp = self._request(
"GET",
f"/v2/stocks/{symbol.upper()}/bars",
params=params,
timeout=15,
use_data_url=True,
)
return resp.get("bars", [])
def is_market_open(self) -> bool:
"""Check if the market is currently open."""
try:
resp = self._request("GET", "/v2/clock")
return resp.get("is_open", False)
except Exception:
return False
def get_account_buying_power(self) -> float:
"""Get current buying power (equity * leverage)."""
account = self.get_account()
return float(account.get("buying_power", 0))
def get_account_equity(self) -> float:
"""Get current account equity."""
account = self.get_account()
return float(account.get("equity", 0))
def get_account_cash(self) -> float:
"""Get current cash balance."""
account = self.get_account()
return float(account.get("cash", 0))
def validate_connection(self) -> Dict[str, Any]:
"""Validate connection and return account summary."""
account = self.get_account()
return {
"status": "connected",
"account_id": account.get("id"),
"status": account.get("status"),
"equity": float(account.get("equity", 0)),
"cash": float(account.get("cash", 0)),
"buying_power": float(account.get("buying_power", 0)),
"day_trade_count": int(account.get("daytrade_count", 0)),
"pattern_day_trader": account.get("pattern_day_trader", False),
"trading_blocked": account.get("trading_blocked", False),
"shorting_enabled": account.get("shorting_enabled", False),
}
class AlpacaError(Exception):
"""Alpaca API error."""
def __init__(self, status_code: int, message: str, code: str = "unknown"):
self.status_code = status_code
self.message = message
self.code = code
super().__init__(f"Alpaca error {status_code} ({code}): {message}")
def create_broker_from_env(account_type: str = "core") -> AlpacaBroker:
"""Create a broker instance from environment variables.
Args:
account_type: 'core' or 'ai' to select the right account keys
Returns:
AlpacaBroker instance
"""
import os
prefix = "ALPACA_CORE" if account_type == "core" else "ALPACA_AI"
api_key = os.environ.get(f"{prefix}_API_KEY", "")
secret_key = os.environ.get(f"{prefix}_SECRET_KEY", "")
base_url = os.environ.get(
"ALPACA_PAPER_URL", "https://paper-api.alpaca.markets"
)
if not api_key or not secret_key:
raise ValueError(
f"Missing Alpaca credentials for {account_type} account. "
f"Set {prefix}_API_KEY and {prefix}_SECRET_KEY environment variables."
)
return AlpacaBroker(api_key=api_key, secret_key=secret_key, base_url=base_url)