public void UpdatesAfterCorrectPeriodElapses() { const int periods = 3; var periodSpan = Time.OneMinute; var reference = new DateTime(2016, 04, 06, 12, 0, 0); var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork); var timeKeeper = new TimeKeeper(referenceUtc); var config = new SubscriptionDataConfig(typeof (TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false); var security = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), config, new Cash("USD", 0, 0), SymbolProperties.GetDefault("USD")); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var model = new RelativeStandardDeviationVolatilityModel(periodSpan, periods); security.VolatilityModel = model; var first = new IndicatorDataPoint(reference, 1); security.SetMarketPrice(first); Assert.AreEqual(0m, model.Volatility); const decimal value = 0.471404520791032M; // std of 1,2 is ~0.707 over a mean of 1.5 var second = new IndicatorDataPoint(reference.AddMinutes(1), 2); security.SetMarketPrice(second); Assert.AreEqual(value, model.Volatility); // update should not be applied since not enough time has passed var third = new IndicatorDataPoint(reference.AddMinutes(1.01), 1000); security.SetMarketPrice(third); Assert.AreEqual(value, model.Volatility); var fourth = new IndicatorDataPoint(reference.AddMinutes(2), 3m); security.SetMarketPrice(fourth); Assert.AreEqual(0.5m, model.Volatility); }
public void PipesDataUsingOfFromFirstToSecond() { var first = new SimpleMovingAverage(2); var second = new Delay(1); // this is a configuration step, but returns the reference to the second for method chaining second.Of(first); var data1 = new IndicatorDataPoint(DateTime.UtcNow, 1m); var data2 = new IndicatorDataPoint(DateTime.UtcNow, 2m); var data3 = new IndicatorDataPoint(DateTime.UtcNow, 3m); var data4 = new IndicatorDataPoint(DateTime.UtcNow, 4m); // sma has one item first.Update(data1); Assert.IsFalse(first.IsReady); Assert.AreEqual(0m, second.Current.Value); // sma is ready, delay will repeat this value first.Update(data2); Assert.IsTrue(first.IsReady); Assert.IsFalse(second.IsReady); Assert.AreEqual(1.5m, second.Current.Value); // delay is ready, and repeats its first input first.Update(data3); Assert.IsTrue(second.IsReady); Assert.AreEqual(1.5m, second.Current.Value); // now getting the delayed data first.Update(data4); Assert.AreEqual(2.5m, second.Current.Value); }
private static void TestPipesData(SequentialIndicator<IndicatorDataPoint> sequential) { var data1 = new IndicatorDataPoint(DateTime.UtcNow, 1m); var data2 = new IndicatorDataPoint(DateTime.UtcNow, 2m); var data3 = new IndicatorDataPoint(DateTime.UtcNow, 3m); var data4 = new IndicatorDataPoint(DateTime.UtcNow, 4m); var data5 = new IndicatorDataPoint(DateTime.UtcNow, 5m); // sma has one item sequential.Update(data1); Assert.IsFalse(sequential.IsReady); Assert.AreEqual(0m, sequential.Current.Value); // sma has two items sequential.Update(data2); Assert.IsFalse(sequential.IsReady); Assert.AreEqual(0m, sequential.Current.Value); // sma is ready, delay will repeat this value sequential.Update(data3); Assert.IsFalse(sequential.IsReady); Assert.AreEqual(2.5m, sequential.Current.Value); // delay is ready, and repeats its first input sequential.Update(data4); Assert.IsTrue(sequential.IsReady); Assert.AreEqual(2.5m, sequential.Current.Value); // now getting the delayed data sequential.Update(data5); Assert.IsTrue(sequential.IsReady); Assert.AreEqual(3.5m, sequential.Current.Value); }
/// <summary> /// Computes the next value of the following sub-indicators from the given state: /// StandardDeviation, MiddleBand, UpperBand, LowerBand /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>The input is returned unmodified.</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { StandardDeviation.Update(input); MiddleBand.Update(input); UpperBand.Update(input); LowerBand.Update(input); return input; }
public void AccessesBaseBySymbol() { IndicatorDataPoint tick = new IndicatorDataPoint(Symbols.SPY, DateTime.Now, 1); Slice slice = new Slice(DateTime.Now, new[] { tick }); IndicatorDataPoint data = slice[tick.Symbol]; Assert.AreEqual(tick, data); }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { // our first data point just return identity if (Samples == 1) { return input; } return input*_k + Current*(1 - _k); }
/// <summary> /// Computes the next value for this indicator from the given state. /// </summary> /// <param name="window">The window of data held in this indicator</param> /// <param name="input">The input value to this indicator on this time step</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IReadOnlyWindow<IndicatorDataPoint> window, IndicatorDataPoint input) { Average.Update(input); var absoluteChange = base.ComputeNextValue(window, input); if (Average == 0m) { return 0m; } return absoluteChange/Average; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { Fast.Update(input); Slow.Update(input); var macd = Fast - Slow; if (Fast.IsReady && Slow.IsReady) { Signal.Update(input.Time, macd); } return macd; }
public void PassesOnDuplicateTimes() { var target = new TestIndicator(); var time = DateTime.UtcNow; const decimal value1 = 1m; var data = new IndicatorDataPoint(time, value1); target.Update(data); Assert.AreEqual(value1, target.Current.Value); // this won't update because we told it to ignore duplicate // data based on time target.Update(data); Assert.AreEqual(value1, target.Current.Value); }
public void DelayOneRepeatsFirstInputValue() { var delay = new Delay(1); var data = new IndicatorDataPoint(DateTime.UtcNow, 1m); delay.Update(data); Assert.AreEqual(1m, delay.Current.Value); data = new IndicatorDataPoint(DateTime.UtcNow.AddSeconds(1), 2m); delay.Update(data); Assert.AreEqual(1m, delay.Current.Value); data = new IndicatorDataPoint(DateTime.UtcNow.AddSeconds(1), 2m); delay.Update(data); Assert.AreEqual(2m, delay.Current.Value); }
public void PassesOnDuplicateTimes() { var target = new TestIndicator(); var time = DateTime.UtcNow; const decimal value1 = 1m; var data = new IndicatorDataPoint(time, TimeZone.Utc, value1); target.Update(data); Assert.Equal(value1, target.Current.Price); // this won't update because we told it to ignore duplicate // data based on time target.Update(data); Assert.Equal(value1, target.Current.Price); }
public void DelayOneRepeatsFirstInputValue() { var delay = new Delay(1); var data = new IndicatorDataPoint(DateTime.UtcNow, 1m); delay.Update(data); Assert.AreEqual(1m, delay.Current.Value); data = new IndicatorDataPoint(DateTime.UtcNow.AddSeconds(1), 2m); delay.Update(data); Assert.AreEqual(1m, delay.Current.Value); data = new IndicatorDataPoint(DateTime.UtcNow.AddSeconds(1), 2m); delay.Update(data); Assert.AreEqual(2m, delay.Current.Value); }
public void UpdatesAfterCorrectDailyPeriodElapses() { const int periods = 3; var reference = new DateTime(2016, 04, 06, 12, 0, 0); var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork); var timeKeeper = new TimeKeeper(referenceUtc); var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false); var security = new Security( SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), config, new Cash(Currencies.USD, 0, 0), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var model = new StandardDeviationOfReturnsVolatilityModel(periods); security.VolatilityModel = model; var first = new IndicatorDataPoint(reference, 1); security.SetMarketPrice(first); Assert.AreEqual(0m, model.Volatility); var second = new IndicatorDataPoint(reference.AddDays(1), 2); security.SetMarketPrice(second); Assert.AreEqual(0, model.Volatility); // update should not be applied since not enough time has passed var third = new IndicatorDataPoint(reference.AddDays(1.01), 1000); security.SetMarketPrice(third); Assert.AreEqual(0, model.Volatility); var fourth = new IndicatorDataPoint(reference.AddDays(2), 3); security.SetMarketPrice(fourth); Assert.AreEqual(5.6124, (double)model.Volatility, 0.0001); }
public void DoesntUpdateOnZeroPrice() { const int periods = 3; var periodSpan = Time.OneMinute; var reference = new DateTime(2016, 04, 06, 12, 0, 0); var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork); var timeKeeper = new TimeKeeper(referenceUtc); var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false); var security = new Security( SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), config, new Cash("USD", 0, 0), SymbolProperties.GetDefault("USD"), ErrorCurrencyConverter.Instance ); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var model = new RelativeStandardDeviationVolatilityModel(periodSpan, periods); security.VolatilityModel = model; var first = new IndicatorDataPoint(reference, 1); security.SetMarketPrice(first); Assert.AreEqual(0m, model.Volatility); const decimal value = 0.471404520791032M; // std of 1,2 is ~0.707 over a mean of 1.5 var second = new IndicatorDataPoint(reference.AddMinutes(1), 2); security.SetMarketPrice(second); Assert.AreEqual(value, model.Volatility); var third = new IndicatorDataPoint(reference.AddMinutes(2), 3m); security.SetMarketPrice(third); Assert.AreEqual(0.5m, model.Volatility); // update should not be applied as price is 0 var forth = new IndicatorDataPoint(reference.AddMinutes(3), 0m); security.SetMarketPrice(forth); Assert.AreEqual(0.5m, model.Volatility); }
private void Price_Updated(object sender, IndicatorDataPoint updated) { if (IsReady) { if (updated.Value >= _upperBand.Current.Value) { SurvivalWindow.Add(1); } else if (updated.Value <= _lowerBand.Current.Value) { SurvivalWindow.Add(-1); } else { SurvivalWindow.Add(0); } } }
protected override decimal ComputeNextValue(IndicatorDataPoint input) { if (input.Price > _vamaHour && input.Price > _vamaW[0] && _residualSm > 0 && _residualHSm > 0 && _rsi > 40 && _prersi <40 && _sd> 0.005m) { Current = 1m; } else if (input.Price < _vamaHour && input.Price < _vamaW[0] && _residualSm < 0 && _residualHSm <0 && _rsi < 60 && _prersi > 60 && _sd> 0.005m) { Current = -1m; } else { Current = 0m; } return(Current); }
public void DoesntUpdateOnZeroPrice() { const int periods = 3; var periodSpan = Time.OneMinute; var reference = new DateTime(2016, 04, 06, 12, 0, 0); var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork); var timeKeeper = new TimeKeeper(referenceUtc); var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false); var security = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), config, new Cash("USD", 0, 0), SymbolProperties.GetDefault("USD")); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var model = new StandardDeviationOfReturnsVolatilityModel(periods); security.VolatilityModel = model; var first = new IndicatorDataPoint(reference, 1); security.SetMarketPrice(first); Assert.AreEqual(0m, model.Volatility); var second = new IndicatorDataPoint(reference.AddDays(1), 2); security.SetMarketPrice(second); Assert.AreEqual(0, model.Volatility); // update should not be applied since not enough time has passed var third = new IndicatorDataPoint(reference.AddDays(1.01), 1000); security.SetMarketPrice(third); Assert.AreEqual(0, model.Volatility); var fourth = new IndicatorDataPoint(reference.AddDays(2), 3); security.SetMarketPrice(fourth); Assert.AreEqual(5.6124, (double)model.Volatility, 0.0001); // update should not be applied as price is 0 var fifth = new IndicatorDataPoint(reference.AddDays(3), 0m); security.SetMarketPrice(fifth); Assert.AreEqual(5.6124, (double)model.Volatility, 0.0001); }
public void UpdatesProperly() { // we want to make sure the initialized value is the default value // for a datapoint, and also verify the our indicator updates as we // expect it to, in this case, it should return identity var target = new TestIndicator(); Assert.AreEqual(DateTime.MinValue, target.Current.Time); Assert.AreEqual(0m, target.Current.Value); var time = DateTime.UtcNow; var data = new IndicatorDataPoint(time, 1m); target.Update(data); Assert.AreEqual(1m, target.Current.Value); target.Update(new IndicatorDataPoint(time.AddMilliseconds(1), 2m)); Assert.AreEqual(2m, target.Current.Value); }
public void UpdatesProperly() { // we want to make sure the initialized value is the default value // for a datapoint, and also verify the our indicator updates as we // expect it to, in this case, it should return identity var target = new TestIndicator(); Assert.AreEqual(DateTime.MinValue, target.Current.Time); Assert.AreEqual(0m, target.Current.Value); var time = DateTime.UtcNow; var data = new IndicatorDataPoint(time, 1m); target.Update(data); Assert.AreEqual(1m, target.Current.Value); target.Update(new IndicatorDataPoint(time.AddMilliseconds(1), 2m)); Assert.AreEqual(2m, target.Current.Value); }
public OrderSignal CheckSignal(TradeBars data, Dictionary <string, string> paramlist, out string comment) { PropertyInfo[] properties = GetType().GetProperties(); // make sure symbol is set first for getting trendCurrent PropertyInfo s = properties.FirstOrDefault(x => x.Name == "symbol"); if (s != null) { symbol = new Symbol(paramlist["symbol"], paramlist["symbol"]); } IndicatorDataPoint trendCurrent = new IndicatorDataPoint(data[symbol].EndTime, 0);; string trend = paramlist["trend"]; trendCurrent.Value = System.Convert.ToDecimal(trend); foreach (var item in paramlist) { PropertyInfo p = properties.FirstOrDefault(x => x.Name == item.Key); if (p != null) { if (item.Key != "symbol") { { var converter = TypeDescriptor.GetConverter(p.PropertyType); var convertedvalue = converter.ConvertFrom(item.Value); var setmethod = p.SetMethod; if (setmethod != null) { p.SetValue(this, convertedvalue); } } } } } string current; OrderSignal retval = CheckSignal(data, trendCurrent, out current); comment = current; return(retval); }
private void Price_Updated(object sender, IndicatorDataPoint updated) { if (IsReady) { if (updated.Value >= _upperBand.Current.Value) { _indicators = Utils.shiftRight(_indicators); _indicators[0] = 1; } else if (updated.Value <= _lowerBand.Current.Value) { _indicators = Utils.shiftRight(_indicators); _indicators[0] = -1; } else { _indicators = Utils.shiftRight(_indicators); _indicators[0] = 0; } } }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { _ema1.Update(input); if (_ema1.IsReady) { _ema2.Update(_ema1.Current); } if (_ema2.IsReady) { _ema3.Update(_ema2.Current); } if (_ema3.IsReady) { _roc.Update(_ema3.Current); } return(_roc); }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { if (previousInput != null && input.Value >= previousInput.Value) { AverageGain.Update(input.Time, input.Value - previousInput.Value); AverageLoss.Update(input.Time, 0m); } else if (previousInput != null && input.Value < previousInput.Value) { AverageGain.Update(input.Time, 0m); AverageLoss.Update(input.Time, previousInput.Value - input.Value); } previousInput = input; if (AverageLoss == 0m) { // all up days is 100 return 100m; } var rs = AverageGain / AverageLoss; return 100m - (100m / (1 + rs)); }
private void ma_Updated(object sender, IndicatorDataPoint updated) { if (!IsReady) { return; } var actualSignal = Math.Sign(_moving_average_difference); if (actualSignal == _lastSignal || _lastSignal == 0) { Signal = (CrossingMovingAveragesSignals)actualSignal; } else if (_lastSignal == -1 && actualSignal == 1) { Signal = CrossingMovingAveragesSignals.FastCrossSlowFromBelow; } else if (_lastSignal == 1 && actualSignal == -1) { Signal = CrossingMovingAveragesSignals.FastCrossSlowFromAbove; } SurvivalWindow.Add((int)Signal); _lastSignal = actualSignal; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { if (previousInput != null && input.Value >= previousInput.Value) { AverageGain.Update(input.Time, input.Value - previousInput.Value); AverageLoss.Update(input.Time, 0m); } else if (previousInput != null && input.Value < previousInput.Value) { AverageGain.Update(input.Time, 0m); AverageLoss.Update(input.Time, previousInput.Value - input.Value); } previousInput = input; if (AverageLoss == 0m) { // all up days is 100 return(100m); } var rs = AverageGain / AverageLoss; return(100m - (100m / (1 + rs))); }
public void Update() { if (_lastUpdate == null || Algo.Time >= _lastUpdate.Add(_timeSpan)) { foreach (var indic in Indicators) { var pnl = Algo.Portfolio.TotalPortfolioValue; //var tb = new TradeBar(Algo.Time, Symbol.Empty, pnl, pnl, pnl, pnl, 0); var idp = new IndicatorDataPoint(Algo.Time, pnl); if (_previous != null) { _previous[indic.Key] = indic.Value.Current; } indic.Value.Update(idp); // if (pnl > 1010000 || indic.Value.Current != 0) // { // int stop = 1; // } //indic.Update(Algo.Time, ); } _lastUpdate = Algo.Time; } }
public OrderSignal CheckSignal(KeyValuePair <Symbol, TradeBar> data, IndicatorDataPoint trendCurrent, out string comment) { OrderSignal retval = OrderSignal.doNothing; comment = string.Empty; UpdateTrendArray(trendCurrent.Value); bReverseTrade = false; ReverseTrade = false; NTrigGTEP = false; NTrigLTEP = false; NTrigGTTA0 = false; NTrigLTTA0 = false; BarcountLT4 = false; OrderFilled = orderFilled; if (Barcount < 4) { BarcountLT4 = true; comment = "Barcount < 4"; retval = OrderSignal.doNothing; } else { nTrig = 2m * trendArray[0] - trendArray[2]; #region "Selection Logic Reversals" retval = CheckLossThreshhold(ref comment, retval); if (nTrig < (Math.Abs(nEntryPrice) / RevPct)) { NTrigLTEP = true; if (IsLong) { retval = OrderSignal.revertToShort; bReverseTrade = true; ReverseTrade = true; comment = string.Format("nTrig {0} < (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, NTrigLTEP, IsLong); } else { NTrigLTEP = false; } } else { if (nTrig > (Math.Abs(nEntryPrice) * RevPct)) { NTrigGTEP = true; if (IsShort) { retval = OrderSignal.revertToLong; bReverseTrade = true; ReverseTrade = true; comment = string.Format("nTrig {0} > (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, NTrigLTEP, IsLong); } else { NTrigGTEP = false; } } } #endregion #region "selection logic buy/sell" retval = CheckLossThreshhold(ref comment, retval); if (!bReverseTrade) { if (nTrig > trendArray[0]) { NTrigGTTA0 = true; if (xOver == -1) { #region "If Not Long" if (!IsLong) { if (!orderFilled) { retval = OrderSignal.goLong; comment = string.Format( "nTrig {0} > trend {1} xOver {2} !IsLong {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, orderFilled); } else { retval = OrderSignal.goLongLimit; comment = string.Format( "nTrig {0} > trend {1} xOver {2} !IsLong {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, orderFilled); } } #endregion } if (comment.Length == 0) { comment = "Trigger over trend - setting xOver to 1"; } xOver = 1; xOverisNegative = xOver < 0; xOverIsPositive = xOver > 0; } else { if (nTrig < trendArray[0]) { NTrigLTTA0 = true; if (xOver == 1) { #region "If Not Short" if (!IsShort) { if (!orderFilled) { retval = OrderSignal.goShort; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } else { retval = OrderSignal.goShortLimit; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } } #endregion } if (comment.Length == 0) { comment = "Trigger under trend - setting xOver to -1"; } xOver = -1; xOverisNegative = xOver < 0; xOverIsPositive = xOver > 0; } } } #endregion } StringBuilder sb = new StringBuilder(); sb.Append(comment); comment = sb.ToString(); return(retval); }
//public OrderSignal CheckSignal(TradeBars data, int tradesize, IndicatorDataPoint trendCurrent, out string current) //{ // return CheckSignal(data, tradesize, out current, TODO); //} /// <summary> /// Executes the Instant Trend strategy /// </summary> /// <param name="data">TradeBars - the current OnData</param> /// <param name="data">TradeBars - the current OnData</param> /// <param name="tradesize"></param> /// <param name="tradesize"></param> /// <param name="current"></param> /// <param name="current"></param> /// <param name="xOver1"></param> /// <param name="trendCurrent">IndicatorDataPoint - the current trend value trend</param> /// <summary> /// Executes the Instant Trend strategy /// </summary> public OrderSignal CheckSignal(TradeBars data, int tradesize, IndicatorDataPoint trendCurrent, out string current) { OrderTicket ticket; int orderId = 0; string comment = string.Empty; OrderSignal retval = OrderSignal.doNothing; trendHistory.Add(trendCurrent); nStatus = 0; if (_algorithm.Portfolio[_symbol].IsLong) { nStatus = 1; } if (_algorithm.Portfolio[_symbol].IsShort) { nStatus = -1; } if (!trendHistory.IsReady) { current = "Trend Not Ready"; return(OrderSignal.doNothing); } #region "Strategy Execution" bReverseTrade = false; try { var nTrig = 2 * trendHistory[0].Value - trendHistory[2].Value; if (nStatus == 1 && nTrig < (nEntryPrice / RevPct)) { comment = string.Format("Long Reverse to short. Close < {0} / {1}", nEntryPrice, RevPct); bReverseTrade = true; retval = OrderSignal.revertToShort; } else { if (nStatus == -1 && nTrig > (nEntryPrice * RevPct)) { comment = string.Format("Short Reverse to Long. Close > {0} * {1}", nEntryPrice, RevPct); bReverseTrade = true; retval = OrderSignal.revertToLong; } } if (!bReverseTrade) { if (nTrig > trendHistory[0].Value) { if (xOver == -1 && nStatus != 1) { if (!orderFilled) { retval = OrderSignal.goLong; comment = string.Format("{0} after order not filled", retval); } else { nLimitPrice = Math.Round(Math.Max(data[_symbol].Low, (data[_symbol].Close - (data[_symbol].High - data[_symbol].Low) * RngFac)), 2, MidpointRounding.ToEven); retval = OrderSignal.goLongLimit; comment = string.Format("{0} nTrig > history[0] xOver {1} Limit Price {2}", retval, xOver, nLimitPrice); } } if (comment.Length == 0) { comment = "Trigger over Trend"; } xOver = 1; } else { if (nTrig < trendHistory[0].Value) { if (xOver == 1 && nStatus != -1) { if (!orderFilled) { retval = OrderSignal.goShort; comment = string.Format("{0} after order not filled", retval); } else { nLimitPrice = Math.Round(Math.Min(data[_symbol].High, (data[_symbol].Close + (data[_symbol].High - data[_symbol].Low) * RngFac)), 2, MidpointRounding.ToEven); retval = OrderSignal.goShortLimit; comment = string.Format("{0} nTrig < history[0] xOver = {1} Limit Price {2}", retval, xOver, nLimitPrice); } } if (comment.Length == 0) { comment = "Trigger under trend"; } xOver = -1; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion current = comment; return(retval); }
public OrderSignal CheckSignal(TradeBars data, IndicatorDataPoint trendCurrent, out string comment) { OrderSignal retval = OrderSignal.doNothing; comment = string.Empty; //decimal price = (data[symbol].Close + data[symbol].Open) / 2; // Here is an attempt to smooth the price //ema.Update(idp(data[symbol].EndTime, price)); //if (ema.IsReady) // UpdatePriceArray(ema.Current); //else // UpdatePriceArray(idp(data[symbol].EndTime, price)); //if (Barcount == 17) // comment = ""; //// Update the trend with the smoothed price //trend.Update(ema.Current); //trend.Current.Symbol = data[symbol].Symbol; // make sure the symbol is correct //if (trend.Current.Value != trendCurrent.Value) // comment = "trends not equal"; UpdateTrendArray(trendCurrent.Value); bReverseTrade = false; ReverseTrade = false; NTrigGTEP = false; NTrigLTEP = false; NTrigGTTA0 = false; NTrigLTTA0 = false; BarcountLT4 = false; if (Barcount < 4) { BarcountLT4 = true; comment = "Barcount < 4"; retval = OrderSignal.doNothing; } else { nTrig = 2m * trendArray[0] - trendArray[2]; #region "Selection Logic Reversals" try { if (nTrig < (Math.Abs(nEntryPrice) / RevPct)) { NTrigLTEP = true; if (IsLong) { retval = OrderSignal.revertToShort; bReverseTrade = true; ReverseTrade = true; comment = string.Format("nTrig {0} < (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, NTrigLTEP, IsLong); } else { NTrigLTEP = false; } } else { if (nTrig > (Math.Abs(nEntryPrice) * RevPct)) { NTrigGTEP = true; if (IsShort) { retval = OrderSignal.revertToLong; bReverseTrade = true; ReverseTrade = true; comment = string.Format("nTrig {0} > (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, NTrigLTEP, IsLong); } else { NTrigGTEP = false; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion #region "selection logic buy/sell" try { if (!bReverseTrade) { if (nTrig > trendArray[0]) { NTrigGTTA0 = true; if (xOver == -1) { #region "If Not Long" if (!IsLong) { if (!orderFilled) { OrderFilled = false; retval = OrderSignal.goLong; comment = string.Format( "nTrig {0} > trend {1} xOver {2} !IsLong {3} !orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, !orderFilled); } else { retval = OrderSignal.goLongLimit; comment = string.Format( "nTrig {0} > trend {1} xOver {2} !IsLong {3} !orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, !orderFilled); } } #endregion } if (comment.Length == 0) comment = "Trigger over trend - setting xOver to 1"; xOver = 1; xOverisNegative = xOver < 0; xOverIsPositive = xOver > 0; } else { if (nTrig < trendArray[0]) { NTrigLTTA0 = true; if (xOver == 1) { #region "If Not Short" if (!IsShort) { if (!orderFilled) { OrderFilled = false; retval = OrderSignal.goShort; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } else { retval = OrderSignal.goShortLimit; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } } #endregion } if (comment.Length == 0) comment = "Trigger under trend - setting xOver to -1"; xOver = -1; xOverisNegative = xOver < 0; xOverIsPositive = xOver > 0; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion } StringBuilder sb = new StringBuilder(); sb.Append(comment); sb.Append(","); sb.Append(retval.ToString()); sb.Append(","); //sb.Append(ToInt32()); sb.Append(","); //sb.Append(ToIntCsv()); comment = sb.ToString(); return retval; }
/// <summary> /// AroonUp = 100 * (period - {periods since max})/period /// </summary> /// <param name="upPeriod">The AroonUp period</param> /// <param name="max">A Maximum indicator used to compute periods since max</param> /// <param name="input">The next input data</param> /// <returns>The AroonUp value</returns> private static decimal ComputeAroonUp(int upPeriod, Maximum max, IndicatorDataPoint input) { max.Update(input); return 100m * (upPeriod - max.PeriodsSinceMaximum) / upPeriod; }
public OrderSignal CheckSignal(KeyValuePair<Symbol, TradeBar> data, IndicatorDataPoint trendCurrent, out string current) { TradeBars tb = new TradeBars(); tb.Add(data.Key, data.Value); return CheckSignal(tb, trendCurrent, out current); }
/// <summary> /// Executes the Instant Trend strategy /// </summary> /// <param name="data">TradeBars - the current OnData</param> /// <param name="tradesize"></param> /// <param name="trendCurrent">IndicatorDataPoint - the current trend value trend</param> /// <param name="current"></param> public OrderSignal ExecuteStrategy(TradeBars data, int tradesize, IndicatorDataPoint trendCurrent, out string current) { OrderTicket ticket; string comment = string.Empty; OrderSignal retval = OrderSignal.doNothing; trendHistory.Add(trendCurrent); nStatus = 0; if (_algorithm.Portfolio[_symbol].IsLong) nStatus = 1; if (_algorithm.Portfolio[_symbol].IsShort) nStatus = -1; if (!trendHistory.IsReady) { current = "Trend Not Ready"; return OrderSignal.doNothing; } #region "Strategy Execution" bReverseTrade = false; try { var nTrig = 2 * trendHistory[0].Value - trendHistory[2].Value; if (nStatus == 1 && nTrig < (Math.Abs(nEntryPrice) / RevPct)) { if (maketrade) { ticket = ReverseToShort(); orderFilled = ticket.OrderId > 0; } bReverseTrade = true; retval = OrderSignal.revertToShort; comment = string.Format("{0} nStatus == {1} && nTrig {2} < (nEntryPrice {3} * RevPct{4} orderFilled {5})", retval, nStatus, nTrig, nEntryPrice, RevPct, orderFilled); } else { if (nStatus == -1 && nTrig > (Math.Abs(nEntryPrice) * RevPct)) { if (maketrade) { ticket = ReverseToLong(); orderFilled = ticket.OrderId > 0; } bReverseTrade = true; retval = OrderSignal.revertToLong; comment = string.Format("{0} nStatus == {1} && nTrig {2} > (nEntryPrice {3} * RevPct{4}, orderFilled {5})", retval, nStatus, nTrig, nEntryPrice, RevPct, orderFilled); } } if (!bReverseTrade) { if (nTrig > trendHistory[0].Value) { if (xOver == -1 && nStatus != 1) { if (!orderFilled) { try { if (maketrade) ticket = _algorithm.Buy(_symbol, tradesize); } catch (Exception e) { Console.WriteLine(e); } retval = OrderSignal.goLong; comment = string.Format("{0} nStatus {1} nTrig {2} > trendHistory[0].Value {3} xOver {4} orderFilled {5}", retval, nStatus, nTrig, trendHistory[0].Value, xOver, orderFilled); } else { nLimitPrice = Math.Round(Math.Max(data[_symbol].Low, (data[_symbol].Close - (data[_symbol].High - data[_symbol].Low) * RngFac)), 2, MidpointRounding.ToEven); try { if (maketrade) ticket = _algorithm.LimitOrder(_symbol, tradesize, nLimitPrice, "Long Limit"); } catch (Exception e) { Console.WriteLine(e); } retval = OrderSignal.goLongLimit; comment = string.Format("{0} nStatus {1} nTrig {2} > trendHistory[0].Value {3} xOver {4} Limit Price {5}", retval, nStatus, nTrig, trendHistory[0].Value, xOver, nLimitPrice); } } if (comment.Length == 0) comment = "Trigger over Trend"; xOver = 1; } else { if (nTrig < trendHistory[0].Value) { if (xOver == 1 && nStatus != -1) { if (!orderFilled) { try { if (maketrade) ticket = _algorithm.Sell(_symbol, tradesize); } catch (Exception e) { Console.WriteLine(e); } retval = OrderSignal.goShort; comment = string.Format("{0} Enter Short after cancel trig xunder price down", retval); } else { nLimitPrice = Math.Round(Math.Min(data[_symbol].High, (data[_symbol].Close + (data[_symbol].High - data[_symbol].Low) * RngFac)), 2, MidpointRounding.ToEven); try { if (maketrade) ticket = _algorithm.LimitOrder(_symbol, -tradesize, nLimitPrice, "Short Limit"); //ticket = _algorithm.Sell(_symbol, tradesize); } catch (Exception e) { Console.WriteLine(e); } retval = OrderSignal.goShortLimit; comment = string.Format("{0} nStatus {1} nTrig {2} < trendHistory[0].Value {3} xOver {4} Limit Price {5}", retval, nStatus, nTrig, trendHistory[0].Value, xOver, nLimitPrice); } } if (comment.Length == 0) comment = "Trigger under trend"; xOver = -1; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion current = comment; return retval; }
private void AttemptCompositeUpdate(IndicatorBase <IndicatorDataPoint> indicator, IndicatorDataPoint point) { if (indicator.GetType() == typeof(CompositeIndicator <IndicatorDataPoint>)) { var composite = ((CompositeIndicator <IndicatorDataPoint>)indicator); composite.Left.Update(point); composite.Right.Update(point); AttemptCompositeUpdate(composite.Left, point); AttemptCompositeUpdate(composite.Right, point); } }
public void MSAFullTest() { #region Fields int idx = 0; int day = 0; DateTime Time = DateTime.Today; DateTime testTime = Time; double amplitude = 1; int shift = 100; int waveLength = 45; IndicatorDataPoint ssObs; Indicator smoothedSeries = new Identity("SmoothedSeries"); MSAStrategy strategy = new MSAStrategy(smoothedSeries, 2, 3, 0m); #endregion Fields #region Warming up Console.WriteLine("Warming up"); do { ssObs = new IndicatorDataPoint(testTime, SineWave(idx, amplitude * idx, waveLength, shift)); smoothedSeries.Update(ssObs); testTime = testTime.AddMinutes(1); idx++; if (idx > 59) { day++; testTime = Time.AddDays(day); idx = 0; switch (day) { case 1: amplitude = 2; shift = 150; waveLength = 15; break; case 2: amplitude = 1.5; shift = 100; waveLength = 20; break; case 3: amplitude = 3; shift = 180; waveLength = 12; break; default: break; } Console.WriteLine("New day: " + day); } } while (!strategy.IsReady); Console.WriteLine("Strategy ready!\nStarting signal test."); #endregion Warming up #region Testing signals var expectedSignals = new Dictionary<int, OrderSignal>(); expectedSignals.Add(34, OrderSignal.goLong); expectedSignals.Add(40, OrderSignal.goShort); expectedSignals.Add(46, OrderSignal.goLong); expectedSignals.Add(52, OrderSignal.goShort); expectedSignals.Add(58, OrderSignal.goLong); for (int i = 0; i < 60; i++) { ssObs = new IndicatorDataPoint(testTime, SineWave(i, amplitude * i, waveLength, shift)); smoothedSeries.Update(ssObs); Console.WriteLine(string.Format("{0}\t|\t{1}\t|\t{2}", i, ssObs.Value.SmartRounding(), strategy.ActualSignal )); if (expectedSignals.ContainsKey(i)) { Assert.AreEqual(expectedSignals[i], strategy.ActualSignal, string.Format("Bar {0} test.", i)); } else { Assert.AreEqual(OrderSignal.doNothing, strategy.ActualSignal, string.Format("Bar {0} test.", i)); } testTime = testTime.AddMinutes(1); } #endregion Testing signals }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { var value = base.ComputeNextValue(input); return(Slow != 0 ? 100 * value / Slow : 0m); }
public OrderSignal CheckSignal(TradeBars data, IndicatorDataPoint trendCurrent, out string comment) { OrderSignal retval = OrderSignal.doNothing; if (Barcount == 1) comment = ""; decimal price = (data[symbol].Close + data[symbol].Open) / 2; trend.Update(idp(data[symbol].EndTime, price)); if (trendCurrent.Value != trend.Current.Value) comment = "not equal"; UpdateTrendArray(trend.Current); comment = ""; bReverseTrade = false; if (Barcount < 4) { comment = "Trend Not Ready"; return OrderSignal.doNothing; } #region "Selection Logic Reversals" try { nTrig = 2 * trendArray[0] - trendArray[2]; // Note this is backwards from a RollingWindow if (IsLong && nTrig < (Math.Abs(nEntryPrice) / RevPct)) { retval = OrderSignal.revertToShort; bReverseTrade = true; comment = string.Format("{0} nTrig {1} < (nEntryPrice {2} * RevPct{3}) orderFilled {4})", retval, Math.Round(nTrig, 4), nEntryPrice, RevPct, orderFilled); } else { if (IsShort && nTrig > (Math.Abs(nEntryPrice) * RevPct)) { retval = OrderSignal.revertToLong; bReverseTrade = true; comment = string.Format("{0} nTrig {1} > (nEntryPrice {2} * RevPct{3}) orderFilled {4})", retval, Math.Round(nTrig, 4), nEntryPrice, RevPct, orderFilled); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion #region "selection logic buy/sell" try { if (!bReverseTrade) { if (nTrig > trendArray[0]) { if (xOver == -1 && !IsLong) { if (!orderFilled) { retval = OrderSignal.goLong; comment = string.Format( "{0} IsLong && nTrig {1} > trend {2} xOver {3} orderFilled {4}", retval, Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, orderFilled); } else { retval = OrderSignal.goLongLimit; comment = string.Format( "{0} IsLong && nTrig {1} > trend {2} xOver {3}", retval, Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver); } } if (comment.Length == 0) comment = "Trigger over trend - setting xOver to 1"; xOver = 1; } else { if (nTrig < trendArray[0]) { if (xOver == 1 && !IsShort) { if (!orderFilled) { retval = OrderSignal.goShort; comment = string.Format( "{0} nTrig {1} < trend {2} xOver {3} orderFilled {4}", retval, Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, orderFilled); } else { retval = OrderSignal.goShortLimit; comment = string.Format( "{0} nTrig {1} < trend {2} xOver {3}", retval, Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver); } } if (comment.Length == 0) comment = "Trigger under trend - setting xOver to -1"; xOver = -1; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion return retval; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <param name="window">The window for the input history</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IReadOnlyWindow<IndicatorDataPoint> window, IndicatorDataPoint input) { return (decimal)Math.Sqrt((double)base.ComputeNextValue(window, input)); }
public OrderSignal CheckSignal(TradeBars data, Dictionary<string, string> paramlist, out string comment) { PropertyInfo[] properties = GetType().GetProperties(); // make sure symbol is set first for getting trendCurrent PropertyInfo s = properties.FirstOrDefault(x => x.Name == "symbol"); if (s != null) { symbol = new Symbol(paramlist["symbol"], paramlist["symbol"]); } IndicatorDataPoint trendCurrent = new IndicatorDataPoint(data[symbol].EndTime,0); ; string trend = paramlist["trend"]; trendCurrent.Value = System.Convert.ToDecimal(trend); foreach (var item in paramlist) { PropertyInfo p = properties.FirstOrDefault(x => x.Name == item.Key); if (p != null) { if (item.Key != "symbol") { { var converter = TypeDescriptor.GetConverter(p.PropertyType); try { var convertedvalue = converter.ConvertFrom(item.Value); var setmethod = p.SetMethod; if (setmethod != null) p.SetValue(this, convertedvalue); } catch (Exception e) { Debug.WriteLine(e.Message); } } } } } string current; OrderSignal retval = CheckSignal(data, trendCurrent, out current); comment = current; return retval; }
private void UpdateTrendArray(IndicatorDataPoint trendCurrent) { trendArray[2] = trendArray[1]; trendArray[1] = trendArray[0]; trendArray[0] = trendCurrent.Value; }
public OrderSignal CheckSignal(KeyValuePair <Symbol, TradeBar> data, IndicatorDataPoint trendCurrent, out string current) { throw new NotImplementedException(); }
public OrderSignal CheckSignal(TradeBars data, IndicatorDataPoint trendCurrent, out string comment) { OrderSignal retval = OrderSignal.doNothing; comment = string.Empty; decimal price = (data[symbol].Close + data[symbol].Open) / 2; trend.Update(idp(data[symbol].EndTime, price)); if (trendCurrent.Value != trend.Current.Value) { comment = "not equal"; } UpdateTrendArray(trend.Current); bReverseTrade = false; v.ReverseTrade = false; v.NTrigGTEP = false; v.NTrigLTEP = false; v.NTrigGTTA0 = false; v.NTrigLTTA0 = false; v.OrderFilled = true; v.IsLong = IsLong; v.IsShort = IsShort; v.BarcountLT4 = false; if (Barcount < 4) { v.BarcountLT4 = true; comment = "Barcount < 4"; retval = OrderSignal.doNothing; } else { nTrig = 2 * trendArray[0] - trendArray[2]; #region "Selection Logic Reversals" try { if (nTrig < (Math.Abs(nEntryPrice) / RevPct)) { v.NTrigLTEP = true; if (IsLong) { retval = OrderSignal.revertToShort; bReverseTrade = true; v.ReverseTrade = true; comment = string.Format("nTrig {0} < (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, v.NTrigLTEP, IsLong); } else { v.NTrigLTEP = false; } } else { if (nTrig > (Math.Abs(nEntryPrice) * RevPct)) { v.NTrigGTEP = true; if (IsShort) { retval = OrderSignal.revertToLong; bReverseTrade = true; v.ReverseTrade = true; comment = string.Format("nTrig {0} > (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, v.NTrigLTEP, IsLong); } else { v.NTrigGTEP = false; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion #region "selection logic buy/sell" try { if (!bReverseTrade) { if (nTrig > trendArray[0]) { v.NTrigGTTA0 = true; if (xOver == -1) { if (!IsLong) { if (!orderFilled) { v.OrderFilled = false; retval = OrderSignal.goLong; comment = string.Format( "nTrig {0} > trend {1} xOver {2} !IsLong {3} !orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, !orderFilled); } else { retval = OrderSignal.goLongLimit; comment = string.Format("nTrig {0} > trend {1} xOver {2} !IsLong {3} !orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, !orderFilled); } } } if (comment.Length == 0) { comment = "Trigger over trend - setting xOver to 1"; } xOver = 1; v.xOverisNegative = xOver < 0; v.xOverIsPositive = xOver > 0; } else { if (nTrig < trendArray[0]) { v.NTrigLTTA0 = true; if (xOver == 1) { if (!IsShort) { if (!orderFilled) { v.OrderFilled = false; retval = OrderSignal.goShort; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } else { retval = OrderSignal.goShortLimit; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } } } if (comment.Length == 0) { comment = "Trigger under trend - setting xOver to -1"; } xOver = -1; v.xOverisNegative = xOver < 0; v.xOverIsPositive = xOver > 0; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion } StringBuilder sb = new StringBuilder(); sb.Append(comment); sb.Append(","); sb.Append(retval.ToString()); sb.Append(","); sb.Append(v.ToInt32()); sb.Append(","); sb.Append(v.ToIntCsv()); comment = sb.ToString(); return(retval); }
public OrderSignal CheckSignal(KeyValuePair<Symbol, TradeBar> data, IndicatorDataPoint trendCurrent, out string comment) { OrderSignal retval = OrderSignal.doNothing; comment = string.Empty; UpdateTrendArray(trendCurrent.Value); bReverseTrade = false; ReverseTrade = false; NTrigGTEP = false; NTrigLTEP = false; NTrigGTTA0 = false; NTrigLTTA0 = false; BarcountLT4 = false; OrderFilled = orderFilled; if (Barcount < 4) { BarcountLT4 = true; comment = "Barcount < 4"; nTrig = trendCurrent.Value; retval = OrderSignal.doNothing; } else { nTrig = 2m * trendArray[0] - trendArray[2]; #region "Selection Logic Reversals" retval = CheckLossThreshhold(ref comment, retval); if (nTrig < (Math.Abs(nEntryPrice) / RevPct)) { NTrigLTEP = true; if (IsLong) { retval = OrderSignal.revertToShort; bReverseTrade = true; ReverseTrade = true; comment = string.Format("nTrig {0} < (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, NTrigLTEP, IsLong); } else { NTrigLTEP = false; } } else { if (nTrig > (Math.Abs(nEntryPrice) * RevPct)) { NTrigGTEP = true; if (IsShort) { retval = OrderSignal.revertToLong; bReverseTrade = true; ReverseTrade = true; comment = string.Format("nTrig {0} > (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, NTrigLTEP, IsLong); } else { NTrigGTEP = false; } } } #endregion #region "selection logic buy/sell" retval = CheckLossThreshhold(ref comment, retval); if (!bReverseTrade) { if (nTrig > trendArray[0]) { NTrigGTTA0 = true; if (xOver == -1) { #region "If Not Long" if (!IsLong) { if (!orderFilled) { retval = OrderSignal.goLong; comment = string.Format( "nTrig {0} > trend {1} xOver {2} !IsLong {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, orderFilled); } else { retval = OrderSignal.goLongLimit; comment = string.Format( "nTrig {0} > trend {1} xOver {2} !IsLong {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, orderFilled); } } #endregion } if (comment.Length == 0) comment = "Trigger over trend - setting xOver to 1"; xOver = 1; xOverisNegative = xOver < 0; xOverIsPositive = xOver > 0; } else { if (nTrig < trendArray[0]) { NTrigLTTA0 = true; if (xOver == 1) { #region "If Not Short" if (!IsShort) { if (!orderFilled) { retval = OrderSignal.goShort; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } else { retval = OrderSignal.goShortLimit; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } } #endregion } if (comment.Length == 0) comment = "Trigger under trend - setting xOver to -1"; xOver = -1; xOverisNegative = xOver < 0; xOverIsPositive = xOver > 0; } } } #endregion } StringBuilder sb = new StringBuilder(); sb.Append(comment); comment = sb.ToString(); return retval; }
private void UpdateTrendArray(IndicatorDataPoint trendCurrent) { trendArray[2] = trendArray[1]; trendArray[1] = trendArray[0]; trendArray[0] = trendCurrent.Value; }
public OrderSignal CheckSignal(TradeBars data, IndicatorDataPoint trendCurrent, out string comment) { OrderSignal retval = OrderSignal.doNothing; comment = string.Empty; decimal price = (data[symbol].Close + data[symbol].Open) / 2; trend.Update(idp(data[symbol].EndTime, price)); if (trendCurrent.Value != trend.Current.Value) comment = "not equal"; UpdateTrendArray(trend.Current); bReverseTrade = false; v.ReverseTrade = false; v.NTrigGTEP = false; v.NTrigLTEP = false; v.NTrigGTTA0 = false; v.NTrigLTTA0 = false; v.OrderFilled = true; v.IsLong = IsLong; v.IsShort = IsShort; v.BarcountLT4 = false; if (Barcount < 4) { v.BarcountLT4 = true; comment = "Barcount < 4"; retval = OrderSignal.doNothing; } else { nTrig = 2 * trendArray[0] - trendArray[2]; #region "Selection Logic Reversals" try { if (nTrig < (Math.Abs(nEntryPrice) / RevPct)) { v.NTrigLTEP = true; if (IsLong) { retval = OrderSignal.revertToShort; bReverseTrade = true; v.ReverseTrade = true; comment = string.Format("nTrig {0} < (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, v.NTrigLTEP, IsLong); } else { v.NTrigLTEP = false; } } else { if (nTrig > (Math.Abs(nEntryPrice) * RevPct)) { v.NTrigGTEP = true; if (IsShort) { retval = OrderSignal.revertToLong; bReverseTrade = true; v.ReverseTrade = true; comment = string.Format("nTrig {0} > (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )", Math.Round(nTrig, 4), nEntryPrice, RevPct, v.NTrigLTEP, IsLong); } else { v.NTrigGTEP = false; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion #region "selection logic buy/sell" try { if (!bReverseTrade) { if (nTrig > trendArray[0]) { v.NTrigGTTA0 = true; if (xOver == -1) { if (!IsLong) { if (!orderFilled) { v.OrderFilled = false; retval = OrderSignal.goLong; comment = string.Format( "nTrig {0} > trend {1} xOver {2} !IsLong {3} !orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, !orderFilled); } else { retval = OrderSignal.goLongLimit; comment = string.Format("nTrig {0} > trend {1} xOver {2} !IsLong {3} !orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsLong, !orderFilled); } } } if (comment.Length == 0) comment = "Trigger over trend - setting xOver to 1"; xOver = 1; v.xOverisNegative = xOver < 0; v.xOverIsPositive = xOver > 0; } else { if (nTrig < trendArray[0]) { v.NTrigLTTA0 = true; if (xOver == 1) { if (!IsShort) { if (!orderFilled) { v.OrderFilled = false; retval = OrderSignal.goShort; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } else { retval = OrderSignal.goShortLimit; comment = string.Format( "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}", Math.Round(nTrig, 4), Math.Round(trendArray[0], 4), xOver, !IsShort, !orderFilled); } } } if (comment.Length == 0) comment = "Trigger under trend - setting xOver to -1"; xOver = -1; v.xOverisNegative = xOver < 0; v.xOverIsPositive = xOver > 0; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion } StringBuilder sb = new StringBuilder(); sb.Append(comment); sb.Append(","); sb.Append(retval.ToString()); sb.Append(","); sb.Append(v.ToInt32()); sb.Append(","); sb.Append(v.ToIntCsv()); comment = sb.ToString(); return retval; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <param name="window">The window for the input history</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IReadOnlyWindow <IndicatorDataPoint> window, IndicatorDataPoint input) { // Calculate the efficiency ratio var efficiencyRatio = base.ComputeNextValue(window, input); if (Samples < Period) { return(input.Value); } if (Samples == Period) { // Calculate the first KAMA // The yesterday price is used here as the previous KAMA. _prevKama = window[1].Value; } // Calculate the smoothing constant var smoothingConstant = efficiencyRatio * _diffSmoothingFactor + _slowSmoothingFactor; smoothingConstant *= smoothingConstant; // Calculate the KAMA like an EMA, using the // smoothing constant as the adaptive factor. _prevKama = (input.Value - _prevKama) * smoothingConstant + _prevKama; return(_prevKama); }
public OrderSignal CheckSignal(KeyValuePair<Symbol, TradeBar> data, IndicatorDataPoint trendCurrent, out string current) { throw new NotImplementedException(); }
/// <summary> /// Executes the Instant Trend strategy /// </summary> /// <param name="data">TradeBars - the current OnData</param> /// <param name="tradesize"></param> /// <param name="trendCurrent">IndicatorDataPoint - the current trend value trend</param> /// <param name="current"></param> public OrderSignal ExecuteStrategy(TradeBars data, int tradesize, IndicatorDataPoint trendCurrent, out string current) { OrderTicket ticket; string comment = string.Empty; OrderSignal retval = OrderSignal.doNothing; trendHistory.Add(trendCurrent); nStatus = 0; if (_algorithm.Portfolio[_symbol].IsLong) { nStatus = 1; } if (_algorithm.Portfolio[_symbol].IsShort) { nStatus = -1; } if (!trendHistory.IsReady) { current = "Trend Not Ready"; return(OrderSignal.doNothing); } #region "Strategy Execution" bReverseTrade = false; try { var nTrig = 2 * trendHistory[0].Value - trendHistory[2].Value; if (nStatus == 1 && nTrig < (Math.Abs(nEntryPrice) / RevPct)) { if (maketrade) { ticket = ReverseToShort(); orderFilled = ticket.OrderId > 0; } bReverseTrade = true; retval = OrderSignal.revertToShort; comment = string.Format("{0} nStatus == {1} && nTrig {2} < (nEntryPrice {3} * RevPct{4} orderFilled {5})", retval, nStatus, nTrig, nEntryPrice, RevPct, orderFilled); } else { if (nStatus == -1 && nTrig > (Math.Abs(nEntryPrice) * RevPct)) { if (maketrade) { ticket = ReverseToLong(); orderFilled = ticket.OrderId > 0; } bReverseTrade = true; retval = OrderSignal.revertToLong; comment = string.Format("{0} nStatus == {1} && nTrig {2} > (nEntryPrice {3} * RevPct{4}, orderFilled {5})", retval, nStatus, nTrig, nEntryPrice, RevPct, orderFilled); } } if (!bReverseTrade) { if (nTrig > trendHistory[0].Value) { if (xOver == -1 && nStatus != 1) { if (!orderFilled) { try { if (maketrade) { ticket = _algorithm.Buy(_symbol, tradesize); } } catch (Exception e) { Console.WriteLine(e); } retval = OrderSignal.goLong; comment = string.Format("{0} nStatus {1} nTrig {2} > trendHistory[0].Value {3} xOver {4} orderFilled {5}", retval, nStatus, nTrig, trendHistory[0].Value, xOver, orderFilled); } else { nLimitPrice = Math.Round(Math.Max(data[_symbol].Low, (data[_symbol].Close - (data[_symbol].High - data[_symbol].Low) * RngFac)), 2, MidpointRounding.ToEven); try { if (maketrade) { ticket = _algorithm.LimitOrder(_symbol, tradesize, nLimitPrice, "Long Limit"); } } catch (Exception e) { Console.WriteLine(e); } retval = OrderSignal.goLongLimit; comment = string.Format("{0} nStatus {1} nTrig {2} > trendHistory[0].Value {3} xOver {4} Limit Price {5}", retval, nStatus, nTrig, trendHistory[0].Value, xOver, nLimitPrice); } } if (comment.Length == 0) { comment = "Trigger over Trend"; } xOver = 1; } else { if (nTrig < trendHistory[0].Value) { if (xOver == 1 && nStatus != -1) { if (!orderFilled) { try { if (maketrade) { ticket = _algorithm.Sell(_symbol, tradesize); } } catch (Exception e) { Console.WriteLine(e); } retval = OrderSignal.goShort; comment = string.Format("{0} Enter Short after cancel trig xunder price down", retval); } else { nLimitPrice = Math.Round(Math.Min(data[_symbol].High, (data[_symbol].Close + (data[_symbol].High - data[_symbol].Low) * RngFac)), 2, MidpointRounding.ToEven); try { if (maketrade) { ticket = _algorithm.LimitOrder(_symbol, -tradesize, nLimitPrice, "Short Limit"); } //ticket = _algorithm.Sell(_symbol, tradesize); } catch (Exception e) { Console.WriteLine(e); } retval = OrderSignal.goShortLimit; comment = string.Format("{0} nStatus {1} nTrig {2} < trendHistory[0].Value {3} xOver {4} Limit Price {5}", retval, nStatus, nTrig, trendHistory[0].Value, xOver, nLimitPrice); } } if (comment.Length == 0) { comment = "Trigger under trend"; } xOver = -1; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion current = comment; return(retval); }
/// <summary> /// Executes the Instant Trend strategy /// </summary> /// <param name="data">TradeBars - the current OnData</param> /// <param name="tradesize"></param> /// <param name="trendCurrent">IndicatorDataPoint - the current trend value trend</param> /// <param name="orderId">int - the orderId if one is placed, -1 if order has not filled and 0 if no order was placed</param> public string ExecuteStrategy(TradeBars data, int tradesize, IndicatorDataPoint max, IndicatorDataPoint min, RateOfChangePercent rocp, ref SimpleMovingAverage sma20, out int orderId) { maximum = max; minimum = min; Price.Add(idp(data[_symbol].EndTime, (data[_symbol].Close + data[_symbol].Open) / 2)); orderId = 0; comment = string.Empty; if (_algorithm.Portfolio[_symbol].IsLong) { nStatus = 1; } if (_algorithm.Portfolio[_symbol].IsShort) { nStatus = -1; } #region "Strategy Execution" bReverseTrade = false; try { if (!_algorithm.Portfolio.Invested) { if (PricePassedAValley() && rocp.Current.Value < 0) { ticket = GetLong(tradesize); orderId = ticket.OrderId; comment = "Bot new position ppMin && rocp < 0"; } if (PricePassedAPeak() && rocp.Current.Value > 0) { ticket = GetShort(tradesize); orderId = ticket.OrderId; comment = "Sld new position ppMin && rocp < 0"; } } else { if (PricePassedAValley() && _algorithm.Portfolio[_symbol].IsShort) { if (Price[0].Value > sma20.Current.Value && (Math.Abs(sma20.Current.Value - Price[0].Value) / Price[0].Value) > .001m) { ticket = ReverseToLong(); comment = "Rev2Long Passed a Valley"; } } if (PricePassedAPeak() && _algorithm.Portfolio[_symbol].IsLong) { if (Price[0].Value <sma20.Current.Value && (Math.Abs(sma20.Current.Value - Price[0].Value) / Price[0].Value)> .001m) { ticket = ReverseToShort(); comment = "Rev2Short Passed a Peak"; } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } #endregion return(comment); }
protected override decimal ComputeNextValue(IReadOnlyWindow <IndicatorDataPoint> window, IndicatorDataPoint input) { if (_previous != null && input.EndTime == _previous.EndTime) { throw new Exception($"Unexpected indicator double data point call: {_previous}"); } _previous = input; return(base.ComputeNextValue(window, input)); }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns> /// A new value for this indicator /// </returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { _standardDeviation.Update(input); LinearRegression.Update(input); LowerChannel.Update(input); UpperChannel.Update(input); return LinearRegression.Current; }
/// <summary> /// Updates the <see cref="Signal" /> status. /// </summary> protected virtual void Indicator_Updated(object sender, IndicatorDataPoint updated) { var actualPositionSignal = GetThresholdState(updated); ProcessThresholdStateChange(actualPositionSignal, updated); }
protected void ProcessThresholdStateChange(ThresholdState actualPositionSignal, IndicatorDataPoint updated) { if (!Indicator.IsReady) { _previousIndicatorValue = updated.Value; _previousSignal = actualPositionSignal; Signal = _previousSignal; return; } var actualSignal = GetActualSignal(_previousSignal, actualPositionSignal); Signal = actualSignal; _previousIndicatorValue = updated.Value; _lastSignals = Utils.shiftRight(_lastSignals); _lastSignals[0] = (int)Signal; _previousSignal = actualSignal; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { return input; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { var value = base.ComputeNextValue(input); return Slow != 0 ? 100 * value / Slow : 0m; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { return(input); }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(TradeBar input) { _trueRange.Update(input); if (Samples == 1) { _previousInput = input; return 50m; } var buyingPressure = new IndicatorDataPoint { Value = input.Close - Math.Min(input.Low, _previousInput.Close) }; _sumBuyingPressure1.Update(buyingPressure); _sumBuyingPressure2.Update(buyingPressure); _sumBuyingPressure3.Update(buyingPressure); _sumTrueRange1.Update(_trueRange.Current); _sumTrueRange2.Update(_trueRange.Current); _sumTrueRange3.Update(_trueRange.Current); _previousInput = input; if (!IsReady) return 50m; var average1 = _sumBuyingPressure1 / _sumTrueRange1; var average2 = _sumBuyingPressure2 / _sumTrueRange2; var average3 = _sumBuyingPressure3 / _sumTrueRange3; return 100m * (4 * average1 + 2 * average2 + average3) / 7; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { _price.Add((double)input.Price); if (_price.Samples == 1) { _price.Add(_price[0]); _price.Add(_price[0]); } double signal = _a0 * _c0 * (_b0 * _price[0] + _b1 * _price[1] + _b2 * _price[2]) + _a0 * (_a1 * _filt[0] + _a2 * _filt[1]); _filt.Add(signal); return (decimal)signal; }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) => input.Price;
public void UpdateTrendHistory(IndicatorDataPoint datapoint) { trendHistory.Add(datapoint); }
/// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="input">The input given to the indicator</param> /// <returns> /// A new value for this indicator /// </returns> protected override decimal ComputeNextValue(IndicatorDataPoint input) { // Until the windows is ready, the indicator returns the input value. decimal output = input; seriesQ.Enqueue((double)input.Value); if (IsReady) { seriesQ.Dequeue(); var series = seriesQ.ToArray(); // Fit OLS Tuple<double, double> ols = Fit.Line(x: t, y: series); var alfa = (decimal)ols.Item1; var beta = (decimal)ols.Item2; // Make the projection. output = alfa + beta * (_period); } return output; }