python-binance icon indicating copy to clipboard operation
python-binance copied to clipboard

when i use STOP_MARKET in the latest version, it not work

Open okluoquan opened this issue 11 months ago • 6 comments

when i use STOP_MARKET in the latest version, such as:

order = client.futures_create_order( symbol="BTCUSDT", side=Client.SIDE_SELL, type=Client.FUTURE_ORDER_TYPE_STOP_MARKET, quantity=qty, stopPrice=price, positionSide="LONG", )

get the result:'orderId' trade

and the STOP_MARKET order not work

okluoquan avatar Dec 10 '25 18:12 okluoquan

Hello @okluoquan thanks for reporting it we will take a look and get back to you

carlosmiei avatar Dec 10 '25 20:12 carlosmiei

Hi @okluoquan, I tested on my side and it worked correctly. Are you using the latest version of python-binance ?

Could it be with the latest change createOrder returns algoId instead of orderId?

pcriadoperez avatar Dec 10 '25 23:12 pcriadoperez

Thanks, @pcriadoperez , the problem of “orderId” is solved, but STOP_MARKET order does not work yet.

I am using the latest version, I am using the futures_create_order, can you give me your tested demo?

okluoquan avatar Dec 11 '25 00:12 okluoquan

Hi @okluoquan , yes this is the code I was using:

"""
Example: Using STOP_MARKET orders with python-binance

Important Notes:
- After 2025-12-09, STOP_MARKET orders are automatically routed to the algo order endpoint
- The library converts 'stopPrice' to 'triggerPrice' automatically
- Response contains 'algoId' instead of 'orderId'
- Use futures_cancel_algo_order() to cancel, not futures_cancel_order()
"""

import os
import sys

root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root)

from binance.client import Client

# Initialize client
api_key = ""
secret = ""
client = Client(api_key, secret, testnet=True)  # Set testnet=False for live trading


def check_position_mode():
    """
    Check if account is in Hedge Mode (dualSidePosition=True) or One-way Mode (dualSidePosition=False).

    - One-way Mode: Use positionSide="BOTH" for all orders
    - Hedge Mode: Use positionSide="LONG" or "SHORT" for separate positions
    """
    try:
        position_mode = client.futures_get_position_mode()
        dual_side = position_mode.get('dualSidePosition', False)

        print(f"✓ Current position mode:")
        if dual_side:
            print(f"  - Hedge Mode (dualSidePosition=True)")
            print(f"  - Use positionSide='LONG' or 'SHORT'")
        else:
            print(f"  - One-way Mode (dualSidePosition=False)")
            print(f"  - Use positionSide='BOTH'")

        return dual_side
    except Exception as e:
        print(f"✗ Error checking position mode: {e}")
        return None


def change_position_mode(dual_side_position):
    """
    Change position mode between Hedge Mode and One-way Mode.

    IMPORTANT: You can only change position mode when you have NO open positions or orders!

    Args:
        dual_side_position: True for Hedge Mode, False for One-way Mode
    """
    try:
        result = client.futures_change_position_mode(dualSidePosition=dual_side_position)
        mode_name = "Hedge Mode" if dual_side_position else "One-way Mode"
        print(f"✓ Successfully changed to {mode_name}")
        print(f"  - Response: {result}")
        return result
    except Exception as e:
        print(f"✗ Error changing position mode: {e}")
        print(f"  - Make sure you have NO open positions or orders!")
        return None


def create_stop_market_order(position_side="BOTH"):
    """
    Create a STOP_MARKET order to close a LONG position when price drops to stopPrice.
    This acts as a stop-loss for your LONG position.

    Args:
        position_side: "BOTH" for One-way Mode, "LONG" or "SHORT" for Hedge Mode
    """

    symbol = "BTCUSDT"
    qty = 0.01  # Adjust based on your position size
    stop_price = 80000  # Price at which the order triggers

    try:
        # Create STOP_MARKET order
        order = client.futures_create_order(
            symbol=symbol,
            side=Client.SIDE_SELL,  # SELL to close LONG position (or open SHORT in Hedge Mode)
            type=Client.FUTURE_ORDER_TYPE_STOP_MARKET,
            quantity=qty,
            stopPrice=stop_price,  # Automatically converted to triggerPrice
            positionSide=position_side,  # "BOTH" for One-way, "LONG"/"SHORT" for Hedge
            # Optional parameters:
            # workingType="MARK_PRICE",  # Default is "CONTRACT_PRICE"
            # priceProtect=True,  # Enable price protection
        )

        print("✓ STOP_MARKET order created successfully!")
        print(f"Response: {order}")
        print(f"\nKey fields:")
        print(f"  - algoId: {order.get('algoId')}")
        print(f"  - clientAlgoId: {order.get('clientAlgoId')}")
        print(f"  - symbol: {order.get('symbol')}")
        print(f"  - side: {order.get('side')}")
        print(f"  - triggerPrice: {order.get('triggerPrice')}")

        return order

    except Exception as e:
        print(f"✗ Error creating order: {e}")
        return None


