Back

Having trouble with stop-loss and take profit when "going short"

Hi!

So, I'm having trouble with shorting a Forex pair in my algorithm. It seems to immediately sell off the pair regardless of how I set my stop loss value. I've tried using LimitOrder, StopLimitOrder and StopMarketOrder and none return the desired effect. I gave Googling and poring over the documentation my best effort. Has anyone worked around this yet/got it right the first time? See below for my latest attempt:

 

import numpy as np
from decimal import Decimal

class VerticalResistanceFlange(QCAlgorithm):

stopMarketTicket = None
limitTicket = None

def Initialize(self):

self.SetStartDate(2018, 3, 23)
self.SetEndDate(2018, 7, 4)
self.SetCash(100000)


self.uj = self.AddForex("USDJPY", Resolution.Minute, Market.Oanda)
self.usdjpy = self.AddForex("USDJPY").Symbol

self.SetBrokerageModel(BrokerageName.OandaBrokerage)

self.SetWarmUp(240, Resolution.Minute)

self.rsi = self.RSI("USDJPY", 10, MovingAverageType.Simple, Resolution.Minute)
self.ich = self.ICHIMOKU("USDJPY", 9, 26, 52, 52, 26, 26, Resolution.Minute)
self.RegisterIndicator("USDJPY", self.rsi, Resolution.Minute)
self.RegisterIndicator("USDJPY", self.ich, Resolution.Minute)

self.UniverseSettings.Resolution = Resolution.Minute

def OnData(self, data):

if self.IsWarmingUp:
return

for key in data.Keys:
self.Log(str(key.Value) + ": " + str(data.Time) + " > " + str(data[key].Value))


#Set individual variables for ICHIMOKU indicator values (Tenkan, Kijun, Senkou) and RSI
ichT = self.ich.Tenkan.Current.Value
ichK = self.ich.Kijun.Current.Value
ichSA = self.ich.SenkouA.Current.Value
ichSB = self.ich.SenkouB.Current.Value

rsi_value = self.rsi.Current.Value

if not self.Portfolio.Invested:
##If "Tenkan" lines meet and RSI is between 15 and 45, short
if round(ichT, 3) == round(ichK, 3) and rsi_value < 45.0 and rsi_value > 15.0:
self.Debug("Tenkan Kijun intersection. Short.")
self.Debug("Tenkan = " + str(ichT) + " Kijun = " + str(ichK))
self.Debug("RSI Value: " + str(rsi_value))
#Set amount of portfolio to venture
self.amount = self.Portfolio.Cash * 0.04
#Order pair, set stops, print values
self.marketTicket = self.MarketOrder("USDJPY", -self.amount)
self.price = data[self.usdjpy].Close
self.Debug(str(self.price))
self.stopPrice = self.price * 1.04
self.limitPrice = self.price * 0.994
self.Debug("Limit price, short: " + str(self.limitPrice))
self.stopMarketTicket = self.StopMarketOrder("USDJPY", self.amount, self.stopPrice)
self.limitTicket = self.StopMarketOrder("USDJPY", self.amount, self.limitPrice)
self.Debug("Short order triggered per Ichimoku! For " + str(self.price))
##If "Tenkan" lines meet and RSI is between 30 and 80, long
elif round(ichT, 3) == round(ichK, 3) and rsi_value < 80.0 and rsi_value > 30.0:
self.Debug("Tenkan Kijun intersection. Long.")
self.Debug("Tenkan = " + str(ichT) + " Kijun = " + str(ichK))
self.Debug("RSI Value: " + str(rsi_value))
self.amount = self.Portfolio.Cash * 0.04
self.marketTicket = self.MarketOrder("USDJPY", self.amount)
self.price = data[self.usdjpy].Close
self.Debug(str(self.price))
self.stopPrice = self.price * 0.996
self.limitPrice = self.price * 1.006
self.Debug("Limit price, long: " + str(self.limitPrice))
self.stopMarketTicket = self.StopMarketOrder("USDJPY", -self.amount, self.stopPrice)
self.limitTicket = self.LimitOrder("USDJPY", -self.amount, self.limitPrice)

self.Debug("Long order triggered per Ichimoku! For " + str(self.price))

def OnOrderEvent(self, orderEvent):
#"One cancels the other" implementation for take profit / stop loss
if self.IsWarmingUp:
return
if self.stopMarketTicket is not None and self.stopMarketTicket.Status == OrderStatus.Filled:
self.Debug("Stop Market hit! For " + str(self.Securities["USDJPY"].Price))
self.limitTicket.Cancel()
self.stopMarketTicket = None
if self.limitTicket is not None and self.limitTicket.Status == OrderStatus.Filled:
self.Debug("Take Profit hit! For " + str(self.Securities["USDJPY"].Price))
self.stopMarketTicket.Cancel()
self.limitTIcket = None

 

Update Backtest








0

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.


Hi Connor,

The time displayed in the Orders tab in backtests is the time the order is submitted, not filled. I've attached a backtest that logs more information regarding the order placement, and you can view from the logs that the limit orders are being placed at a time when the limit price is hit, not at the exact same time as the market order.

0

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.


Update Backtest





0

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.


Loading...

This discussion is closed