I am trying to set a stop loss and take profit for a market order:

OrderTicket orderTicket = MarketOrder(_ticker, quantity);
if (orderTicket.Status == OrderStatus.Filled) {
  // set stop loss
  decimal stopLoss = StopLoss(_price);
  OrderTicket stopLossTicket = StopMarketOrder(_ticker, -quantity, stopLoss);

  // set take profit
  decimal takeProfit = TakeProfit(_price);
  OrderTicket takeProfitTicket = LimitOrder(_ticker, -quantity, takeProfit);

But the second pending order is always invalid. I guess I can only enter a position for a quantity that i actually have? So as a solution I will enter one position (for example stop loss) and handle the other one manually in code. Is there some other better solution to handle stop loss and take profit?