def query_algo_order(symbol, algo_id):
    """
    Query the status of an algo order (STOP_MARKET order).
    """
    try:
        order_info = client.futures_get_algo_order(
            symbol=symbol,
            algoId=algo_id
        )

        print(f"\n✓ Order status:")
        print(f"  - algoId: {order_info.get('algoId')}")
        print(f"  - symbol: {order_info.get('symbol')}")
        print(f"  - algoStatus: {order_info.get('algoStatus')}")  # WORKING, CANCELLED, FINISHED
        print(f"  - triggerPrice: {order_info.get('triggerPrice')}")
        print(f"  - executedQty: {order_info.get('executedQty')}")

        return order_info

    except Exception as e:
        print(f"✗ Error querying order: {e}")
        return None


def cancel_algo_order(symbol, algo_id):
    """
    Cancel an active STOP_MARKET order.
    """
    try:
        result = client.futures_cancel_algo_order(
            symbol=symbol,
            algoId=algo_id
        )

        print(f"\n✓ Order cancelled:")
        print(f"  - algoId: {result.get('algoId')}")
        print(f"  - algoStatus: {result.get('algoStatus')}")

        return result

    except Exception as e:
        print(f"✗ Error cancelling order: {e}")
        return None


def get_all_open_algo_orders(symbol=None):
    """
    Get all open algo orders (including STOP_MARKET orders).
    """
    try:
        params = {}
        if symbol:
            params['symbol'] = symbol

        orders = client.futures_get_algo_open_orders(**params)

        print(f"\n✓ Open algo orders: {len(orders)}")
        for order in orders:
            print(f"  - {order.get('symbol')}: algoId={order.get('algoId')}, "
                  f"type={order.get('algoType')}, "
                  f"triggerPrice={order.get('triggerPrice')}")

        return orders

    except Exception as e:
        print(f"✗ Error getting open orders: {e}")
        return []


def main():
    """
    Example workflow for STOP_MARKET orders.
    """
    print("=" * 60)
    print("STOP_MARKET Order Example")
    print("=" * 60)

    # Step 0: Check position mode
    print("\n0. Checking position mode...")
    is_hedge_mode = check_position_mode()

    if is_hedge_mode is None:
        print("\nFailed to check position mode. Check your API keys.")
        return

    # Determine correct positionSide based on mode
    if is_hedge_mode:
        # Hedge Mode: Use "LONG" to close a LONG position with a SELL order
        position_side = "LONG"
        print(f"\n→ Using positionSide='{position_side}' for Hedge Mode")
    else:
        # One-way Mode: Always use "BOTH"
        position_side = "BOTH"
        print(f"\n→ Using positionSide='{position_side}' for One-way Mode")

    # Step 1: Create a STOP_MARKET order
    print("\n1. Creating STOP_MARKET order...")
    order = create_stop_market_order(position_side=position_side)

    if not order:
        print("\nFailed to create order. Check your API keys and parameters.")
        return

    algo_id = order.get('algoId')
    symbol = order.get('symbol')

    # Step 2: Query the order status
    print("\n2. Querying order status...")
    query_algo_order(symbol, algo_id)

    # Step 3: Get all open algo orders
    print("\n3. Getting all open algo orders...")
    get_all_open_algo_orders(symbol)

    # Step 4: Cancel the order (optional - comment out if you want to keep the order)
    print("\n4. Cancelling order...")
    cancel_algo_order(symbol, algo_id)

    print("\n" + "=" * 60)
    print("Example completed!")
    print("=" * 60)


if __name__ == "__main__":
    # Before running:
    # 1. Set your api_key and secret above
    # 2. Make sure you have an open LONG position on BTCUSDT (or adjust the symbol)
    # 3. Adjust qty and stop_price according to your needs
    # 4. Set testnet=False for live trading (BE CAREFUL!)

    # Uncomment this to change position mode (requires NO open positions/orders):
    # change_position_mode(dual_side_position=False)  # False = One-way Mode, True = Hedge Mode

    main()```

pcriadoperez avatar Dec 13 '25 19:12 pcriadoperez

thanks,I find the reason, the binance desk software have to update, or the algo_order will not show otherwise, this can be closed.

okluoquan avatar Dec 16 '25 05:12 okluoquan

@okluoquan thanks for the feedback!

carlosmiei avatar Dec 16 '25 10:12 carlosmiei