public commonIndicatorForm(Indicators.Meta meta) : base(meta) { InitializeComponent(); tabControl.SendToBack(); SetPara(meta); }
/// <summary> /// Create parametter grid from meta.ParameterDefaultValues /// </summary> /// <param name="meta"></param> protected void SetPara(Indicators.Meta meta) { this.Text = meta.Name; paramGrid.Rows.Clear(); string[] keys = meta.ParameterList.Keys; object[] values = meta.ParameterList.Values; for (int idx = 0; idx < keys.Length; idx++) { paramGrid.Rows.Add(keys[idx], values[idx]); } valueColumn.DefaultCellStyle.Format = "N" + meta.ParameterPrecision.ToString(); inNewPaneChk.Checked = meta.DrawInNewWindow; keys = meta.OutputInfoList.Keys; values = meta.OutputInfoList.Values; for (int idx = 0; idx < keys.Length; idx++) { Color color = (meta.Output.Length > idx ? meta.Output[idx].Color : Color.Red); int weight = (meta.Output.Length > idx ? meta.Output[idx].Weight : 1); AppTypes.ChartTypes chartType = (meta.Output.Length > idx ? meta.Output[idx].ChartType : AppTypes.ChartTypes.Line); outputGrid.Rows.Add(keys[idx], color, weight,chartType); } paraDescEd.Text = common.system.ToString(meta.ParameterDescriptions); hintTextEd.Text = meta.Description + common.Consts.constCRLF + meta.URL; }
public sampleMACD(Indicators.Meta meta) : base(meta) { InitializeComponent(); macdColorEd.LoadColors(); signalColorEd.LoadColors(); histColorCb.LoadColors(); this.macdColorEd.Color = (meta.Output.Length>0?meta.Output[0].Color:Color.Green); this.signalColorEd.Color = (meta.Output.Length > 1 ? meta.Output[1].Color : Color.Red); this.histColorCb.Color = (meta.Output.Length > 2 ? meta.Output[2].Color : Color.Navy); this.macdWeightEd.Value = (meta.Output.Length > 0 ? meta.Output[0].Weight : 1); this.sigWeightEd.Value = (meta.Output.Length > 1 ? meta.Output[1].Weight : 1); this.histWeightEd.Value = (meta.Output.Length > 2 ? meta.Output[2].Weight : 1); }
protected override void CollectMetaData(Indicators.Meta meta) { meta.Parameters = new double[] { (int)fastParaEd.Value, (int)slowParaEd.Value, (int)signalParaEd.Value }; meta.DrawInNewWindow = inNewPaneChk.Checked; meta.Output = new Indicators.Meta.OutputInfo[3]; meta.Output[0].ChartType = AppTypes.ChartTypes.Line; meta.Output[0].Color = macdColorEd.Color; meta.Output[0].Weight = (byte)macdWeightEd.Value; meta.Output[1].ChartType = AppTypes.ChartTypes.Line; meta.Output[1].Color = signalColorEd.Color; meta.Output[1].Weight = (byte)sigWeightEd.Value; meta.Output[2].ChartType = AppTypes.ChartTypes.Bar; meta.Output[2].Color = histColorCb.Color; meta.Output[2].Weight = (byte)histWeightEd.Value; }
//TUAN 9/3/2012 public void updateFormFromMeta(Indicators.Meta _meta) { if (_meta.ListWindowNames != null) { foreach (DictionaryEntry item in _meta.ListWindowNames) { if (item.Key.Equals(constPaneNamePrice) || item.Key.Equals(constPaneNameNew)) { } else { cbbWindow.Items.Add(item.Key.ToString()); } } cbbWindow.SelectedIndex = 0; } }
protected override void CollectMetaData(Indicators.Meta meta) { double val = 0; double[] paras = new double[paramGrid.Rows.Count]; for (int idx = 0; idx < paramGrid.Rows.Count; idx++) { paras[idx] = (double.TryParse(paramGrid[1, idx].Value.ToString(), out val) ? val : 0); } meta.Parameters = paras; Indicators.Meta.OutputInfo[] outPut = new Indicators.Meta.OutputInfo[outputGrid.Rows.Count]; for (int idx = 0; idx < outputGrid.Rows.Count; idx++) { outPut[idx] = new Indicators.Meta.OutputInfo((Color)outputGrid[outColorColumn.Name, idx].Value, int.Parse(outputGrid[outWeightColumn.Name, idx].Value.ToString()), (AppTypes.ChartTypes)outputGrid[outChartTypeColumn.Name, idx].Value); } meta.Output = outPut; meta.DrawInNewWindow = inNewPaneChk.Checked; }
public commonIndicatorForm(Indicators.Meta meta) : base(meta) { InitializeComponent(); tabControl.SendToBack(); SetPara(meta); //TUAN 7/24/2012 - Add Windows selection for drawing - BEGIN if (meta.ListWindowNames!=null) { lblWindow.Visible = true; cbbWindow.Visible = true; inNewPaneChk.Visible = false; if (meta.DrawInNewWindow) { cbbWindow.Items.Add(Languages.Libs.GetString("newPanel")); cbbWindow.Items.Add(Languages.Libs.GetString("pricePanel")); } else { cbbWindow.Items.Add(Languages.Libs.GetString("pricePanel")); cbbWindow.Items.Add(Languages.Libs.GetString("newPanel")); } foreach (DictionaryEntry item in meta.ListWindowNames) { if (item.Key.Equals(constPaneNamePrice) || item.Key.Equals(constPaneNameNew)) { } else { cbbWindow.Items.Add(item.Key.ToString()); } } cbbWindow.SelectedIndex = 0; } //TUAN 7/24/2012 - Add Windows selection for drawing - END }
protected override void OnStart() { rsi = Indicators.RelativeStrengthIndex(Source, Periods); ma = Indicators.MovingAverage(Source, MAPeriod, MAType); }
/// <summary> /// Calculate statistics based on sample data for the delimitter supplied /// </summary> /// <param name="data"></param> /// <param name="delimiter"></param> /// <returns></returns> private DelimiterInfo GetDelimiterInfo(string[][] data, char delimiter) { var indicators = Indicators.CalculateByDelimiter(delimiter, data, QuotedChar); return(new DelimiterInfo(delimiter, indicators.Avg, indicators.Max, indicators.Min, indicators.Deviation)); }
protected override void OnStart() { sma = Indicators.GetIndicator <SampleSMA>(Source, SmaPeriod); }
protected override void Initialize() { ma = Indicators.MovingAverage(Source1, maPeriod, MovingAverageType.Simple); }
public static decimal GetMACDComposite(JArray resultSet, int daysToCalculate) { int daysCalulated = 0; int numberOfResults = 0; HashSet <string> dates = new HashSet <string>(); Stack <decimal> macdHistYList = new Stack <decimal>(); Stack <decimal> macdBaseYList = new Stack <decimal>(); Stack <decimal> macdSignalYList = new Stack <decimal>(); decimal macdTotalHist = 0; foreach (var result in resultSet) { if (daysCalulated < daysToCalculate) { decimal macdBaseValue = decimal.Parse(result.Value <string>("macd")); decimal macdSignalValue = decimal.Parse(result.Value <string>("macd_signal")); decimal macdHistogramValue = decimal.Parse(result.Value <string>("macd_hist")); macdHistYList.Push(macdHistogramValue); macdBaseYList.Push(macdBaseValue); macdSignalYList.Push(macdSignalValue); macdTotalHist += macdHistogramValue; numberOfResults++; string resultDate = result.Value <string>("datetime"); string macdDate = DateTime.Parse(resultDate).ToString("yyyy-MM-dd"); if (!dates.Contains(macdDate)) { dates.Add(macdDate); daysCalulated++; } } else { break; } } List <decimal> macdXList = new List <decimal>(); for (int i = 1; i <= numberOfResults; i++) { macdXList.Add(i); } List <decimal> baseYList = macdBaseYList.ToList(); decimal baseSlope = Indicators.GetSlope(macdXList, baseYList); List <decimal> signalYList = macdSignalYList.ToList(); decimal signalSlope = Indicators.GetSlope(macdXList, signalYList); List <decimal> histYList = macdHistYList.ToList(); decimal histSlope = Indicators.GetSlope(macdXList, histYList); //look for buy and sell signals bool macdHasBuySignal = false; bool macdHasSellSignal = false; decimal macdPrev = histYList[0]; bool macdPrevIsNegative = macdPrev < 0; for (int i = 1; i < histYList.Count(); i++) { decimal current = histYList[i]; bool currentIsNegative = current < 0; if (!currentIsNegative && macdPrevIsNegative) { macdHasBuySignal = true; } else if (currentIsNegative && !macdPrevIsNegative) { macdHasSellSignal = true; } macdPrev = current; macdPrevIsNegative = macdPrev < 0; } decimal histSlopeMultiplier = Indicators.GetSlopeMultiplier(histSlope); decimal baseSlopeMultiplier = Indicators.GetSlopeMultiplier(baseSlope); decimal signalSlopeMultiplier = Indicators.GetSlopeMultiplier(signalSlope); decimal histBonus = Math.Min((macdTotalHist * 5) + 5, 20); //cap histBonus at 20 //calculate composite score based on the following values and weighted multipliers decimal composite = 0; composite += (histSlope > -0.05M) ? (histSlope * histSlopeMultiplier) + 25 : 0; composite += (baseSlope > -0.05M) ? (baseSlope * baseSlopeMultiplier) + 10 : 0; composite += (signalSlope > -0.05M) ? (signalSlope * signalSlopeMultiplier) + 10 : 0; composite += (histBonus > 0) ? histBonus : 0; //Add histBonus if macdTotalHist is not negative composite += (macdHasBuySignal) ? 40 : 0; composite += (macdHasSellSignal) ? -40 : 0; return(composite); }
protected override void Initialize() { bb = Indicators.BollingerBands(Source, Period, std, matype); }
protected override void Initialize() { wma = Indicators.WeightedMovingAverage(MarketSeries.Close, Period); }
public static decimal GetADXComposite(JArray resultSet, int daysToCalculate) { int daysCalulated = 0; int numberOfResults = 0; HashSet <string> dates = new HashSet <string>(); Stack <decimal> adxValueYList = new Stack <decimal>(); decimal adxTotal = 0; foreach (var result in resultSet) { if (daysCalulated < daysToCalculate) { decimal adxVal = decimal.Parse(result.Value <string>("adx")); adxValueYList.Push(adxVal); adxTotal += adxVal; numberOfResults++; string resultDate = result.Value <string>("datetime"); string adxDate = DateTime.Parse(resultDate).ToString("yyyy-MM-dd"); if (!dates.Contains(adxDate)) { dates.Add(adxDate); daysCalulated++; } } else { break; } } List <decimal> adxXList = new List <decimal>(); for (int i = 1; i <= numberOfResults; i++) { adxXList.Add(i); } List <decimal> adxYList = adxValueYList.ToList(); decimal adxSlope = Indicators.GetSlope(adxXList, adxYList); decimal adxSlopeMultiplier = Indicators.GetSlopeMultiplier(adxSlope); decimal adxAvg = adxTotal / numberOfResults; List <decimal> adxZScores = Indicators.GetZScores(adxYList); decimal zScoreSlope = Indicators.GetSlope(adxXList, adxZScores); decimal zScoreSlopeMultiplier = Indicators.GetSlopeMultiplier(zScoreSlope); //Start with the average of the 2 most recent ADX values decimal baseValue = (adxYList[adxYList.Count - 1] + adxYList[adxYList.Count - 2]) / 2; //Add based on the most recent Z Score * 100 if it is positive decimal recentZScore = adxZScores[adxZScores.Count - 1]; if (recentZScore > 0) { baseValue += (recentZScore * 100) / 2; //to even it out } else { baseValue += 10; //pity points } //Add bonus for ADX average above 25 per investopedia recommendation decimal averageBonus = adxAvg > 25 ? 25 : 0; //calculate composite score based on the following values and weighted multipliers decimal composite = 0; composite += baseValue; composite += averageBonus; composite += (adxSlope > 0.1M) ? (adxSlope * adxSlopeMultiplier) + 10 : -10; //penalty composite += (zScoreSlope > 0.1M) ? (zScoreSlope * zScoreSlopeMultiplier) + 10 : 0; return(Math.Min(composite, 100)); //cap ADX composite at 100, no extra weight }
public override void Initialize() { //initialize this entry template emaslow = Indicators.ExponentialMovingAverage(slowperiod, Agent.Stream); emafast = Indicators.ExponentialMovingAverage(fastperiod, Agent.Stream); }
public static ShortInterestResult GetShortInterest(string symbol, IEnumerable <Skender.Stock.Indicators.Quote> history, int daysToCalculate) { decimal compositeScore = 0; List <FinraRecord> shortRecords = GetShortVolume(symbol, history, daysToCalculate); int daysCalulated = 0; int numberOfResults = 0; HashSet <string> dates = new HashSet <string>(); Stack <decimal> shortInterestYList = new Stack <decimal>(); decimal shortInterestToday = 0; decimal totalVolume = 0; decimal totalVolumeShort = 0; foreach (FinraRecord shortRecord in shortRecords) { if (daysCalulated < daysToCalculate) { decimal shortVolume = shortRecord.ShortVolume + shortRecord.ShortExemptVolume; decimal shortInterest = (shortVolume / shortRecord.TotalVolume) * 100; if (numberOfResults == 0) { shortInterestToday = shortInterest; } shortInterestYList.Push(shortInterest); totalVolume += shortRecord.TotalVolume; totalVolumeShort += shortVolume; numberOfResults++; string shortDate = shortRecord.Date.ToString("yyyy-MM-dd"); if (!dates.Contains(shortDate)) { dates.Add(shortDate); daysCalulated++; } } else { break; } } List <decimal> shortXList = new List <decimal>(); for (int i = 1; i <= numberOfResults; i++) { shortXList.Add(i); } List <decimal> shortYList = shortInterestYList.ToList(); decimal shortSlope = shortYList.Count > 0 ? Indicators.GetSlope(shortXList, shortYList) : 0.0M; //set to 0 if not found decimal shortSlopeMultiplier = Indicators.GetSlopeMultiplier(shortSlope); decimal shortInterestAverage = totalVolume > 0 ? (totalVolumeShort / totalVolume) * 100 : 30.0M; //set to 30 if not found //Add these bonuses to account for normal short interest fluctuations //The slope cannot be in both ranges if the ranges do not overlap //This prevents adding both bonuses bool slightlyBearish = (SlightlyBearishLowerBound <= shortSlope && shortSlope <= SlightlyBearishUpperBound); bool moderatelyBearish = (ModeratelyBearishLowerBound <= shortSlope && shortSlope <= ModeratelyBearishUpperBound); //calculate composite score based on the following values and weighted multipliers compositeScore += 100 - shortInterestAverage; //get base score as 100 - short interest compositeScore += (shortSlope < 0) ? (shortSlope * shortSlopeMultiplier) + 10 : -15; compositeScore += (shortSlope > 0 && slightlyBearish) ? 10 : 0; compositeScore += (shortSlope > 0 && moderatelyBearish) ? 5 : 0; //Cap this compositeScore at 100 because we should not give it extra weight compositeScore = Math.Min(compositeScore, 100); //Return ShortInterestResult return(new ShortInterestResult { TotalVolume = totalVolume, TotalVolumeShort = totalVolumeShort, ShortInterestPercentToday = shortInterestToday, ShortInterestPercentAverage = shortInterestAverage, ShortInterestSlope = shortSlope, ShortInterestCompositeScore = compositeScore }); }
protected override void Initialize() { atr = Indicators.AverageTrueRange(14, MovingAverageType.Exponential); }
// Initialization logic protected override void OnStart() { rsi = Indicators.RelativeStrengthIndex(Source, Periods); sma = Indicators.SimpleMovingAverage(Source, SmaPeriod); sma2 = Indicators.SimpleMovingAverage(Source, Sma2Period); }
protected override void Initialize() { adx = Indicators.DirectionalMovementSystem(interval); }
private Indicators CalculateIndicators(char c, string[][] data) { var res = new Indicators(); int totalDelimiters = 0; int lines = 0; foreach (string[] fileData in data) { foreach (string line in fileData) { if (string.IsNullOrEmpty(line)) continue; lines++; var delimiterInLine = QuoteHelper.CountNumberOfDelimiters(line, c, QuotedChar); if (delimiterInLine > res.Max) res.Max = delimiterInLine; if (delimiterInLine < res.Min) res.Min = delimiterInLine; totalDelimiters += delimiterInLine; } } res.Avg = totalDelimiters / (double) lines; return res; }
protected override void Initialize() { _fastEma = Indicators.ExponentialMovingAverage(MarketSeries.Close, FastEMA); _slowEma = Indicators.ExponentialMovingAverage(MarketSeries.Close, SlowEMA); iRSI = Indicators.RelativeStrengthIndex(MarketSeries.Close, RSIPeriod); }
protected override void OnBar() { // This Bar is a potential Trigger Bar. MA20 = Indicators.MovingAverage(SourceSeries, 20, MAType); MA34 = Indicators.MovingAverage(SourceSeries, 34, MAType); MA27 = Indicators.MovingAverage(SourceSeries, 27, MAType); DateTime EntryExpiration = MarketSeries.OpenTime.LastValue.AddMinutes(PendingOrderEpiration); // Only run during Market Opening Times.. if (MarketSeries.OpenTime.LastValue.TimeOfDay <= new TimeSpan(8, 0, 0) & MarketSeries.OpenTime.LastValue.TimeOfDay >= new TimeSpan(11, 0, 0)) { return; } // Reasons not to take the trade: if ((MarketSeries.High.Last(1) - MarketSeries.Low.Last(1)) > 50) { Print("Signal Bar greater than 50 points, exiting..."); return; } // Reasons not to take the trade: if ((MarketSeries.High.Last(1) - MarketSeries.Low.Last(1)) < MinSignalLength) { Print("Signal Bar too small, exiting..."); return; } // Reasons not to take the trade: if (IsPreviousBarsOK() == false) { Print("Previous Bars fail"); return; } // Only look for trades if there are no existing positions open. if (Positions.Count == 0) { // Only trade if there is a sufficient Gap between MA's double MAGap = Math.Abs(MA20.Result.Last(1) - MA34.Result.Last(1)); if (MAGap >= MinMAGap) { // Only trade if Candle is touching the MA lines if (DoesCandleTouch(MarketSeries.High.Last(1), MarketSeries.Low.Last(1), MA20.Result.Last(1), MA34.Result.Last(1)) == true) { //Get Direction Of Signal Bar TradeType SignalBarDirection = TradeType.Sell; if (MarketSeries.Open.Last(1) < MarketSeries.Close.Last(1)) { SignalBarDirection = TradeType.Buy; } else { SignalBarDirection = TradeType.Sell; } Print("Bar Direction: " + SignalBarDirection.ToString()); if (IsCloseWithinPercent(MarketSeries.High.Last(1), MarketSeries.Low.Last(1), SignalBarDirection, MarketSeries.Close.Last(1)) == true) { // Rule 10: Make sure the candle is in the same direction as the trend // string Trend = GetMACDTrend(); string Trend = GetMA27Trend(); // Check for Minimum Trend Movement bool MinSignal = CheckMovment(SignalBarsBack, MinSignalEMAMovement, MaxSignalEMAMovement, "Signal Movement Result:"); if (!MinSignal) { Print("Signal movement was not sufficient."); return; } // Check for Minimum Trend Movement bool MinTrend = CheckMovment(TrendBarsBack, MinTrendEMAMovement, MaxTrendEMAMovement, "Trend Movement Result:"); if (!MinTrend) { Print("Trned movement was not sufficient."); return; } if (Trend == "UP" & SignalBarDirection == TradeType.Buy) { double EntryPrice = MarketSeries.High.Last(1) + 2; double InitialStopLoss = GetStopLoss(SignalBarDirection, EntryPrice); TradeResult CurrentOrder = PlaceLimitOrder(SignalBarDirection, Symbol, DefaultContractSize, EntryPrice, "Woo!", InitialStopLoss, InitialStopLoss, EntryExpiration); if (CurrentOrder.IsSuccessful) { Print("Buy Successful!"); } else { Print("Buy Error: " + CurrentOrder.Error.Value.ToString()); } } if (Trend == "DOWN" & SignalBarDirection == TradeType.Sell) { double EntryPrice = MarketSeries.Low.Last(1) - 2; double InitialStopLoss = GetStopLoss(SignalBarDirection, EntryPrice); TradeResult CurrentOrder = PlaceLimitOrder(SignalBarDirection, Symbol, DefaultContractSize, EntryPrice, "Woo!", InitialStopLoss, InitialStopLoss, EntryExpiration); if (CurrentOrder.IsSuccessful) { Print("Buy Successful!"); } else { Print("Buy Error: " + CurrentOrder.Error.Value.ToString()); } } } else { Print("Signal didnt close within 25% of Close."); } } else { Print("Cannot trade due to Candles dont touch"); } } else { Print("Cannot trade due to EMA Gap being too small"); } } else { Print("Cannot trade due to Open Position"); } }
protected override void OnStart() { _zigZag = Indicators.GetIndicator <ZigZag>(ZzDepth, ZzDeviation, ZzBackStep); }
public static decimal GetAROONComposite(JArray resultSet, int daysToCalculate) { int daysCalulated = 0; int numberOfResults = 0; HashSet <string> dates = new HashSet <string>(); Stack <decimal> aroonUpYList = new Stack <decimal>(); Stack <decimal> aroonDownYList = new Stack <decimal>(); Stack <decimal> aroonOscillatorYList = new Stack <decimal>(); decimal aroonUpTotal = 0; decimal aroonDownTotal = 0; foreach (var result in resultSet) { if (daysCalulated < daysToCalculate) { decimal aroonUpVal = decimal.Parse(result.Value <string>("aroon_up")); decimal aroonDownVal = decimal.Parse(result.Value <string>("aroon_down")); aroonUpYList.Push(aroonUpVal); aroonDownYList.Push(aroonDownVal); aroonOscillatorYList.Push(aroonUpVal - aroonDownVal); aroonUpTotal += aroonUpVal; aroonDownTotal += aroonDownVal; numberOfResults++; string resultDate = result.Value <string>("datetime"); string aroonDate = DateTime.Parse(resultDate).ToString("yyyy-MM-dd"); if (!dates.Contains(aroonDate)) { dates.Add(aroonDate); daysCalulated++; } } else { break; } } List <decimal> aroonXList = new List <decimal>(); for (int i = 1; i <= numberOfResults; i++) { aroonXList.Add(i); } List <decimal> upYList = aroonUpYList.ToList(); decimal upSlope = Indicators.GetSlope(aroonXList, upYList); List <decimal> downYList = aroonDownYList.ToList(); decimal downSlope = Indicators.GetSlope(aroonXList, downYList); List <decimal> oscillatorYList = aroonOscillatorYList.ToList(); //decimal oscillatorSlope = GetSlope(aroonXList, oscillatorYList); decimal upSlopeMultiplier = Indicators.GetSlopeMultiplier(upSlope); decimal downSlopeMultiplier = Indicators.GetSlopeMultiplier(downSlope); //decimal oscillatorSlopeMultiplier = GetSlopeMultiplier(oscillatorSlope); //look for buy and sell signals bool aroonHasBuySignal = false; bool aroonHasSellSignal = false; decimal previousOscillatorValue = oscillatorYList[0]; bool previousIsNegative = previousOscillatorValue <= 0; for (int i = 1; i < oscillatorYList.Count(); i++) { decimal currentOscillatorValue = oscillatorYList[i]; bool currentIsNegative = currentOscillatorValue <= 0; if (!currentIsNegative && previousIsNegative && (upYList[i] >= 30 && downYList[i] <= 70)) { aroonHasBuySignal = true; } else if (currentIsNegative && !previousIsNegative && (upYList[i] <= 30 && downYList[i] >= 70)) { aroonHasSellSignal = true; } previousOscillatorValue = currentOscillatorValue; previousIsNegative = previousOscillatorValue <= 0; } decimal aroonAvgUp = Math.Max(aroonUpTotal / numberOfResults, 1.0M); decimal aroonAvgDown = Math.Max(aroonDownTotal / numberOfResults, 1.0M); decimal percentDiffDown = (aroonAvgDown / aroonAvgUp) * 100; decimal percentDiffUp = (aroonAvgUp / aroonAvgDown) * 100; decimal bullResult = Math.Min(100 - percentDiffDown, 50); //bull result caps at 50 decimal bearResult = Math.Min(percentDiffUp + 15, 20); //bear result caps at 20 //Add bull bonus if last AROON UP >= 70 per investopedia recommendation //This is the same as when last AROON OSC >= 50 //Cap bullBonus at 15 decimal bullBonus = (aroonAvgUp > aroonAvgDown && previousOscillatorValue >= 50) ? Math.Min(previousOscillatorValue / 5, 15) : 0; //Add bear bonus if last AROON UP > last AROON DOWN per investopedia recommendation //This is the same as when last AROON OSC > 0 //Cap bearBonus at 10 decimal bearBonus = (aroonAvgDown > aroonAvgUp && previousOscillatorValue > 0) ? Math.Min(previousOscillatorValue / 5, 10) : 0; //calculate composite score based on the following values and weighted multipliers //if AROON avg up > AROON avg down, start score with 100 - (down as % of up) //if AROON avg up < AROON avg down, start score with 100 - (up as % of down) decimal composite = 0; composite += (aroonAvgUp > aroonAvgDown) ? bullResult : bearResult; composite += (bullBonus > bearBonus) ? bullBonus : bearBonus; composite += (upSlope > -0.05M) ? (upSlope * upSlopeMultiplier) + 5 : 0; composite += (downSlope < 0.05M) ? (downSlope * downSlopeMultiplier) + 5 : -(downSlope * downSlopeMultiplier); composite += (aroonHasBuySignal) ? 25 : 0; composite += (aroonHasSellSignal) ? -25 : 0; return(composite); }
private List <DelimiterInfo> GetDelimiters(string[][] data) { var frequency = new Dictionary <char, int>(); int lines = 0; for (int i = 0; i < data.Length; i++) { for (int j = 0; j < data[i].Length; j++) { // Ignore Header Line (if any) if (j == 0) { continue; } // ignore empty lines string line = data[i][j]; if (string.IsNullOrEmpty(line)) { continue; } // analyse line lines++; for (int ci = 0; ci < line.Length; ci++) { char c = line[ci]; if (char.IsLetterOrDigit(c) || c == ' ') { continue; } int count; if (frequency.TryGetValue(c, out count)) { count++; frequency[c] = count; } else { frequency.Add(c, 1); } } } } var candidates = new List <DelimiterInfo>(); // sanity check if (lines == 0) { return(candidates); } // remove delimiters with low occurrence count var delimiters = new List <char> (frequency.Count); foreach (var pair in frequency) { if (pair.Value >= lines) { delimiters.Add(pair.Key); } } // calculate foreach (var key in delimiters) { var indicators = Indicators.CalculateByDelimiter(key, data, QuotedChar); // Adjust based on the number of lines if (lines < MinSampleData) { indicators.Deviation = indicators.Deviation * Math.Min(1, ((double)lines) / MinSampleData); } if (indicators.Avg > 1 && indicators.Deviation < MinDelimitedDeviation) { candidates.Add(new DelimiterInfo(key, indicators.Avg, indicators.Max, indicators.Min, indicators.Deviation)); } } return(candidates); }
//unused for now public static decimal GetOBVComposite(JArray resultSet, int daysToCalculate) { int daysCalulated = 0; int numberOfResults = 0; HashSet <string> dates = new HashSet <string>(); Stack <decimal> obvValueYList = new Stack <decimal>(); decimal obvSum = 0; foreach (var result in resultSet) { if (daysCalulated < daysToCalculate) { decimal obvValue = decimal.Parse(result.Value <string>("obv")); obvValueYList.Push(obvValue); obvSum += obvValue; numberOfResults++; string resultDate = result.Value <string>("datetime"); string obvDate = DateTime.Parse(resultDate).ToString("yyyy-MM-dd"); if (!dates.Contains(obvDate)) { dates.Add(obvDate); daysCalulated++; } } else { break; } } List <decimal> obvXList = new List <decimal>(); for (int i = 1; i <= numberOfResults; i++) { obvXList.Add(i); } List <decimal> obvYList = obvValueYList.ToList(); decimal obvSlope = Indicators.GetSlope(obvXList, obvYList); decimal obvSlopeMultiplier = Indicators.GetSlopeMultiplier(obvSlope); List <decimal> zScores = Indicators.GetZScores(obvYList); decimal zScoreSlope = Indicators.GetSlope(zScores, obvXList); decimal zScoreSlopeMultiplier = Indicators.GetSlopeMultiplier(zScoreSlope); List <decimal> normalizedScores = Indicators.GetNormalizedData(obvYList); decimal normalizedSlope = Indicators.GetSlope(normalizedScores, obvXList); decimal normalizedSlopeMultiplier = Indicators.GetSlopeMultiplier(normalizedSlope); decimal obvAverage = obvSum / numberOfResults; //look for buy and sell signals bool obvHasBuySignal = false; bool obvHasSellSignal = false; decimal obvPrev = obvYList[0]; bool obvPrevIsNegative = obvPrev < 0; for (int i = 1; i < obvYList.Count(); i++) { decimal current = obvYList[i]; bool currentIsNegative = current < 0; if (!currentIsNegative && obvPrevIsNegative) { obvHasBuySignal = true; if (obvHasSellSignal) { obvHasSellSignal = false; //cancel the previous sell signal if buy signal is most recent } } else if (currentIsNegative && !obvPrevIsNegative) { obvHasSellSignal = true; if (obvHasBuySignal) { obvHasBuySignal = false; //cancel the previous buy signal if sell signal is most recent } } obvPrev = current; obvPrevIsNegative = obvPrev < 0; } //Start with the average of the 2 most recent OBV Normalized Scores //Only use the normalized scores if average OBV is greater than 0 decimal baseValue; if (obvAverage > 0) { baseValue = ((normalizedScores[normalizedScores.Count - 1] + normalizedScores[normalizedScores.Count - 2]) / 2) * 100; } else { //ZScore bonus helps us score based on derivatives //Only add ZScoreBonus if it is positive, divide by 4 instead of 2 (which would be classic mean) decimal zScoreBonus = ((zScores[zScores.Count - 1] + zScores[zScores.Count - 2]) / 4) * 100; if (zScoreBonus < 0) { zScoreBonus = 15; //pity points } baseValue = zScoreBonus; } //Add bonus if average OBV is greater than 0 decimal obvAverageBonus = obvAverage > 0 ? 15 : 0; //Add bonus if OBV slope positive decimal obvSlopeBonus = (obvSlope > 0) ? 10 : 0; //calculate composite score based on the following values and weighted multipliers decimal composite = 0; composite += baseValue; composite += obvAverageBonus; composite += obvSlopeBonus; composite += (zScoreSlope > 0) ? (zScoreSlope * zScoreSlopeMultiplier) : 0; composite += (normalizedSlope > 0) ? (normalizedSlope * normalizedSlopeMultiplier) : 0; composite += (obvHasBuySignal) ? 15 : 0; composite += (obvHasSellSignal) ? -15 : 0; return(Math.Min(composite, 100)); //cap OBV composite at 100, no extra weight }
public State ProcessNext(PointF next) { var currentDateTime = _currentTime(); if (StartTime == default(DateTime)) StartTime = currentDateTime; EndTime = currentDateTime; AvgCenter = new PointF( AvgCenter.X * Count / (Count + 1) + next.X / (Count + 1), AvgCenter.Y * Count / (Count + 1) + next.Y / (Count + 1) ); MaxCenter = new PointF(Math.Max(MaxCenter.X, next.X), Math.Max(MaxCenter.Y, next.Y)); MinCenter = new PointF(Math.Min(MaxCenter.X, next.X), Math.Min(MaxCenter.Y, next.Y)); if (LastCenter.HasValue) { if (LastCenter.Value.X < AvgCenter.X && AvgCenter.X <= next.X) { XAmplitudes.Add(Math.Abs(MinCenter.X - -AvgCenter.X)* 2); MinCenter = new PointF(AvgCenter.X, MinCenter.Y); } if (LastCenter.Value.X > AvgCenter.X && AvgCenter.X >= next.X) { XAmplitudes.Add(Math.Abs(MaxCenter.X - AvgCenter.X) *2); MaxCenter = new PointF(AvgCenter.X, MaxCenter.Y); } if (LastCenter.Value.Y < AvgCenter.Y && AvgCenter.Y <= next.Y) { YAmplitudes.Add(Math.Abs(MinCenter.Y - AvgCenter.Y)*2); MinCenter = new PointF(MinCenter.X, AvgCenter.Y); } if (LastCenter.Value.Y > AvgCenter.Y && AvgCenter.Y >= next.Y) { YAmplitudes.Add(Math.Abs(MaxCenter.Y - AvgCenter.Y)*2); MaxCenter = new PointF(MaxCenter.X, AvgCenter.Y); } } var length = LastCenter.HasValue ? Indicators.Length + next.DistanceTo(LastCenter.Value) : Indicators.Length; var frequencyX = XAmplitudes.Count / (EndTime - StartTime).TotalSeconds; var frequencyY = YAmplitudes.Count / (EndTime - StartTime).TotalSeconds; var periodX = XAmplitudes.Count == 0 ? 0 : 1 / frequencyX; var periodY = YAmplitudes.Count == 0 ? 0 : 1 / frequencyY; Indicators = new Indicators { Length = length, Frequency = new PointF((float)frequencyX, (float)frequencyY), Period = new PointF((float)periodX, (float)periodY), AvgAmplitude = new PointF( XAmplitudes.Count == 0 ? 0f : (float)XAmplitudes.Average(), YAmplitudes.Count == 0 ? 0f : (float)YAmplitudes.Average()), MaxAmplitude = new PointF( XAmplitudes.Count == 0 ? 0f : (float)XAmplitudes.Max(), YAmplitudes.Count == 0 ? 0f : (float)YAmplitudes.Max()) }; Count = Count + 1; LastCenter = next; return this; }
private void ModelChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "Rigs": { Rigs = new ObservableCollection <Settings.Rig>(_model.Rigs); RigsNames = from r in Rigs orderby r.Index select r.Name; for (int i = 0; i < RigsNames.Count(); i++) { Indicators.Add(RigStatus.offline); Watch.Add(Rigs[i].Waching); { if (Rigs[i].Waching) { AddRigPanel(i); } else { RemoveRigPanel(i); } } } } break; case "PoolsSets": { for (int i = 0; i < _model.PoolsSets.Count; i++) { Selection.Add(false); PoolsSets.Add(_model.PoolsSets[i]); if (_model.PoolsSets[i].Wach) { WachPoolStart(i); } } } break; case "GenSettings": { GenSettings = _model.GenSettings; StartOfRange = GenSettings.TotalMinTemp; StartOfRangeD = GenSettings.TotalMinTemp; EndOfRange = GenSettings.TotalMaxTemp; EndOfRangeD = GenSettings.TotalMaxTemp; eWeLogin = GenSettings.eWeLogin; eWePasswordSend = GenSettings.eWePassword; if (!String.IsNullOrEmpty(eWeLogin) && !String.IsNullOrEmpty(eWePasswordSend)) { Task.Run(() => eWeConnect()); } Task.Run(() => { if (!string.IsNullOrEmpty(GenSettings.HiveLogin) && !string.IsNullOrEmpty(GenSettings.HivePassword)) { AuthenticationStatus st = HiveClient.HiveAuthentication( GenSettings.HiveLogin, GenSettings.HivePassword); if (st.Status) { HiveLogin = GenSettings.HiveLogin; HivePasswordSend = GenSettings.HivePassword; HiveConnection = true; App.HiveConnection = true; HiveAccountState = "Подключение к Hive установлено"; HiveConnectionState = "Подключение к Hive установлено"; HiveWorkers = HiveClient.GetWorkers(); if (HiveWorkers != null) { List <string> LST = (from w in HiveWorkers select w.name).ToList(); LST.Insert(0, "---"); HiveWorkersNames = LST; } } else { HiveAccountState = st.Message; } } else { HiveAccountState = "Подключение к Hive отсутствует"; HiveConnectionState = "Подключение к Hive отсутствует"; } }); VKuserID = GenSettings.VKuserID; } break; } }
public static Indicators CalculateByDelimiter(char delimiter, string[][] data, char? quotedChar) { var res = new Indicators (); int totalDelimiters = 0; int lines = 0; List<int> delimiterPerLine = new List<int> (100); foreach (var fileData in data) { foreach (var line in fileData) { if (string.IsNullOrEmpty (line)) continue; lines++; var delimiterInLine = 0; if (quotedChar.HasValue) delimiterInLine = QuoteHelper.CountNumberOfDelimiters (line, delimiter, quotedChar.Value); else delimiterInLine = CountNumberOfDelimiters (line, delimiter); // add count for deviation analysis delimiterPerLine.Add (delimiterInLine); if (delimiterInLine > res.Max) res.Max = delimiterInLine; if (delimiterInLine < res.Min) res.Min = delimiterInLine; totalDelimiters += delimiterInLine; } } res.Avg = totalDelimiters / (double)lines; // calculate deviation res.Deviation = CalculateDeviation (delimiterPerLine, res.Avg); return res; }
/// <summary> /// Double MA /// </summary> /// <returns></returns> public DoubleMA DoubleMA(Data.IDataSeries input, double angle, int arrowDisplacement, Color barColorDown, Color barColorNeutral, Color barColorUp, int mA1Period, MAV.MAType mA1Type, int mA2Period, MAV.MAType mA2Type, bool paintBar, bool showArrows, bool soundOn, string wavLongFileName, string wavShortFileName) { if (cacheDoubleMA != null) { for (int idx = 0; idx < cacheDoubleMA.Length; idx++) { if (Math.Abs(cacheDoubleMA[idx].Angle - angle) <= double.Epsilon && cacheDoubleMA[idx].ArrowDisplacement == arrowDisplacement && cacheDoubleMA[idx].BarColorDown == barColorDown && cacheDoubleMA[idx].BarColorNeutral == barColorNeutral && cacheDoubleMA[idx].BarColorUp == barColorUp && cacheDoubleMA[idx].MA1Period == mA1Period && cacheDoubleMA[idx].MA1Type == mA1Type && cacheDoubleMA[idx].MA2Period == mA2Period && cacheDoubleMA[idx].MA2Type == mA2Type && cacheDoubleMA[idx].PaintBar == paintBar && cacheDoubleMA[idx].ShowArrows == showArrows && cacheDoubleMA[idx].SoundOn == soundOn && cacheDoubleMA[idx].WavLongFileName == wavLongFileName && cacheDoubleMA[idx].WavShortFileName == wavShortFileName && cacheDoubleMA[idx].EqualsInput(input)) { return(cacheDoubleMA[idx]); } } } lock (checkDoubleMA) { checkDoubleMA.Angle = angle; angle = checkDoubleMA.Angle; checkDoubleMA.ArrowDisplacement = arrowDisplacement; arrowDisplacement = checkDoubleMA.ArrowDisplacement; checkDoubleMA.BarColorDown = barColorDown; barColorDown = checkDoubleMA.BarColorDown; checkDoubleMA.BarColorNeutral = barColorNeutral; barColorNeutral = checkDoubleMA.BarColorNeutral; checkDoubleMA.BarColorUp = barColorUp; barColorUp = checkDoubleMA.BarColorUp; checkDoubleMA.MA1Period = mA1Period; mA1Period = checkDoubleMA.MA1Period; checkDoubleMA.MA1Type = mA1Type; mA1Type = checkDoubleMA.MA1Type; checkDoubleMA.MA2Period = mA2Period; mA2Period = checkDoubleMA.MA2Period; checkDoubleMA.MA2Type = mA2Type; mA2Type = checkDoubleMA.MA2Type; checkDoubleMA.PaintBar = paintBar; paintBar = checkDoubleMA.PaintBar; checkDoubleMA.ShowArrows = showArrows; showArrows = checkDoubleMA.ShowArrows; checkDoubleMA.SoundOn = soundOn; soundOn = checkDoubleMA.SoundOn; checkDoubleMA.WavLongFileName = wavLongFileName; wavLongFileName = checkDoubleMA.WavLongFileName; checkDoubleMA.WavShortFileName = wavShortFileName; wavShortFileName = checkDoubleMA.WavShortFileName; if (cacheDoubleMA != null) { for (int idx = 0; idx < cacheDoubleMA.Length; idx++) { if (Math.Abs(cacheDoubleMA[idx].Angle - angle) <= double.Epsilon && cacheDoubleMA[idx].ArrowDisplacement == arrowDisplacement && cacheDoubleMA[idx].BarColorDown == barColorDown && cacheDoubleMA[idx].BarColorNeutral == barColorNeutral && cacheDoubleMA[idx].BarColorUp == barColorUp && cacheDoubleMA[idx].MA1Period == mA1Period && cacheDoubleMA[idx].MA1Type == mA1Type && cacheDoubleMA[idx].MA2Period == mA2Period && cacheDoubleMA[idx].MA2Type == mA2Type && cacheDoubleMA[idx].PaintBar == paintBar && cacheDoubleMA[idx].ShowArrows == showArrows && cacheDoubleMA[idx].SoundOn == soundOn && cacheDoubleMA[idx].WavLongFileName == wavLongFileName && cacheDoubleMA[idx].WavShortFileName == wavShortFileName && cacheDoubleMA[idx].EqualsInput(input)) { return(cacheDoubleMA[idx]); } } } DoubleMA indicator = new DoubleMA(); indicator.BarsRequired = BarsRequired; indicator.CalculateOnBarClose = CalculateOnBarClose; #if NT7 indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256; indicator.MaximumBarsLookBack = MaximumBarsLookBack; #endif indicator.Input = input; indicator.Angle = angle; indicator.ArrowDisplacement = arrowDisplacement; indicator.BarColorDown = barColorDown; indicator.BarColorNeutral = barColorNeutral; indicator.BarColorUp = barColorUp; indicator.MA1Period = mA1Period; indicator.MA1Type = mA1Type; indicator.MA2Period = mA2Period; indicator.MA2Type = mA2Type; indicator.PaintBar = paintBar; indicator.ShowArrows = showArrows; indicator.SoundOn = soundOn; indicator.WavLongFileName = wavLongFileName; indicator.WavShortFileName = wavShortFileName; Indicators.Add(indicator); indicator.SetUp(); DoubleMA[] tmp = new DoubleMA[cacheDoubleMA == null ? 1 : cacheDoubleMA.Length + 1]; if (cacheDoubleMA != null) { cacheDoubleMA.CopyTo(tmp, 0); } tmp[tmp.Length - 1] = indicator; cacheDoubleMA = tmp; return(indicator); } }
protected virtual void CollectMetaData(Indicators.Meta meta) { }
protected override void Initialize() { RSI = Indicators.RelativeStrengthIndex(MarketSeries.Close, Period); ATR = Indicators.AverageTrueRange(14, MovingAverageType.Simple); count = MarketSeries.Open.Count; }
/// <summary> /// a band around an MA /// </summary> /// <returns></returns> public zMovingAverageBand zMovingAverageBand(Data.IDataSeries input, double bandArg, int bandSmoothArg, RWT_MA.MAType bandSmoothType, RWT_Bands.BandType bandType, int lengthOfBand, int smoothArg, RWT_MA.MAType smoothType) { if (cachezMovingAverageBand != null) { for (int idx = 0; idx < cachezMovingAverageBand.Length; idx++) { if (Math.Abs(cachezMovingAverageBand[idx].BandArg - bandArg) <= double.Epsilon && cachezMovingAverageBand[idx].BandSmoothArg == bandSmoothArg && cachezMovingAverageBand[idx].BandSmoothType == bandSmoothType && cachezMovingAverageBand[idx].BandType == bandType && cachezMovingAverageBand[idx].LengthOfBand == lengthOfBand && cachezMovingAverageBand[idx].SmoothArg == smoothArg && cachezMovingAverageBand[idx].SmoothType == smoothType && cachezMovingAverageBand[idx].EqualsInput(input)) { return(cachezMovingAverageBand[idx]); } } } lock (checkzMovingAverageBand) { checkzMovingAverageBand.BandArg = bandArg; bandArg = checkzMovingAverageBand.BandArg; checkzMovingAverageBand.BandSmoothArg = bandSmoothArg; bandSmoothArg = checkzMovingAverageBand.BandSmoothArg; checkzMovingAverageBand.BandSmoothType = bandSmoothType; bandSmoothType = checkzMovingAverageBand.BandSmoothType; checkzMovingAverageBand.BandType = bandType; bandType = checkzMovingAverageBand.BandType; checkzMovingAverageBand.LengthOfBand = lengthOfBand; lengthOfBand = checkzMovingAverageBand.LengthOfBand; checkzMovingAverageBand.SmoothArg = smoothArg; smoothArg = checkzMovingAverageBand.SmoothArg; checkzMovingAverageBand.SmoothType = smoothType; smoothType = checkzMovingAverageBand.SmoothType; if (cachezMovingAverageBand != null) { for (int idx = 0; idx < cachezMovingAverageBand.Length; idx++) { if (Math.Abs(cachezMovingAverageBand[idx].BandArg - bandArg) <= double.Epsilon && cachezMovingAverageBand[idx].BandSmoothArg == bandSmoothArg && cachezMovingAverageBand[idx].BandSmoothType == bandSmoothType && cachezMovingAverageBand[idx].BandType == bandType && cachezMovingAverageBand[idx].LengthOfBand == lengthOfBand && cachezMovingAverageBand[idx].SmoothArg == smoothArg && cachezMovingAverageBand[idx].SmoothType == smoothType && cachezMovingAverageBand[idx].EqualsInput(input)) { return(cachezMovingAverageBand[idx]); } } } zMovingAverageBand indicator = new zMovingAverageBand(); indicator.BarsRequired = BarsRequired; indicator.CalculateOnBarClose = CalculateOnBarClose; #if NT7 indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256; indicator.MaximumBarsLookBack = MaximumBarsLookBack; #endif indicator.Input = input; indicator.BandArg = bandArg; indicator.BandSmoothArg = bandSmoothArg; indicator.BandSmoothType = bandSmoothType; indicator.BandType = bandType; indicator.LengthOfBand = lengthOfBand; indicator.SmoothArg = smoothArg; indicator.SmoothType = smoothType; Indicators.Add(indicator); indicator.SetUp(); zMovingAverageBand[] tmp = new zMovingAverageBand[cachezMovingAverageBand == null ? 1 : cachezMovingAverageBand.Length + 1]; if (cachezMovingAverageBand != null) { cachezMovingAverageBand.CopyTo(tmp, 0); } tmp[tmp.Length - 1] = indicator; cachezMovingAverageBand = tmp; return(indicator); } }
protected override void CollectMetaData(Indicators.Meta meta) { double val = 0; double[] paras = new double[paramGrid.Rows.Count]; for (int idx = 0; idx < paramGrid.Rows.Count; idx++) { paras[idx] = (double.TryParse(paramGrid[1, idx].Value.ToString(), out val) ? val : 0); } meta.Parameters = paras; Indicators.Meta.OutputInfo[] outPut = new Indicators.Meta.OutputInfo[outputGrid.Rows.Count]; for (int idx = 0; idx < outputGrid.Rows.Count; idx++) { outPut[idx] = new Indicators.Meta.OutputInfo((Color)outputGrid[outColorColumn.Name, idx].Value, int.Parse(outputGrid[outWeightColumn.Name, idx].Value.ToString()), (AppTypes.ChartTypes)outputGrid[outChartTypeColumn.Name, idx].Value); } meta.Output = outPut; meta.DrawInNewWindow = inNewPaneChk.Checked; if (cbbWindow.SelectedItem.ToString().Equals(Languages.Libs.GetString("newPanel"))) { meta.SelectedWindowName =meta.ListWindowNames[constPaneNameNew].ToString(); } else if (cbbWindow.SelectedItem.ToString().Equals(Languages.Libs.GetString("pricePanel"))) { meta.SelectedWindowName = meta.ListWindowNames[constPaneNamePrice].ToString(); } else { meta.SelectedWindowName = meta.ListWindowNames[cbbWindow.SelectedItem.ToString()].ToString(); } }
/// <summary> /// Tools4Trading: True SpreadSymbolChart, full tickbased and syncronized for any (intraday) BarTypes /// </summary> /// <returns></returns> public t4tSpreadSym t4tSpreadSym(Data.IDataSeries input, t4t.SpreadSymResult spreadSymResult, double sSfactor1, double sSfactor2, string sSfullName1, string sSfullName2) { if (cachet4tSpreadSym != null) { for (int idx = 0; idx < cachet4tSpreadSym.Length; idx++) { if (cachet4tSpreadSym[idx].SpreadSymResult == spreadSymResult && Math.Abs(cachet4tSpreadSym[idx].SSfactor1 - sSfactor1) <= double.Epsilon && Math.Abs(cachet4tSpreadSym[idx].SSfactor2 - sSfactor2) <= double.Epsilon && cachet4tSpreadSym[idx].SSfullName1 == sSfullName1 && cachet4tSpreadSym[idx].SSfullName2 == sSfullName2 && cachet4tSpreadSym[idx].EqualsInput(input)) { return(cachet4tSpreadSym[idx]); } } } lock (checkt4tSpreadSym) { checkt4tSpreadSym.SpreadSymResult = spreadSymResult; spreadSymResult = checkt4tSpreadSym.SpreadSymResult; checkt4tSpreadSym.SSfactor1 = sSfactor1; sSfactor1 = checkt4tSpreadSym.SSfactor1; checkt4tSpreadSym.SSfactor2 = sSfactor2; sSfactor2 = checkt4tSpreadSym.SSfactor2; checkt4tSpreadSym.SSfullName1 = sSfullName1; sSfullName1 = checkt4tSpreadSym.SSfullName1; checkt4tSpreadSym.SSfullName2 = sSfullName2; sSfullName2 = checkt4tSpreadSym.SSfullName2; if (cachet4tSpreadSym != null) { for (int idx = 0; idx < cachet4tSpreadSym.Length; idx++) { if (cachet4tSpreadSym[idx].SpreadSymResult == spreadSymResult && Math.Abs(cachet4tSpreadSym[idx].SSfactor1 - sSfactor1) <= double.Epsilon && Math.Abs(cachet4tSpreadSym[idx].SSfactor2 - sSfactor2) <= double.Epsilon && cachet4tSpreadSym[idx].SSfullName1 == sSfullName1 && cachet4tSpreadSym[idx].SSfullName2 == sSfullName2 && cachet4tSpreadSym[idx].EqualsInput(input)) { return(cachet4tSpreadSym[idx]); } } } t4tSpreadSym indicator = new t4tSpreadSym(); indicator.BarsRequired = BarsRequired; indicator.CalculateOnBarClose = CalculateOnBarClose; #if NT7 indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256; indicator.MaximumBarsLookBack = MaximumBarsLookBack; #endif indicator.Input = input; indicator.SpreadSymResult = spreadSymResult; indicator.SSfactor1 = sSfactor1; indicator.SSfactor2 = sSfactor2; indicator.SSfullName1 = sSfullName1; indicator.SSfullName2 = sSfullName2; Indicators.Add(indicator); indicator.SetUp(); t4tSpreadSym[] tmp = new t4tSpreadSym[cachet4tSpreadSym == null ? 1 : cachet4tSpreadSym.Length + 1]; if (cachet4tSpreadSym != null) { cachet4tSpreadSym.CopyTo(tmp, 0); } tmp[tmp.Length - 1] = indicator; cachet4tSpreadSym = tmp; return(indicator); } }
public static Indicators CalculateAsFixedSize(string[][] data) { var res = new Indicators (); double sum = 0; int lines = 0; List<int> sizePerLine = new List<int> (100); foreach (var fileData in data) { foreach (var line in fileData) { if (string.IsNullOrEmpty (line)) continue; lines++; sum += line.Length; sizePerLine.Add (line.Length); if (line.Length > res.Max) res.Max = line.Length; if (line.Length < res.Min) res.Min = line.Length; } } res.Avg = sum / (double)lines; // calculate deviation res.Deviation = CalculateDeviation (sizePerLine, res.Avg); return res; }
protected override void Initialize() { atr = Indicators.AverageTrueRange(MarketData.GetSeries(AtrTimeFrame), AtrPeriod, AtrMaType); }
public baseIndicatorForm(Indicators.Meta meta) { InitializeComponent(); Indicators.Libs.GetUserSettings(meta); this.FormMeta = meta; }
protected override void Initialize() { _calculateValue = TimeFrame == "calculateValue"; _trend = new int[MarketSeries.Close.Count]; _atr = Indicators.GetIndicator <AverageTrueRange>(ATRPeriod); }
protected override void Initialize() { _bollingerBands = Indicators.BollingerBands(Source, Period, K, MaType); }
protected override void Initialize() { // Initialize and create nested indicators peakTroughtFinder = Indicators.GetIndicator <PeakTroughtFinder>(true, 10, 10); utils = new Utils(); }
/// <summary> /// Initialize the data and resolution you require for your strategy /// </summary> public override void Initialize() { //Initialize SetStartDate(2013, 1, 1); SetEndDate(2014, 12, 31); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute); //Add the Custom Data: AddData<Bitcoin>("BTC"); //Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object) _indicators = new Indicators { BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily), RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily), ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily), EMA = EMA(_symbol, 14, Resolution.Daily), SMA = SMA(_symbol, 14, Resolution.Daily), MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily), AROON = AROON(_symbol, 20, Resolution.Daily), MOM = MOM(_symbol, 20, Resolution.Daily), MOMP = MOMP(_symbol, 20, Resolution.Daily), STD = STD(_symbol, 20, Resolution.Daily), MIN = MIN(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the min of the low property MAX = MAX(_symbol, 14, Resolution.Daily) // by default if the symbol is a tradebar type then it will be the max of the high property }; // Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator // These functions have a signature like the following: decimal Selector(BaseData baseData), and can be defined like: baseData => baseData.Value // We'll define these 'selector' functions to select the Low value // // For more information on 'anonymous functions' see: http://en.wikipedia.org/wiki/Anonymous_function // https://msdn.microsoft.com/en-us/library/bb397687.aspx // _selectorIndicators = new Indicators { BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily, Field.Low), RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, Field.Low), EMA = EMA(_symbol, 14, Resolution.Daily, Field.Low), SMA = SMA(_symbol, 14, Resolution.Daily, Field.Low), MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily, Field.Low), MOM = MOM(_symbol, 20, Resolution.Daily, Field.Low), MOMP = MOMP(_symbol, 20, Resolution.Daily, Field.Low), STD = STD(_symbol, 20, Resolution.Daily, Field.Low), MIN = MIN(_symbol, 14, Resolution.Daily, Field.High), // this will find the 14 day min of the high property MAX = MAX(_symbol, 14, Resolution.Daily, Field.Low), // this will find the 14 day max of the low property // ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar // before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, SelectorDoubleTradeBar), AROON = AROON(_symbol, 20, Resolution.Daily, SelectorDoubleTradeBar) }; //Custom Data Indicator: _rsiCustom = RSI(_customSymbol, 14, MovingAverageType.Simple, Resolution.Daily); _minCustom = MIN(_customSymbol, 14, Resolution.Daily); _maxCustom = MAX(_customSymbol, 14, Resolution.Daily); // in addition to defining indicators on a single security, you can all define 'composite' indicators. // these are indicators that require multiple inputs. the most common of which is a ratio. // suppose we seek the ratio of BTC to SPY, we could write the following: var spyClose = Identity(_symbol); var btcClose = Identity(_customSymbol); // this will create a new indicator whose value is BTC/SPY _ratio = btcClose.Over(spyClose); // we can also easily plot our indicators each time they update using th PlotIndicator function PlotIndicator("Ratio", _ratio); }
public static CompositeScoreResult GetCompositeScoreResult(string symbol, Security quote) { string adxResponse = CompleteTwelveDataRequest("ADX", symbol).Result; decimal adxCompositeScore = GetCompositeScore(symbol, "ADX", adxResponse, 7); //string obvResponse = CompleteTwelveDataRequest("OBV", symbol).Result; //decimal obvCompositeScore = GetCompositeScore("OBV", obvResponse, 7); string aroonResponse = CompleteTwelveDataRequest("AROON", symbol).Result; decimal aroonCompositeScore = GetCompositeScore(symbol, "AROON", aroonResponse, 7); string macdResponse = CompleteTwelveDataRequest("MACD", symbol).Result; decimal macdCompositeScore = GetCompositeScore(symbol, "MACD", macdResponse, 7); ShortInterestResult shortResult = new ShortInterestResult(); //FINRA.GetShortInterest(symbol, 7); FundamentalsResult fundResult = Indicators.GetFundamentals(symbol, quote); TipRanksResult trResult = TipRanks.GetTipRanksResult(symbol); CompositeScoreResult scoreResult = new CompositeScoreResult { Symbol = symbol, DataProviders = "TwelveData, FINRA, YahooFinance, TipRanks", ADXComposite = adxCompositeScore, //OBVComposite = obvCompositeScore, AROONComposite = aroonCompositeScore, MACDComposite = macdCompositeScore, RatingsComposite = trResult.RatingsComposite, ShortInterestComposite = shortResult.ShortInterestCompositeScore, FundamentalsComposite = fundResult.FundamentalsComposite, CompositeScoreValue = (adxCompositeScore + /*obvCompositeScore +*/ aroonCompositeScore + macdCompositeScore + shortResult.ShortInterestCompositeScore + fundResult.FundamentalsComposite + trResult.RatingsComposite) / 6, ShortInterest = shortResult, Fundamentals = fundResult, TipRanks = trResult }; string rank = string.Empty; if (scoreResult.Fundamentals.IsBlacklisted) { rank = "DISQUALIFIED"; } else if (scoreResult.CompositeScoreValue > 0 && scoreResult.CompositeScoreValue < 60) { rank = "BAD"; } else if (scoreResult.CompositeScoreValue >= 60 && scoreResult.CompositeScoreValue < 70) { rank = "FAIR"; } else if (scoreResult.CompositeScoreValue >= 70 && scoreResult.CompositeScoreValue < 80) { rank = "GOOD"; } else if (scoreResult.CompositeScoreValue >= 80) { rank = "PRIME"; } scoreResult.CompositeRank = rank; return(scoreResult); }
public baseIndicatorForm(Indicators.Meta meta) { InitializeComponent(); Indicators.Libs.GetLocalConfig(meta); this.FormMeta = meta; }
protected override void OnStart() { rsi = Indicators.RelativeStrengthIndex(Source, Periods); }