Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Confused - How to close a long position vs. selling

    Indicators/Strategies/Analyzers
    2
    2
    4576
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • T
      Taewoo Kim last edited by

      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()
      
      1 Reply Last reply Reply Quote 0
      • B
        backtrader administrators last edited by

        • 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)

        1 Reply Last reply Reply Quote 0
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors