timkpaine / tdameritrade

Python interface to TD Ameritrade (https://developer.tdameritrade.com)
Apache License 2.0
521 stars 203 forks source link

Stop limit order #108

Open hnguyen2k opened 4 years ago

hnguyen2k commented 4 years ago

I've been trying to set a stop limit order for a vertical spread, but haven't been successful.

Whenever I set the orderType to OrderType.STOP_LIMIT, I got the following error from the broker: _b'{\n "error" : "OrderType must be one of those values: NET_CREDIT, NET_DEBIT, NETZERO or MARKET."\n}'

If I set the orderType to OrderType.NET_CREDIT or OrderType.NET_DEBIT, it became a Limit Order, which is not a Stop Limit Order.

Here is my code to build a stop limit order to buy back a vertical spread:

 def build_stop_limit_for_vertical_spread_order(
      self, sell_symbol, buy_symbol, quantity, stop_price):
         # Constants
         order_type = OrderType.STOP_LIMIT
         session = Session.NORMAL
         duration = Duration.DAY
         order_strategy_type = OrderStrategyType.SINGLE

         _buy_order_leg = create_option_order_leg(
             instruction=Instruction.BUY_TO_OPEN, quantity=quantity, symbol=buy_symbol,
         )

         _sell_order_leg = create_option_order_leg(
             instruction=Instruction.SELL_TO_OPEN, quantity=quantity, symbol=sell_symbol,
         )

         order_leg_collection = [
             _buy_order_leg,
             _sell_order_leg,
         ]

         # Hard coded 1% from the stop price as the price limit
         limit_price = str(stop_price + 0.01*stop_price) 

         return Order(
             orderType=order_type,
             session=session,
             price=limit_price,
             stopPrice=stop_price,
             stopType=StopType.BID,
             duration=duration,
             orderStrategyType=order_strategy_type,
             orderLegCollection=order_leg_collection,
         )

I read TD API from https://developer.tdameritrade.com/account-access/apis/post/accounts/%7BaccountId%7D/orders-0. It seems that they support stop limit order through API.

Can you please point out what wrong with the code? Has anyone successfully gotten the stop limit order working? Any sample code of it is very appreciated. Thanks!

timkpaine commented 3 years ago

I second this https://github.com/areed1192/td-ameritrade-python-api/issues/113#issuecomment-715557887