Confused - How to close a long position vs. selling



  • My algo has been shorting like crazy, and i realize I didn't quite understand how to close a position. From the tutorial, I got the sense that calling self.sell() somehow knew the last position created by self.buy() was what I wanted to sell.

    Take a simple strategy like SMA cross over for example. If I wanted to sell when the close crossed SMA line when it crossed up, and close the position when it crossed down.. would this be the correct way to it?

    class St(bt.Strategy):
    params = (
    )
    
    def __init__(self):
    	self.sma = bt.ind.MovingAverageSimple()
    	self.sig = bt.ind.CrossOver(self.datas[0].close,self.sma)
    	
    
    def next(self):
    	buysig = (self.sig == 1.0)
    	sellsig = (self.sig == -1.0)
    
    	size = self.position.size
    	
    	if(not size):
    		if(buysig):
    			self.buy()
    		elif (sellsig):
    			self.sell()
    	elif (size > 0):
    		if(not buysig):
    			self.close()
    	elif (not sellsig): #(size < 0 and buysig):
    		self.close()

  • administrators

    • buy is for buying
    • sell is for selling

    Both can obviously close an existing position if they are opposing each other. But if any of the above had intelligence to undo what the other do, how would you reverse a position?

    • close is for closing a position and will take into account the existing position.

    They are documented in Docs - Strategy

    You may also close a position with order_target_xxx by setting the target to 0. See Docs - Target Orders

    And you can even close positions with sell if your position sizing is controlled with a Sizer or convert the same code to be a position reverser. See Docs - Sizers - Smart Staking

    The code will probably close positions in many cases, where there isn't simply a signal (neither buy nor sell)


Log in to reply
 

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.