Improve posting trades to OANDA and make everything more robust

This commit is contained in:
2022-11-10 19:27:46 +00:00
parent bf863f43b2
commit af9f874209
11 changed files with 267 additions and 30 deletions

View File

@@ -4,11 +4,46 @@ from alpaca.common.exceptions import APIError
from core.models import Strategy, Trade
from core.util import logs
from core.exchanges import GenericAPIError
log = logs.get_logger(__name__)
def to_usd(account, amount, from_currency):
if account.exchange == "alpaca":
separator = "/"
elif account.exchange == "oanda":
separator = "_"
symbol = f"{from_currency.upper()}{separator}{to_currency.upper()}"
prices = account.client.get_currencies([symbol])
def to_currency(direction, account, amount, from_currency, to_currency):
if account.exchange == "alpaca":
separator = "/"
elif account.exchange == "oanda":
separator = "_"
if direction == "buy":
price_index = "bids"
elif direction == "sell":
price_index = "asks"
symbol = f"{from_currency.upper()}{separator}{to_currency.upper()}"
if symbol not in account.supported_symbols:
symbol = f"{to_currency.upper()}{separator}{from_currency.upper()}"
inverted = True
try:
prices = account.client.get_currencies([symbol])
except GenericAPIError as e:
log.error(f"Error getting currencies and inverted currencies: {e}")
return None
price = prices["prices"][0][price_index][0]["price"]
if inverted:
price = D(1.0) / D(price)
converted = D(amount) * price
return converted
def execute_strategy(callback, strategy):
cash_balance = strategy.account.client.get_balance()
instruments = strategy.account.instruments
log.debug(f"Cash balance: {cash_balance}")
user = strategy.user
@@ -20,21 +55,31 @@ def execute_strategy(callback, strategy):
if callback.exchange != account.exchange:
log.error("Market exchange differs from account exchange.")
return
if account.exchange == "alpaca":
separator = "/"
elif account.exchange == "oanda":
separator = "_"
if account.exchange == "alpaca":
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()}"
elif account.exchange == "oanda":
symbol = f"{base.upper()}_{quote.upper()}"
symbol = f"{base.upper()}{separator}{quote.upper()}"
if symbol not in account.supported_symbols:
log.error(f"Symbol not supported by account: {symbol}")
return False
print(f"Identified pair from callback {symbol}")
instrument = strategy.account.client.extract_instrument(instruments, symbol)
if not instrument:
log.error(f"Symbol not found: {symbol}")
return False
try:
trade_precision = instrument["tradeUnitsPrecision"]
display_precision = instrument["displayPrecision"]
except KeyError:
log.error(f"Precision not found for {symbol}")
return False
# 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:
@@ -45,16 +90,17 @@ def execute_strategy(callback, strategy):
type = "market"
trade_size_as_ratio = D(strategy.trade_size_percent) / D(100)
log.debug(f"Trade size as ratio: {trade_size_as_ratio}")
amount_usd = D(trade_size_as_ratio) * D(cash_balance)
log.debug(f"Trade size: {amount_usd}")
price = round(D(callback.price), 8)
amount_fiat = D(trade_size_as_ratio) * D(cash_balance)
log.debug(f"Trade size: {amount_fiat}")
price = round(D(callback.price), display_precision)
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 = D(amount_usd) / D(price)
log.debug(f"Trade size in quote: {trade_size_in_quote}")
# trade_size_in_base = D(amount_fiat) / D(price)
trade_size_in_base = to_currency(direction, account, amount_fiat, account.currency, base)
log.debug(f"Trade size in base: {trade_size_in_base}")
# calculate sl/tp
stop_loss_as_ratio = D(strategy.stop_loss_percent) / D(100)
@@ -79,11 +125,11 @@ def execute_strategy(callback, strategy):
hook=hook,
symbol=symbol,
type=type,
# amount_usd=amount_usd,
amount=float(round(trade_size_in_quote, 2)),
# amount_fiat=amount_fiat,
amount=float(round(trade_size_in_base, trade_precision)),
# price=price,
stop_loss=float(round(stop_loss, 2)),
take_profit=float(round(take_profit, 2)),
stop_loss=float(round(stop_loss, display_precision)),
take_profit=float(round(take_profit, display_precision)),
direction=direction,
)
new_trade.save()
@@ -99,5 +145,5 @@ def process_callback(callback):
log.debug(f"Executing strategy {strategy}")
if callback.hook.user != strategy.user:
log.error("Ownership differs between callback and strategy.")
return
continue
execute_strategy(callback, strategy)

View File

@@ -352,3 +352,84 @@ AccountInstrumentsSchema = {
],
)
}
class OrderTransaction(BaseModel):
id: str
accountID: str
userID: int
batchID: str
requestID: str
time: str
type: str
instrument: str
units: str
timeInForce: str
positionFill: str
reason: str
class OrderCreate(BaseModel):
orderCreateTransaction: OrderTransaction
OrderCreateSchema = {
"id": "orderCreateTransaction.id",
"accountID": "orderCreateTransaction.accountID",
"userID": "orderCreateTransaction.userID",
"batchID": "orderCreateTransaction.batchID",
"requestID": "orderCreateTransaction.requestID",
"time": "orderCreateTransaction.time",
"type": "orderCreateTransaction.type",
"symbol": "orderCreateTransaction.instrument",
"units": "orderCreateTransaction.units",
"timeInForce": "orderCreateTransaction.timeInForce",
"positionFill": "orderCreateTransaction.positionFill",
"reason": "orderCreateTransaction.reason",
}
class PriceBid(BaseModel):
price: str
liquidity: int
class PriceAsk(BaseModel):
price: str
liquidity: int
class PriceQuoteHomeConversionFactors(BaseModel):
positiveUnits: str
negativeUnits: str
class Price(BaseModel):
type: str
time: str
bids: list[PriceBid]
asks: list[PriceAsk]
closeoutBid: str
closeoutAsk: str
status: str
tradeable: bool
quoteHomeConversionFactors: PriceQuoteHomeConversionFactors
instrument: str
class PricingInfo(BaseModel):
time: str
prices: list[Price]
PricingInfoSchema = {
"time": "time",
"prices": (
"prices",
[
{
"type": "type",
"time": "time",
"bids": "bids",
"asks": "asks",
"closeoutBid": "closeoutBid",
"closeoutAsk": "closeoutAsk",
"status": "status",
"tradeable": "tradeable",
"quoteHomeConversionFactors": "quoteHomeConversionFactors",
"symbol": "instrument",
}
],
),
}