ByBit API: is there a way to place Take Profit & Stop Loss orders after a opening a position?

Viewed 3973

From the official docs I found this:

import bybit
client = bybit.bybit(test=True, api_key="api_key", api_secret="api_secret")
print(client.LinearOrder.LinearOrder_new(
side="Sell",
symbol="BTCUSDT",
order_type="Limit",
qty=0.22,
price=10000,
time_in_force="GoodTillCancel",
reduce_only=False, 
close_on_trigger=False
).result())

Additional parameters take_profit & stop_loss may also be sent. The TP&SL then get placed along with the order.

I'm wondering if there is a way to place TP&SL orders after an order is placed. There are no examples in the official docs, and I do not understand any instructions written for those orders in there either.

Thank you in advance

2 Answers

Yes, it is possible to attach these orders after entering a position. In the docs they reference set stop, and this is also included in the test.py doc page within the Bybit python install

here is the link to the docs

Bybit Set Stop

Here is what a stop and TP would look like for a LONG position. Please note that for a long we set what our current pos is for the side argument. (BUY)

# Stop Loss
print(client.LinearPositions.LinearPositions_tradingStop(
    symbol="BTCUSDT", 
    side="Buy", 
    stop_loss=41000).result())

# Take profit
print(client.LinearPositions.LinearPositions_tradingStop(
    symbol="BTCUSDT", 
    side="Buy", 
    take_profit=49000).result())

Additional note: TP orders are conditional orders, meaning they are sent to the order book once triggered, which results in a market order. If you already know your target level, a limit order may be more suitable. This will go to your active orders, which you will have to cancel. We use a sell argument for this one:

# Limit order
print(client.LinearOrder.LinearOrder_new(
    side="Sell",
    symbol="BTCUSDT",
    order_type="Limit",
    qty=0.001,
    price=49000,
    time_in_force="GoodTillCancel",
    reduce_only=True, 
    close_on_trigger=False).result())

Cheers my friend and good luck with your coding and trading!

Another way to is to listen to websocket data. What I do is I subscribe to "execution" topic. This way, every time your order gets executed you receive an event with all the info about the trade. Then, you can have a callback function that places a trade for you.

Here's the link to the api: https://bybit-exchange.github.io/docs/inverse/#t-websocketexecution

Here's how to subscribe:

enter image description here

Here's the sample response:

enter image description here

Related