Implement strategies and posting trades
This commit is contained in:
115
core/lib/market.py
Normal file
115
core/lib/market.py
Normal file
@@ -0,0 +1,115 @@
|
||||
from alpaca.common.exceptions import APIError
|
||||
|
||||
from core.models import Strategy, Trade
|
||||
from core.util import logs
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
|
||||
def get_balance(account):
|
||||
account_info = account.client.get_account()
|
||||
cash = account_info["equity"]
|
||||
try:
|
||||
return float(cash)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def get_market_value(account, symbol):
|
||||
try:
|
||||
position = account.client.get_position(symbol)
|
||||
return float(position["market_value"])
|
||||
except APIError:
|
||||
return False
|
||||
|
||||
|
||||
def execute_strategy(callback, strategy):
|
||||
cash_balance = get_balance(strategy.account)
|
||||
log.debug(f"Cash balance: {cash_balance}")
|
||||
if not cash_balance:
|
||||
return None
|
||||
|
||||
user = strategy.user
|
||||
account = strategy.account
|
||||
hook = callback.hook
|
||||
base = callback.base
|
||||
quote = callback.quote
|
||||
direction = hook.direction
|
||||
if quote not in ["usd", "usdt", "usdc", "busd"]:
|
||||
log.error(f"Quote not compatible with Dollar: {quote}")
|
||||
return False
|
||||
quote = "usd" # TODO: MASSIVE HACK
|
||||
symbol = f"{base.upper()}/{quote.upper()}"
|
||||
|
||||
if symbol not in account.supported_assets:
|
||||
log.error(f"Symbol not supported by account: {symbol}")
|
||||
return False
|
||||
|
||||
print(f"Identified pair from callback {symbol}")
|
||||
|
||||
# market_from_alpaca = get_market_value(account, symbol)
|
||||
# change_percent = abs(((float(market_from_alpaca)-price)/price)*100)
|
||||
# if change_percent > strategy.price_slippage_percent:
|
||||
# log.error(f"Price slippage too high: {change_percent}")
|
||||
# return False
|
||||
|
||||
# type = "limit"
|
||||
type = "market"
|
||||
trade_size_as_ratio = strategy.trade_size_percent / 100
|
||||
log.debug(f"Trade size as ratio: {trade_size_as_ratio}")
|
||||
amount_usd = trade_size_as_ratio * cash_balance
|
||||
log.debug(f"Trade size: {amount_usd}")
|
||||
price = callback.price
|
||||
if not price:
|
||||
return
|
||||
log.debug(f"Extracted price of quote: {price}")
|
||||
|
||||
# We can do this because the quote IS in $ or equivalent
|
||||
trade_size_in_quote = amount_usd / price
|
||||
log.debug(f"Trade size in quote: {trade_size_in_quote}")
|
||||
|
||||
# calculate sl/tp
|
||||
stop_loss_as_ratio = strategy.stop_loss_percent / 100
|
||||
take_profit_as_ratio = strategy.take_profit_percent / 100
|
||||
log.debug(f"Stop loss as ratio: {stop_loss_as_ratio}")
|
||||
log.debug(f"Take profit as ratio: {take_profit_as_ratio}")
|
||||
|
||||
stop_loss_subtract = price * stop_loss_as_ratio
|
||||
take_profit_add = price * take_profit_as_ratio
|
||||
log.debug(f"Stop loss subtract: {stop_loss_subtract}")
|
||||
log.debug(f"Take profit add: {take_profit_add}")
|
||||
|
||||
stop_loss = price - stop_loss_subtract
|
||||
take_profit = price + take_profit_add
|
||||
|
||||
log.debug(f"Stop loss: {stop_loss}")
|
||||
log.debug(f"Take profit: {take_profit}")
|
||||
|
||||
new_trade = Trade.objects.create(
|
||||
user=user,
|
||||
account=account,
|
||||
hook=hook,
|
||||
symbol=symbol,
|
||||
type=type,
|
||||
# amount_usd=amount_usd,
|
||||
amount=trade_size_in_quote,
|
||||
# price=price,
|
||||
stop_loss=stop_loss,
|
||||
take_profit=take_profit,
|
||||
direction=direction,
|
||||
)
|
||||
new_trade.save()
|
||||
posted, info = new_trade.post()
|
||||
log.debug(f"Posted trade: {posted} - {info}")
|
||||
|
||||
|
||||
def process_callback(callback):
|
||||
log.info(f"Received callback for {callback.hook}")
|
||||
strategies = Strategy.objects.filter(hooks=callback.hook, enabled=True)
|
||||
log.debug(f"Matched strategies: {strategies}")
|
||||
for strategy in strategies:
|
||||
log.debug(f"Executing strategy {strategy}")
|
||||
if callback.hook.user != strategy.user:
|
||||
log.error("Ownership differs between callback and strategy.")
|
||||
return
|
||||
execute_strategy(callback, strategy)
|
||||
@@ -1,5 +1,83 @@
|
||||
# Trade handling
|
||||
from alpaca.common.exceptions import APIError
|
||||
from alpaca.trading.enums import OrderSide, TimeInForce
|
||||
from alpaca.trading.requests import LimitOrderRequest, MarketOrderRequest
|
||||
|
||||
from core.util import logs
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
|
||||
def sync_trades_with_db(user):
|
||||
pass
|
||||
|
||||
|
||||
def post_trade(trade):
|
||||
# the trade is not placed yet
|
||||
trading_client = trade.account.get_client()
|
||||
if trade.direction == "buy":
|
||||
direction = OrderSide.BUY
|
||||
elif trade.direction == "sell":
|
||||
direction = OrderSide.SELL
|
||||
else:
|
||||
raise Exception("Unknown direction")
|
||||
|
||||
cast = {"symbol": trade.symbol, "side": direction, "time_in_force": TimeInForce.IOC}
|
||||
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:
|
||||
return (False, "No amount specified")
|
||||
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 = trading_client.submit_order(order_data=market_order_data)
|
||||
except APIError as e:
|
||||
log.error(f"Error placing market order: {e}")
|
||||
return (False, e)
|
||||
elif trade.type == "limit":
|
||||
if not trade.price:
|
||||
return (False, "Limit order with no price")
|
||||
cast["limit_price"] = trade.price
|
||||
limit_order_data = LimitOrderRequest(**cast)
|
||||
try:
|
||||
order = trading_client.submit_order(order_data=limit_order_data)
|
||||
except APIError as e:
|
||||
log.error(f"Error placing limit order: {e}")
|
||||
return (False, e)
|
||||
|
||||
print("ORDER", order)
|
||||
else:
|
||||
raise Exception("Unknown trade type")
|
||||
trade.response = order
|
||||
trade.status = "posted"
|
||||
trade.order_id = order["id"]
|
||||
trade.client_order_id = order["client_order_id"]
|
||||
trade.save()
|
||||
return (True, order)
|
||||
|
||||
|
||||
def update_trade(self):
|
||||
pass
|
||||
|
||||
|
||||
def close_trade(trade):
|
||||
pass
|
||||
|
||||
|
||||
def get_position_info(account, asset_id):
|
||||
trading_client = account.get_client()
|
||||
try:
|
||||
position = trading_client.get_open_position(asset_id)
|
||||
except APIError as e:
|
||||
return (False, e)
|
||||
return (True, position)
|
||||
|
||||
Reference in New Issue
Block a user