Skip to content

How to close a specific trade #222

Description

@Priyedev

I am new to backtesting framework and recently learned python so need some help to implement a strategy, I want to implement a strategy which opens long or short trades without any stop loss and take profit level. I get that I can do that using self.buy() and self.sell() methods of strategy class as in examples but I am not sure how I close a trade as there's no self.close(). My strategy may have multiple long and short trades open at same time and each trade needs to be explicitly closed by strategy based on certain criteria (not by stop loss or take profit). I get that I need to have exclusive_orders=False. Do I need to loop through all open positions or trades and then call close on Position or Trade, if so how do I uniquely identify a Position or Trade? would be helpful if you can point me to or provide a related example snippet.
Thanks

Activity

  1. kernc commented on Jan 7, 2021

    @kernc
    Owner

    See #43.

    As some general guidance, first read through the tutorials, then go over the available API, so you see what's possible.

    Other than that, use the search, use discussions, find Python help on StackOverflow.

    Thanks!

  2. changed the title [-]Question: How to explicitly close a trade from a strategy [/-] [+]How to close a trade[/+] on Jan 7, 2021
  3. kernc commented on Jan 7, 2021

    @kernc
    Owner

    Do I need to loop through all open positions or trades and then call close on Position or Trade, if so how do I uniquely identify a Position or Trade?

    Yes. You can identify them by saving them in a well-known place or by any Python object properties you attach to them. 🤷‍♂️

    self.buy(...)
    last_placed_order = self.orders[-1]

    To learn what Trade this last_placed_order resulted in is a work in progress, see #197, #200.

  4. changed the title [-]How to close a trade[/-] [+]How to close a specific trade[/+] on Jan 7, 2021
  5. Priyedev commented on Jan 8, 2021

    @Priyedev
    Author

    Thanks @kernc , really appreciate your prompt response. #200 is the one I need for tagging, will keep an eye on it when its merged

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionNot a bug, but a FAQ entry

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions