Binance API sell only the profit & all the position

Viewed 7117

I'm trying to understand what's the logic to implement when selling only the profit or all the position of a given order.

I have already implemented the BUY operation. So, let's say the user wants to buy 100$ worth of BTC at the current BTC price, I do as the follow:

$params = 
[
    'symbol' => 'BTCUSDT', 
    'side' => 'BUY', 
    'type' => 'MARKET', 
    'quoteOrderQty' => 100, 
    'timestamp' => $timestamp
];

$binance->buy($params);

https://binance-docs.github.io/apidocs/spot/en/#new-order-trade

I save both OrderId & clientOrderId response from Binance. A week later I'd like to sell the order position and to have the following available options:

  1. Sell only the profit of this order & (maybe) close
  2. Sell all my position (no matter if with profit or not) of this order & (maybe) close

Question: How can I accomplish both situations?

1 Answers
  1. You need to wait for when the order will be in FILLED status. For MARKET orders it usually happens immediately but to be sure you need to check the status in response and if it's NEW or PARTIALLY_FILLED make this call GET /api/v3/order.
  2. Ok you FILLED your order. In this step, you need to save executedQty and cummulativeQuoteQty fields. First is how many BTC did you buy, second how many USDT did you spend.
  3. I'm not sure what do you exactly mean under "sell only the profit", but lets me guess. You need to take lastPrice of the pair GET /api/v3/ticker/price then calculate

$profit = $currentPrice * $exectuedQty - $cummulativeQuoteQty. It will be your profit in USDT. For partially sell you need to make order

    'symbol' => 'BTCUSDT', 
    'side' => 'SELL', 
    'type' => 'MARKET', 
    'quoteOrderQty' => $profit, 
    'timestamp' => $timestamp

Keep in mind, quoteOrderQty can't be less than $10

  1. And this is the order for your full close
    'symbol' => 'BTCUSDT', 
    'side' => 'SELL', 
    'type' => 'MARKET', 
    'quantity' => $exectuedQty, 
    'timestamp' => $timestamp
Related