import model model.connect() model.cursor.execute(''' SELECT sell_order.stop_loss, buy_order.stop_loss FROM orders buy_order, orders sell_order, ownership buyer, ownership seller WHERE buy_order.buy AND NOT sell_order.buy AND buyer.rowid = buy_order.ownership_id AND seller.rowid = sell_order.ownership_id AND buyer.ownable_id = ? AND seller.ownable_id = ? AND sell_order."limit" <= buy_order."limit" ORDER BY CASE WHEN sell_order."limit" IS NULL THEN 0 ELSE 1 END ASC, CASE WHEN buy_order."limit" IS NULL THEN 0 ELSE 1 END ASC, buy_order."limit" DESC, sell_order."limit" ASC, buy_order.ordered_amount - buy_order.executed_amount DESC, sell_order.ordered_amount - sell_order.executed_amount DESC LIMIT 1 ''', (3, 3,)) print(model.cursor.fetchone())