I need some advice regarding a part of my automated strategy. Here’s the scenario:
- At 7:00 AM, I enter a long trade.
- By 7:05 AM, the trade is in a negative position, but the stop loss hasn’t been triggered.
- At this point, the method ReversePosition() is called. This closes the current ATM strategy and attempts to open a trade in the opposite direction.
However, instead of successfully opening the new position, I encounter an error.
I’ve tried implementing logic to prevent this issue (see code below) but haven’t been able to resolve it. Specifically, I’m looking for:
- A better way to retrieve the order status after canceling an order.
- Guidance on how to wait until the order is no longer in the CancelPending state before submitting the new order.
Thank you for your help!
Error log:
| Order 'fb09e1e1506e403fbd64aacfec319c95' can't be submitted: order status is CancelPending. affected Order: Sell 5 Market |
| Order='fb09e1e1506e403fbd64aacfec319c95/APEX-41035-71' Name='Close' New state='Rejected' Instrument='ES 12-24' Action='Sell' Limit price=0 Stop price=0 Quantity=5 Type='Market' Time in force=GTC Oco='' Filled=0 Fill price=0 Error='Unable to submit order' Native error='Order 'fb09e1e1506e403fbd64aacfec319c95' can't be submitted: order status is CancelPending.' |
#region Reverse Position
private void ReversePosition()
{
// Reverse the position logic
if (GetAtmStrategyMarketPosition(atmStrategyId) == MarketPosition.Long)
{
AtmStrategyClose(atmStrategyId); // Close the long position
// Wait until the cancel operation completes
while (true)
{
string[] orderStatus = GetAtmStrategyEntryOrderStatus(atmStrategyOrderId);
// Check if the returned array contains valid order information
if (orderStatus.Length > 0)
{
string currentState = orderStatus[2]; // The third element represents the order state
if (currentState != "CancelPending")
break; // Exit the loop once the state is no longer CancelPending
Print("LONG position is being cancelled...");
}
else
{
Print("No order information found. Exiting loop.");
break;
}
System.Threading.Thread.Sleep(50); // Pause for 50 milliseconds
}
atmStrategyId = GetAtmStrategyUniqueId();
atmStrategyOrderId = GetAtmStrategyUniqueId();
double bidPrice = GetCurrentBid(); // Get the current bid price
Print("Current Bid is: " + bidPrice);
AtmStrategyCreate(OrderAction.Sell, OrderType.Limit, bidPrice, 0, TimeInForce.Day,
atmStrategyOrderId, "ATM T-Stop 5 Lot", atmStrategyId, (atmCallbackErrorCode, atmCallbackId) => {
if (atmCallbackId == atmStrategyId && atmCallbackErrorCode == Cbi.ErrorCode.NoError)
{
isAtmStrategyCreated = true;
Print("Reversing the losing LONG Position!");
}
});
}

Comment