2022-10-30 10:57:53 +00:00
|
|
|
from alpaca.common.exceptions import APIError
|
2022-10-30 11:21:48 +00:00
|
|
|
from alpaca.trading.client import TradingClient
|
2022-10-30 10:57:53 +00:00
|
|
|
from alpaca.trading.enums import OrderSide, TimeInForce
|
2022-10-30 11:21:48 +00:00
|
|
|
from alpaca.trading.requests import (
|
|
|
|
GetAssetsRequest,
|
|
|
|
LimitOrderRequest,
|
|
|
|
MarketOrderRequest,
|
|
|
|
)
|
2022-10-30 10:57:53 +00:00
|
|
|
|
2022-12-13 07:20:49 +00:00
|
|
|
from core.exchanges import BaseExchange, ExchangeError, GenericAPIError, common
|
2022-10-30 19:11:07 +00:00
|
|
|
|
2022-10-30 10:57:53 +00:00
|
|
|
|
2022-11-04 07:20:55 +00:00
|
|
|
class AlpacaExchange(BaseExchange):
|
2022-10-30 10:57:53 +00:00
|
|
|
def connect(self):
|
|
|
|
self.client = TradingClient(
|
2022-10-30 11:21:48 +00:00
|
|
|
self.account.api_key,
|
|
|
|
self.account.api_secret,
|
|
|
|
paper=self.account.sandbox,
|
|
|
|
raw_data=True,
|
2022-10-30 10:57:53 +00:00
|
|
|
)
|
|
|
|
|
2022-10-30 11:21:48 +00:00
|
|
|
def get_account(self):
|
2022-11-04 07:20:14 +00:00
|
|
|
return self.call("get_account")
|
2022-10-30 11:21:48 +00:00
|
|
|
|
2022-12-13 07:20:49 +00:00
|
|
|
def get_instruments(self):
|
2022-10-30 19:11:07 +00:00
|
|
|
request = GetAssetsRequest(status="active", asset_class="crypto")
|
2022-11-04 07:20:55 +00:00
|
|
|
assets = self.call("get_all_assets", filter=request)
|
2022-12-13 07:20:49 +00:00
|
|
|
return assets
|
|
|
|
|
|
|
|
def get_currencies(self, currencies):
|
|
|
|
pass # TODO
|
|
|
|
|
|
|
|
def get_supported_assets(self):
|
|
|
|
assets = self.get_instruments()
|
2022-10-30 19:11:07 +00:00
|
|
|
assets = assets["itemlist"]
|
|
|
|
asset_list = [x["symbol"] for x in assets if "symbol" in x]
|
|
|
|
|
2022-11-04 07:20:55 +00:00
|
|
|
return asset_list
|
2022-10-30 10:57:53 +00:00
|
|
|
|
|
|
|
def get_balance(self):
|
2022-11-04 07:20:55 +00:00
|
|
|
account_info = self.call("get_account")
|
2022-10-30 10:57:53 +00:00
|
|
|
equity = account_info["equity"]
|
|
|
|
try:
|
|
|
|
balance = float(equity)
|
|
|
|
except ValueError:
|
2022-11-04 07:20:55 +00:00
|
|
|
raise GenericAPIError(f"Balance is not a float: {equity}")
|
2022-10-30 10:57:53 +00:00
|
|
|
|
2022-12-13 07:20:49 +00:00
|
|
|
common.get_balance_hook(
|
|
|
|
self.account.user.id,
|
|
|
|
self.account.user.username,
|
|
|
|
self.account.id,
|
|
|
|
self.account.name,
|
|
|
|
balance,
|
|
|
|
)
|
2022-11-04 07:20:55 +00:00
|
|
|
return balance
|
2022-10-30 10:57:53 +00:00
|
|
|
|
2022-10-31 08:58:08 +00:00
|
|
|
def get_market_value(self, symbol): # TODO: pydantic
|
2022-10-30 10:57:53 +00:00
|
|
|
try:
|
|
|
|
position = self.client.get_position(symbol)
|
|
|
|
except APIError as e:
|
|
|
|
self.log.error(f"Could not get market value for {symbol}: {e}")
|
2022-11-04 07:20:55 +00:00
|
|
|
raise GenericAPIError(e)
|
2022-10-30 10:57:53 +00:00
|
|
|
return float(position["market_value"])
|
|
|
|
|
2022-10-31 08:58:08 +00:00
|
|
|
def post_trade(self, trade): # TODO: pydantic
|
2022-10-30 10:57:53 +00:00
|
|
|
# the trade is not placed yet
|
|
|
|
if trade.direction == "buy":
|
|
|
|
direction = OrderSide.BUY
|
|
|
|
elif trade.direction == "sell":
|
|
|
|
direction = OrderSide.SELL
|
|
|
|
else:
|
2022-11-04 07:20:55 +00:00
|
|
|
raise ExchangeError("Unknown direction")
|
2022-10-30 10:57:53 +00:00
|
|
|
|
2022-10-30 11:21:48 +00:00
|
|
|
cast = {
|
|
|
|
"symbol": trade.symbol,
|
|
|
|
"side": direction,
|
2022-12-13 07:20:49 +00:00
|
|
|
"time_in_force": TimeInForce.IOC, # TODO
|
2022-10-30 11:21:48 +00:00
|
|
|
}
|
2022-10-30 10:57:53 +00:00
|
|
|
if trade.amount is not None:
|
|
|
|
cast["qty"] = trade.amount
|
|
|
|
if trade.amount_usd is not None:
|
|
|
|
cast["notional"] = trade.amount_usd
|
|
|
|
if not trade.amount and not trade.amount_usd:
|
2022-11-04 07:20:55 +00:00
|
|
|
raise ExchangeError("No amount specified")
|
2022-10-30 10:57:53 +00:00
|
|
|
if trade.take_profit:
|
|
|
|
cast["take_profit"] = {"limit_price": trade.take_profit}
|
|
|
|
if trade.stop_loss:
|
|
|
|
stop_limit_price = trade.stop_loss - (trade.stop_loss * 0.005)
|
|
|
|
cast["stop_loss"] = {
|
|
|
|
"stop_price": trade.stop_loss,
|
|
|
|
"limit_price": stop_limit_price,
|
|
|
|
}
|
|
|
|
if trade.type == "market":
|
|
|
|
market_order_data = MarketOrderRequest(**cast)
|
|
|
|
try:
|
|
|
|
order = self.client.submit_order(order_data=market_order_data)
|
|
|
|
except APIError as e:
|
2022-10-30 11:21:48 +00:00
|
|
|
self.log.error(f"Error placing market order: {e}")
|
2022-10-30 19:11:07 +00:00
|
|
|
trade.status = "error"
|
|
|
|
trade.save()
|
2022-11-04 07:20:55 +00:00
|
|
|
raise GenericAPIError(e)
|
2022-10-30 10:57:53 +00:00
|
|
|
elif trade.type == "limit":
|
|
|
|
if not trade.price:
|
2022-11-04 07:20:55 +00:00
|
|
|
raise ExchangeError("No price specified for limit order")
|
2022-10-30 10:57:53 +00:00
|
|
|
cast["limit_price"] = trade.price
|
|
|
|
limit_order_data = LimitOrderRequest(**cast)
|
|
|
|
try:
|
|
|
|
order = self.client.submit_order(order_data=limit_order_data)
|
|
|
|
except APIError as e:
|
2022-10-30 11:21:48 +00:00
|
|
|
self.log.error(f"Error placing limit order: {e}")
|
2022-10-30 19:11:07 +00:00
|
|
|
trade.status = "error"
|
|
|
|
trade.save()
|
2022-11-04 07:20:55 +00:00
|
|
|
raise GenericAPIError(e)
|
2022-10-30 10:57:53 +00:00
|
|
|
|
|
|
|
else:
|
2022-11-04 07:20:55 +00:00
|
|
|
raise ExchangeError("Unknown trade type")
|
2022-10-30 10:57:53 +00:00
|
|
|
trade.response = order
|
|
|
|
trade.status = "posted"
|
|
|
|
trade.order_id = order["id"]
|
|
|
|
trade.client_order_id = order["client_order_id"]
|
|
|
|
trade.save()
|
2022-11-04 07:20:55 +00:00
|
|
|
return order
|
2022-10-30 10:57:53 +00:00
|
|
|
|
2023-02-20 07:20:03 +00:00
|
|
|
def close_trade(self, trade_id, units=None): # TODO
|
2023-01-02 18:42:03 +00:00
|
|
|
"""
|
|
|
|
Close a trade
|
|
|
|
"""
|
|
|
|
|
2022-10-30 10:57:53 +00:00
|
|
|
def get_trade(self, trade_id):
|
2022-12-13 07:20:49 +00:00
|
|
|
pass # TODO
|
2022-10-30 10:57:53 +00:00
|
|
|
|
|
|
|
def update_trade(self, trade):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def cancel_trade(self, trade_id):
|
|
|
|
pass
|
|
|
|
|
2022-11-02 18:25:34 +00:00
|
|
|
def get_position_info(self, symbol):
|
2022-11-04 07:20:55 +00:00
|
|
|
position = self.call("get_open_position", symbol)
|
2022-12-13 07:20:49 +00:00
|
|
|
return position # TODO: check
|
2022-10-30 10:57:53 +00:00
|
|
|
|
|
|
|
def get_all_positions(self):
|
|
|
|
items = []
|
2022-11-04 07:20:55 +00:00
|
|
|
response = self.call("get_all_positions")
|
2022-10-30 10:57:53 +00:00
|
|
|
|
2022-11-02 18:25:34 +00:00
|
|
|
for item in response["itemlist"]:
|
2022-11-02 18:28:31 +00:00
|
|
|
item["account"] = self.account.name
|
2022-10-30 10:57:53 +00:00
|
|
|
item["account_id"] = self.account.id
|
|
|
|
item["unrealized_pl"] = float(item["unrealized_pl"])
|
|
|
|
items.append(item)
|
2022-11-04 07:20:55 +00:00
|
|
|
return items
|
2022-12-02 07:20:37 +00:00
|
|
|
|
|
|
|
def close_position(self, side, symbol):
|
2022-12-13 07:20:49 +00:00
|
|
|
pass # TODO
|
2022-12-02 07:20:37 +00:00
|
|
|
|
|
|
|
def close_all_positions(self):
|
2022-12-13 07:20:49 +00:00
|
|
|
pass # TODO
|