async def openOrder(
marketId: str,
initialMargin: float,
initialNotional: float,
isLong: bool,
priceThreshold: float,
stopLossPrice: float = 0,
takeProfitPrice: float = 0,
):
greatestOrderId = 0
orders = await retrieveOrders()
# Validate that new order side matches existing open orders in this market
new_order_side = Side.SIDE_LONG if isLong else Side.SIDE_SHORT
for order in orders:
if order.market_id == marketId:
# Check orders that are still open
if order.status in [
OrderStatus.ORDER_STATUS_PENDING,
OrderStatus.ORDER_STATUS_PARTIALLY_FILLED,
OrderStatus.ORDER_STATUS_PARTIALLY_MERGED,
]:
if order.side != new_order_side:
raise ValueError(
"Cannot open order with opposite side of current open orders"
)
if order.order_id > greatestOrderId:
greatestOrderId = order.order_id
contract = retrieveContract()
w3 = retrieveWeb3Instance()
tick_units = await retrieveMarketTickDecimals(marketId)
transaction = contract.functions.openOrder(
(
marketId,
convertFloatToUINT(initialMargin, USDC_DECIMALS),
convertFloatToUINT(initialNotional, USDC_DECIMALS),
isLong,
convertFloatToUINT(priceThreshold, tick_units),
# These parameters are interpreted on chain and reduce order is executed automatically setting the order to the approriate type
convertFloatToUINT(stopLossPrice, tick_units),
convertFloatToUINT(takeProfitPrice, tick_units),
)
).build_transaction(
{
"from": Web3.to_checksum_address(os.getenv("ACCOUNT")),
"nonce": w3.eth.get_transaction_count(
Web3.to_checksum_address(os.getenv("ACCOUNT")),
),
"gas": GAS_VALUE,
"gasPrice": math.ceil(w3.eth.gas_price + (w3.eth.gas_price * 0.25)),
}
)
await submitTransactionWithOracle(w3, transaction, marketId)
# TODO if order sucessfully submitted, do we immediatley call recude order if its a SL/TP order here?
found = False
count = 0
while found == False:
orders = await retrieveOrders()
for i, order in enumerate(orders, 0):
if order.market_id == marketId:
if order.order_id > greatestOrderId:
greatestOrderId = order.order_id
found = True
retVal = order
if found == False:
count += 1
if count == 9:
break
time.sleep(5)
if found:
print(retVal)
return retVal
else:
print("Max retry attempts reached")