How do i close a trade after say 5 days? i cant seem to figure out the documentation
QUANTCONNECT COMMUNITY
How do i close a trade after say 5 days? i cant seem to figure out the documentation
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Jing Wu
You could use a variable to record the time when you place the order and then do the subtraction. For example
if not self.Portfolio.Invested: self.current = self.Time self.SetHoldings("SPY", 1) if (self.Time - self.current).days == 5: self.Liquidate()
If the resolution is not daily, you might need to use the exact minite and/or second to decide the closing time.
Edvinas Jablonskis
This throws the following error: 'BasicTemplateAlgorithm' object has no attribute 'current'
Jing Wu
You need to initialize the "current" in Initialize(self) method like self.current = None. I was trying to show the idea with a piece of code, you could set your own variable name.
Edvinas Jablonskis
I have done the following:
class BasicTemplateAlgorithm(QCAlgorithm): def Initialize(self): self.current = None self.SetStartDate(2015,10,07) #Set Start Date self.SetEndDate(2016,10,11) #Set End Date self.SetCash(100000) #Set Strategy Cash self.AddForex("EURUSD", Resolution.Daily)
you can see i let self.current = None
The following is my loop for executing trades
if c > upper and o > upper and price > hourhalf: if not self.Portfolio.Invested: self.current = self.Time self.Buy("EURUSD", 1000) if (self.Time - self.current).days == 5: self.Liquidate("EURUSD")
It isnt liquidating any trades
Andrea Ardemagni
Hi Edvinas, I'm a beginner with this platform but if you try this code using Jing's suggestion, it works on my end:
import clr
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d
### <summary>
### In this example we look at the canonical 15/30 day moving average cross. This algorithm
### will go long when the 15 crosses above the 30 and will liquidate when the 15 crosses
### back below the 30.
### however if the position was open for 5 days, we close the position
class MovingAverageCrossAlgorithm(QCAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.SetStartDate(2001, 01, 01) #Set Start Date
self.SetEndDate(2018, 02, 8) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.AddEquity("SPY")
# create a 15 day exponential moving average
self.fast = self.EMA("SPY", 15, Resolution.Daily);
# create a 30 day exponential moving average
self.slow = self.EMA("SPY", 30, Resolution.Daily);
self.previous = None
self.current = None
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# a couple things to notice in this method:
# 1. We never need to 'update' our indicators with the data, the engine takes care of this for us
# 2. We can use indicators directly in math expressions
# 3. We can easily plot many indicators at the same time
# wait for our slow ema to fully initialize
if not self.slow.IsReady:
return
# only once per day
if self.previous is not None and self.previous.date() == self.Time.date():
return
# define a small tolerance on our checks to avoid bouncing
tolerance = 0.00015;
holdings = self.Portfolio["SPY"].Quantity
# we only want to go long if we're currently short or flat
if holdings <= 0:
# if the fast is greater than the slow, we'll go long
if self.fast.Current.Value > self.slow.Current.Value * d.Decimal(1 + tolerance):
self.Log("BUY >> {0}".format(self.Securities["SPY"].Price))
self.SetHoldings("SPY", 1.0)
self.current = self.Time
# we only want to liquidate if we're currently long
# if the fast is less than the slow we'll liquidate our long
if holdings > 0 and self.fast.Current.Value < self.slow.Current.Value:
self.Log("SELL >> {0}".format(self.Securities["SPY"].Price))
self.Liquidate("SPY")
if holdings > 0 and (self.Time - self.current).days == 5:
self.log("liquiditing position after 5 days pos.open. Curr Px:{0}".format(self.Securities["SPY"].Price))
self.Liquidate()
self.previous = self.Time
Edvinas Jablonskis
Hello Andrea, I have tried your code and i believe that it dosent work. You have 2 loops with a liquidating function and of course the first loop is liquidating and the one of intrest to me (the bottom one) is left redundant. If i delete the first loop (the one i posted below) and use the second loop then there are no trades being liquidated
# we only want to liquidate if we're currently long # if the fast is less than the slow we'll liquidate our long if holdings > 0 and self.fast.Current.Value < self.slow.Current.Value: self.Log("SELL >> {0}".format(self.Securities["SPY"].Price)) self.Liquidate("SPY")
Recordatio
I want to do this as well but the examples above doesn't liquidate. I have attached a backtest.
Recordatio
Solved it with another counter in my code.
Edvinas Jablonskis
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!