1

Struggelig a bit with my trading algo. It seems that the orders cant finish before the next onBars() is called, and the quantities become a mess. Im using the enterLongLimit() to enter a trade, which calls onEnterOk() when it finishes - but im using limitOrder to exit parts of a position based on some technical indicator, and that doesnt seem to call onExitOk().

def onExitOk(self, position):
    print("Exit ok", position.getExitOrder().getExecutionInfo().getDateTime())

def onEnterOk(self, position):
    print("Enter ok", position.getEntryOrder().getExecutionInfo())

def _closePosition(self, price, qty, reason, date):
    print("Closing position with price", price, "and closing qty", qty)
    brk = self.getBroker()
    shares = brk.getShares(self.instrument) * qty
    print("Cash now before sell: ", brk.getCash(self.instrument))
    self.info("Sell BTC %s at %s because %s on %s " % (shares, price, reason, date))
    self.position = self.limitOrder(self.instrument, price, shares*-1)
    print("Cash now after sell: ", brk.getCash(self.instrument))

Execution:

Closing position with price 746.3 and closing qty 0.5


Cash now before sell: 17.423283999999967


Cash now after sell: 17.423283999999967

The cash before and after the limitOrder is the same, so i have to wait for the event to come in. Ideas?

shakalakka
  • 105
  • 1
  • 1
  • 8
  • Do you get all the printouts from onEnterOk and onExitOk events? I cannot get those to work for some reason even though my strategy executes 2.5k trades in backtesting through stop and limit orders - whatever code I put into those events does not get executed. – mac13k Nov 28 '21 at 10:34
  • It seems like it depends on which method is used to open a position - for some reason stop, limit and stop-limit orders to not trigger onEnter/onExit events, but enterLong or enterShort do. – mac13k Nov 28 '21 at 11:02

1 Answers1

0

I had a similar problem and then after some digging I found that onEnter and onExit events are only triggered when a position is opened using one of the enterLong or enterShort methods. Trades executed with stop, limit or stop-limit orders do not trigger onEnter or onExit events which is a real shame.

This what the comments in the source code say, ie.:

def onEnterOk(self, position):
    """Override (optional) to get notified when the order submitted to enter a position was filled. The default implementation is empty.
    :param position: A position returned by any of the enterLongXXX or enterShortXXX methods.
    :type position: :class:`pyalgotrade.strategy.position.Position`.
    """
    pass

See the strategy class code.

Your limit order should still work as expected even though you do not get the notification.

mac13k
  • 2,423
  • 23
  • 34