I have the following code to detect stock trades by counting orders:
import json
orders = '[{"side": "SELL", "executedQty": "0.046"}, {"side": "SELL", "executedQty": "0.041"}, {"side": "SELL", "executedQty": "0.056"}, {"side": "SELL", "executedQty": "0.140"}, {"side": "BUY", "executedQty": "0.283"}]'
orders = json.loads(orders)
cur_qty = 0
raw_trades = []
trade = []
trade_side = None
for order in orders:
if trade_side is None:
trade_side = order['side']
numbers_after_decimal = len(order['executedQty'].split('.')[-1])
order_qty = float(order['executedQty'])
order_qty = round(order_qty, numbers_after_decimal)
if trade_side == order['side']:
cur_qty += order_qty
else:
cur_qty -= order_qty
trade.append(order)
if cur_qty == 0:
raw_trades.append(trade)
trade_side = None
trade = []
in this example, orders has only 1 trade (we sold 0.046 + 0.041 + 0.056 + 0.140 = 0.283 (entry) and we bought 0.283 (exit))
The problem is, that when running this code, for some reason, when in the for loop and order is {"side": "SELL", "executedQty": "0.140"}
and cur_qty = 0.143
, when I add them the result is 0.28300000000000003
.
This messes up the whole count because I search for cur_qty == 0
to know that the trade is over (I sold everything I bought or vise versa).
Tried to round the float to its string number of decimal places, but it keeps happening.
Any Idea how to solve this, rounding the number didn't help