blankly-finance / blankly

🚀 💸 Easily build, backtest and deploy your algo in just a few lines of code. Trade stocks, cryptos, and forex across exchanges w/ one package.
https://package.blankly.finance
GNU Lesser General Public License v3.0
2.03k stars 261 forks source link

Closing orders by id #259

Open SamTov opened 1 month ago

SamTov commented 1 month ago

I want to be able to close an order by an id, something like this:

def close_position_by_id(symbol, order_id, state):
    print(f"Before: {state.interface.paper_trade_orders}")
    print(order_id)
    print(symbol)
    state.interface.cancel_order(symbol, str(order_id))
    print(f"After: {state.interface.paper_trade_orders}")

Where before should be my standard list of open orders and after should be empty if I only have one active order. While this exists for pending orders, I don't see how I can deliberately close a done order in Blankly. I can open a sell position and by default, reduce the amount of money I have in an instrument, but those two things aren't the same. One can think of opening a buy and sell position simultaneously. Not saying it is a great idea, but it is surely something I should be able to do in a backtesting framework. Is this already possible within blankly?

EmersonDove commented 1 month ago

Hey there, we're trying to mimic live trading as much as possible in the framework. On many exchanges recent finished orders come back as "done" so when you do a get all orders you'll see them sitting in the array.

You may also want to use get_orders() in the API over the interface attribute because I think there's a bit of preprocessing that might help filter in the function call.

SamTov commented 1 month ago

Hi, thanks for the reply. My issue was that there is (as far as I could see), no method for closing done orders. If i put in a buy order it will come back done and I own the instrument. Then I want to make a sell order to also have short position on the same instrument. Now I want to close the buy position but leave the short open or some combination. I don't see how I can do that from the blankly API. The close method was only applicable for pending orders and not for done orders. Maybe am just missing something simple, but I don't see how one can do this.