|
I would like to sell a long position at a set limit, instead of buying a short position with sell. Can anyone help? after the self.sell() and when reaching the next next() the self.position.is_short changes to True, which is not what I want. I would just like to buy and sell long positions. |
Replies: 1 comment
|
The usual cause here is that the strategy submits a new If this is just a take-profit exit for the long entry, the cleanest approach is to attach it to the entry order instead of manually placing a separate sell order: if not self.position:
self.buy(tp=limit)That creates a contingent take-profit order tied to the trade. When the TP is hit, it closes the long trade instead of acting like an independent short-entry idea. If you really want to manage the limit exit manually, keep a reference to the pending exit order and do not create another one while it is still waiting: class MyStrategy(Strategy):
exit_order = None
def next(self):
if not self.position:
self.exit_order = None
self.buy()
return
if self.position.is_long:
# If the order filled/cancelled, it will no longer be in self.orders.
if self.exit_order is not None and self.exit_order not in self.orders:
self.exit_order = None
if self.exit_order is None:
self.exit_order = self.sell(
size=abs(self.position.size),
limit=limit,
)Two extra safeguards:
For most long-only strategies, I would prefer the first version with |
The usual cause here is that the strategy submits a new
sell(limit=...)order on every bar while the long position is still open. If several of those pending sell-limit orders later fill, they can close the long trade and then continue into a short position.If this is just a take-profit exit for the long entry, the cleanest approach is to attach it to the entry order instead of manually placing a separate sell order:
That creates a contingent take-profit order tied to the trade. When the TP is hit, it closes the long trade instead of acting like an independent short-entry idea.
If you really want to manage the limit exit manually, keep a refer…