Hello,
In my code I want to set these rules:
- if today's price is higher than yesterday, open 2 short positions. One position without and one with trailing SL.
- After 4 days, close only the 1st position
I implemented these rules but I receive this error:
Trying to dynamically access a method that does not exist throws a TypeError exception. To prevent the exception, ensure each parameter type matches those required by the 'QuantConnect.Orders.OrderTicket'>) method. Please checkout the API documentation.
at OnData
self.Liquidate(self.ticketPair1)
at Python.Runtime.PythonException.ThrowLastAsClrException()
at Python.Runtime.PyObject.Invoke(PyTuple args in main.py: line 45
The code looks as follows:
# region imports
from AlgorithmImports import *
# endregion
class Strategy(QCAlgorithm):
def Initialize(self):
self.Pair_1 = "EURUSD"
self.holdingDays = 1
self.SetStartDate (2010, 1, 1)
self.SetEndDate(2022,7,1)
self.SetCash(10000)
self.SetBrokerageModel(BrokerageName.OandaBrokerage)
self.EURSEK = self.AddForex(self.Pair_1, Resolution.Daily, Market.Oanda)
self.symbols = [self.Pair_1]
self.prevPrices = { symbol : RollingWindow[QuoteBar](7) for symbol in self.symbols }
self.ticketPair1 = None
def OnData(self,data):
self.quantity_1 = self.CalculateOrderQuantity(self.Pair_1, 1)
for symbol in self.symbols:
if data.ContainsKey(symbol):
self.prevPrices[symbol].Add( data[symbol] )
if not all([ window.IsReady for window in self.prevPrices.values() ]):
return
Pair1_window = self.prevPrices[self.Pair_1]
Pair1_1D = Pair1_window[1].Close
Pair1_0D = Pair1_window[0].Close
if self.ticketPair1 is not None and self.UtcTime < self.ticketPair1.Time + timedelta(days=(self.holdingDays)):
return
if self.ticketPair1 is None and self.Securities[self.Pair_1].Exchange.ExchangeOpen is True and Pair1_0D > Pair1_1D :
self.ticketPair1 = self.MarketOrder(self.Pair_1, 1000 )
stop_price = self.ticketPair1.AverageFillPrice * 0.99
self.stop_loss_ticket = self.StopMarketOrder(self.Pair_1, -self.quantity_1, stop_price)
self.price = self.ticketPair1.AverageFillPrice
if self.ticketPair1 is not None and self.Securities[self.Pair_1].Exchange.ExchangeOpen is True and self.UtcTime >= self.ticketPair1.Time + timedelta(days = 4):
self.Liquidate(self.ticketPair1)
self.ticketPair1 = None
Do you know what could be the reason of it ? If I delete the last 3 rows, so orders will never be closed, the strategy opens trades correctly, so there is not problem with implementing orders.
I would appreciate any help/tips :)
Nico Xenox
Hey sebul
I didnt found anything to close orders by the orderId but maybe this method solves your problem.
Yuri Lopukhov
sebul self.ticketPair1 in your code will contain OrderTicket, not Symbol, try changing to self.Liquidate(self.ticketPair1.Symbol).
Sebul
Thank you for you advices Nico Xenox and Yuri Lopukhov !
While continuing working on my code, I am stuck with an error, which I can't solve. I am sure it's a simple mistake in my code, but despite spending a decent amount of time on this, I cant find the solution. Could you please provide me with some guidance on how to approach this issue? I want to implement a Trailing SL Orders in my strategy, and although I followed carefully tutorials about this topic, an error still pops up.
and here is my code:
Nico Xenox
sebul
You're updating a order that does not exist. First you have to check if the order exists:
I changed this:
To this:
Sebul
Nico Xenox
Thank you very much!! I have one last question which I would like to ask you. Although the trailing order is implemented correctly, the strategy doesn't close the order when it's supposed to. Whenever the price of a security increases, SL should be shifted accordingly. By printing the updated stopPrice every time it shifts, from what I see it works how it's supposed to be, but inconsistently, with some visible gaps in dates. Despite that, no positions with trailing SL are closed.
Additionally, as I mentioned before, there are some strange gaps in printing shifter SL in Logs (screenshots attached below). SL is shifter a few days, then it stays unchanged for a few monts. Do you know what could be causing these two strange errors?
Nico Xenox
Hey sebul
I'm not sure if I understand correctly but I guess your problem is here:
You enter this just if you have a new high in close, meaning that it will just update the orders when there is a new High.
I made a Plot to visualize this problem. As you can see on PAIR1 the red visualises the high and the green your trailing stop. They just get updated if there's a new high otherwise the stay the same.
You have to change the ultimate high to a daily high or something similar that works with your strategy.
Hope it helps;)
Sebul
Nico Xenox
Oh yeah it makes sense now, thank you!
Sebul
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!