protected override void Create() { // 初始化下單物件,Contracts.UserSpecified 可指定規模,OrderExit.FromAll 可一次全平 BUY = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.UserSpecified, EOrderAction.Buy, OrderExit.FromAll)); SELL = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.UserSpecified, EOrderAction.SellShort, OrderExit.FromAll)); BUY_C = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.Default, EOrderAction.Sell, OrderExit.FromAll)); SELL_C = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.Default, EOrderAction.BuyToCover, OrderExit.FromAll)); __cKD = new KD(this); __cMACD = new MACD(this); }
protected override void Create() { m_MACD = new MACD(this); m_XAverage = new XAverage(this); m_my_MACD = new VariableSeries<Double>(this); m_MACD_diff = new VariableSeries<Double>(this); m_MacdSE = OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, "MacdSE", EOrderAction.SellShort)); }
public void MACD() { //MACD macd = new MACD(); MACD macd = new MACD(true); macd.Load(csvPath); MACDSerie serie = macd.Calculate(); Assert.NotNull(serie); Assert.True(serie.Signal.Count > 0); Assert.True(serie.MACDLine.Count > 0); Assert.True(serie.MACDHistogram.Count > 0); }
public void MACD() { //MACD macd = new MACD(); MACD macd = new MACD(true); macd.Load(Directory.GetCurrentDirectory() + "\\table.csv"); MACDSerie serie = macd.Calculate(); Assert.IsNotNull(serie); Assert.IsTrue(serie.Signal.Count > 0); Assert.IsTrue(serie.MACDLine.Count > 0); Assert.IsTrue(serie.MACDHistogram.Count > 0); }
public ThoseFourIndicators(BarItemType barType) { this.barType = barType; this.identityCode = string.Format("{0}({1})", IDENTITY_CODE, barType.Code); cci = new CCI(barType, 14); stoch = new Stochastics(barType, 14, 2, 2); macd = new MACD(barType, 8, 40, 8); adx = new ADX(barType, 14); Register(cci, stoch, macd, adx); }
public BOTTOM(kdata data) { var macd = new MACD(data.close()); var lows = new PEAK(data, PEAK_TYPE.low).Select(p => new { p.Date, p.Value, type = PEAK_TYPE.low }).ToArray(); var highs = new PEAK(data, PEAK_TYPE.high).Select(p => new { p.Date, p.Value, type = PEAK_TYPE.high }).ToArray(); var peaks = lows.Concat(highs).OrderBy(p => p.Date).ToArray(); for (var i = 0; i < peaks.Length - 3; ++i) { var a = peaks[i]; var b = peaks[i + 1]; var c = peaks[i + 2]; var d = peaks[i + 3]; if (a.type == PEAK_TYPE.low && b.type == PEAK_TYPE.high && c.type == PEAK_TYPE.low && d.type == PEAK_TYPE.high && b.Value > a.Value && c.Value < b.Value && c.Value >= a.Value && d.Value > b.Value) { //var next = macd.Where(p => p.Date > d.Date).ToArray(); //for(var k = 2; k < next.Length; ++k) //{ // if (next[k].DIF < 0 && // next[k - 1].DIF < 0 && // next[k - 2].DIF < 0 && // next[k].DIF > next[k - 1].DIF && // next[k].DIF > next[k - 2].DIF) // { // var v = data.FirstOrDefault(p=>p.date == next[k].Date); // if (v != null) // { // if (!this.Any(p => p.Date == next[k].Date)) // { // Add(next[k].Date, v.high); // } // } // break; // } //} var next = macd.cross_gold().Where(p => p.Date > d.Date).ToArray(); if (next.Any()) { Add(next.First().Date, 0); } } } }
public void SeriesTest() { DataSeries ds = null; // TODO: Initialize to an appropriate value double fastPeriod = 0F; // TODO: Initialize to an appropriate value double slowPeriod = 0F; // TODO: Initialize to an appropriate value double signalPeriod = 0F; // TODO: Initialize to an appropriate value string name = string.Empty; // TODO: Initialize to an appropriate value MACD expected = null; // TODO: Initialize to an appropriate value MACD actual; actual = MACD.Series(ds, fastPeriod, slowPeriod, signalPeriod, name); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public void SignalSeriesTest() { //application.MarketData market = new application.MarketData(AppTypes.TimeRanges.Y1, AppTypes.TimeScaleFromType(AppTypes.TimeScaleTypes.Day),"SSI"); application.MarketData stockData = new application.MarketData(AppTypes.TimeRanges.Y1, AppTypes.TimeScaleFromCode("D1")); DataSeries ds = null; // TODO: Initialize to an appropriate value double fastPeriod = 12; double slowPeriod = 26; double signalPeriod = 9; string name = string.Empty; // TODO: Initialize to an appropriate value MACD target = new MACD(ds, fastPeriod, slowPeriod, signalPeriod, name); // TODO: Initialize to an appropriate value DataSeries actual; actual = target.SignalSeries; Assert.Inconclusive("Verify the correctness of this test method."); }
public void Run(string downloadTime) { DateTime date = DateTime.Now; DownloadEngine download = new DownloadEngine(); Formatting formatting = new Formatting(); PeregrineOperation peregrine = new PeregrineOperation(); MACD macd = new MACD(); Stochastic stochastic = new Stochastic(); TechnicalIndicators indicators = new TechnicalIndicators(); Transactions transactions = new Transactions(); WebClient web = new WebClient(); // provides the ability to download from the internet WebURIs uRIs = new WebURIs(); // refers to an instance of the Wall Street Journal URL DownloadTimer(download, formatting, peregrine, macd, stochastic, indicators, transactions, web, uRIs, Database, downloadTime); }
public QUOTATION(kdata data) { var close = data.close(); var macd = new MACD(close); var ma120 = new MA(close, 120); var q = (from a in data join m in macd on a.date equals m.Date select new { date = a.date, price = a, macd = m, ma120 = ma120[m.Date] }).ToArray(); for (var i = 0; i < q.Length; ++i) { var item = q[i]; var state = quotationstate.None; if (item.macd.MACD < 0) { state = quotationstate.调整; if (item.price.close >= item.price.open) { state = quotationstate.反弹; } } else { state = quotationstate.升; if (i - 1 > 0) { if (this[i - 1].state == quotationstate.回调 || this[i - 1].state == quotationstate.调整) { state = quotationstate.回升; } } if (item.price.close < item.price.open) { state = quotationstate.回调; } } Add(new quotation { date = item.date, state = state, position = judgePosition(state, item.price, item.ma120), strategy = judgeStrategy(state, item.price, item.ma120) }); } }
public static MACD GetMACD(List <float> input, int fastLength, int slowLength) { int maxLength = fastLength > slowLength ? fastLength : slowLength; List <float> emaFast = GetEMA(input, fastLength); List <float> emaSlow = GetEMA(input, slowLength); MACD output = new MACD(); output.Macd = Enumerable.Repeat(0f, maxLength - 1).ToList(); output.Macd.AddRange(emaFast.GetRange(maxLength - 1, emaFast.Count - maxLength + 1).Zip(emaSlow.GetRange(maxLength - 1, emaSlow.Count - maxLength + 1), (x, y) => x - y).ToList()); output.Signal = Enumerable.Repeat(0f, maxLength - 1).ToList(); output.Signal.AddRange(GetEMA(output.Macd.GetRange(maxLength - 1, output.Macd.Count - maxLength + 1), 9)); output.Histogram = Enumerable.Repeat(0f, maxLength + 9 - 2).ToList(); output.Histogram.AddRange(output.Macd.GetRange(maxLength + 9 - 2, output.Macd.Count - maxLength - 7).Zip(output.Signal.GetRange(maxLength + 9 - 2, output.Macd.Count - maxLength - 7), (x, y) => x - y).ToList()); return(output); }
public void MACDTest() { BacktestBroker backtestBroker = new BacktestBroker(); BrokerAccount brokerAccount = new BrokerAccount(); backtestBroker.LoadAccount(new BrokerAccount(), Guid.Empty); BacktestSession backtestSession = backtestBroker.CreateSession(brokerAccount.AccountId, SpotForex.EURUSD, Timeframes.M1, @"data\EURUSD-M1.bar", Guid.Empty); MACD macd = new MACD(Timeframes.M1, 12, 26, 9); backtestSession.Indicators.Add(macd); backtestSession.Start(); }
//Тест проверяет правильно ли срабатывает TradingRule public void test_TradingRule() { //Входные данные //Создать 2 условия int index1 = 0, index2 = 0; int curIndex = 60; ParameterCondition par1 = ParameterCondition.PriceMax; ParameterCondition par2 = ParameterCondition.PriceMin; Predicate predicate = Predicate.Less; Condition cond = new Condition(index1, index2, par1, par2, null, null, 0.0, 0.0, predicate); int index1_ = 1, index2_ = 1; ParameterCondition par1_ = ParameterCondition.Indicator; ParameterCondition par2_ = ParameterCondition.Indicator; Predicate predicate_ = Predicate.MoreEqual; Indicator ind1 = new SMA(14); Indicator ind2 = new MACD(28); Condition cond2 = new Condition(index1_, index2_, par1_, par2_, ind1, ind2, 0.0, 0.0, predicate_); //Накопить данные для индикаторов for (int i = 0; i < curIndex; i++) { ind1.update_value(i, instrument); ind2.update_value(i, instrument); } //Создать правило TradingRule rule = new TradingRule(Signal.Buy); rule.add_condition(cond); rule.add_condition(cond2); bool expected = instrument.get_interval(curIndex, index1).ClosingPrice < instrument.get_interval(curIndex, index1).OpeningPrice&& ind1.get_value(curIndex, index1_) >= ind2.get_value(curIndex, index2_); Assert.AreEqual(expected, rule.check(curIndex, instrument)); }
static void Main(string[] args) { DownloadAllStockFiles(); string[] stockNames = ConfigurationManager.AppSettings["StockNames"].Split(','); foreach (var stockName in stockNames) { MACD macd = new MACD(false); MACDSerie macdSeries = GetMacdSeries(macd, stockName); RSI rsi = new RSI(14); RSISerie rsiSeries = GetRsiSeries(rsi, stockName); SMAV2 shortTermSma = new SMAV2(14); SingleDoubleSerieV2 shorttermSingleDoubleSerieV2 = GetSingleDoubleSeriesV2(shortTermSma, stockName); SMAV2 longTermSma = new SMAV2(60); SingleDoubleSerieV2 longtermSingleDoubleSerieV2 = GetSingleDoubleSeriesV2(longTermSma, stockName); ExcelUtilities.WriteMacdhistogramDataToExcel(macdSeries, rsiSeries, shorttermSingleDoubleSerieV2, longtermSingleDoubleSerieV2, stockName); } }
static macd[] cross(MACD k, Func <macd, macd, bool> cmp) { var cross = new List <macd>(); for (var i = 1; i < k.Count; ++i) { if (cmp(k[i - 1], k[i])) { if (Math.Abs(k[i - 1].DEA - k[i - 1].DIF) < Math.Abs(k[i].DEA - k[i].DIF)) { cross.Add(k[i - 1]); } else { cross.Add(k[i]); } } } return(cross.ToArray()); }
override protected void StrategyExecute() { MACD macd = Indicators.MACD.Series(data.Close, parameters[0], parameters[1], parameters[2], ""); ADX adx = new ADX(data.Bars, parameters[3], ""); int cutlosslevel = (int)parameters[4]; int takeprofitlevel = (int)parameters[5]; double delta = 0, lastDelta = 0; for (int idx = 1; idx < macd.Values.Length; idx++) { delta = (macd.HistSeries[idx] - macd.HistSeries[idx - 1]); //If there is a trend if (adx[idx] > 25) { if (delta > 0 && lastDelta < 0) { BuyAtClose(idx); } } if (delta < 0 && lastDelta > 0) { SellAtClose(idx); } if (is_bought && CutLossCondition(data.Close[idx], buy_price, cutlosslevel)) { SellCutLoss(idx); } if (is_bought && TakeProfitCondition(data.Close[idx], buy_price, takeprofitlevel)) { SellTakeProfit(idx); } lastDelta = delta; } }
public void TestCalculate() { TickerBLL tbll = new TickerBLL(_unit); List <Ticker> tList = tbll.GetTickerListByShareDB(1585, 0, 21100000); double[] inputData = new double[tList.Count]; var i = 0; foreach (var t in tList) { inputData[i] = t.Close; i++; } double?[] m = new double?[tList.Count]; double?[] s = new double?[tList.Count]; double?[] h = new double?[tList.Count]; Result res = MACD.Calculate(inputData, 26, 12, 9, m, s, h); }
protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @"Enter the description for your new custom Strategy here."; Name = "DrawOnIndicatorPanels"; Calculate = Calculate.OnBarClose; EntriesPerDirection = 1; EntryHandling = EntryHandling.AllEntries; IsExitOnSessionCloseStrategy = true; ExitOnSessionCloseSeconds = 30; IsFillLimitOnTouch = false; MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix; OrderFillResolution = OrderFillResolution.Standard; Slippage = 0; StartBehavior = StartBehavior.WaitUntilFlat; TimeInForce = TimeInForce.Gtc; TraceOrders = false; RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose; StopTargetHandling = StopTargetHandling.PerEntryExecution; BarsRequiredToTrade = 20; DrawOnPricePanel = false; // Disable this property for performance gains in Strategy Analyzer optimizations // See the Help Guide for additional information IsInstantiatedOnEachOptimizationIteration = true; } else if (State == State.DataLoaded) { MACD1 = MACD(12, 26, 9); AddChartIndicator(MACD1); MACD1.DrawOnPricePanel = false; MACD1.IsOverlay = false; MACD2 = MACD(13, 26, 9); AddChartIndicator(MACD2); MACD2.DrawOnPricePanel = false; MACD2.IsOverlay = false; } }
protected override void OnCalculate() { MACD macd = MACD(8, 17, 9); StochasticsFast stoc = StochasticsFast(5, 14); EMA ema = EMA(10); //if (macd[0] > macd.Avg[0]) { // //AddChartArrowUp("ArrowLong_MACD" + +Bars[0].Time.Ticks, this.IsAutoAdjustableScale, 0, Bars[0].Low, Color.Green); //} //if (stoc.K[0] > stoc.D[0]) //{ // //AddChartArrowUp("ArrowLong_STOC" + +Bars[0].Time.Ticks, this.IsAutoAdjustableScale, 0, Bars[0].High, Color.DarkMagenta); //} //if (Bars[0].Close > ema[0]) //{ // //AddChartArrowUp("ArrowLong_EMA" + +Bars[0].Time.Ticks, this.IsAutoAdjustableScale, 0, Bars[0].High - (Bars[0].Range/2), Color.DarkGoldenrod); //} if (macd[0] > macd.Avg[0] && stoc.K[0] > stoc.D[0] && Bars[0].Close > ema[0]) { AddChartArrowUp("ArrowLong_philtown" + +Bars[0].Time.Ticks, this.IsAutoAdjustableScale, 0, Bars[0].Low, Color.Green); MyPlot1[0] = 1; } else if (macd[0] < macd.Avg[0] && stoc.K[0] < stoc.D[0] && Bars[0].Close < ema[0]) { AddChartArrowDown("ArrowShort_philtown" + +Bars[0].Time.Ticks, this.IsAutoAdjustableScale, 0, Bars[0].High, Color.Red); MyPlot1[0] = -1; } else { MyPlot1[0] = 0; } }
static void Intraday() { SubscribeEvents(); var ticks = mainProvider.GetTicks(symbols, 121, 30, GooglePoints); #region Main Symbol Loop foreach (var tick in ticks.Where(t => t.TickGroup.Count() > 0)) { notificationsList.Add(tick.Symbol, mainProvider.GenerateTickReportData(tick)); #region Intraday Ticks Indicators Events var twoMinutesFiveDaysClosePrices = tick.TickGroup2Minutes5Days.Select(x => x.Close).ToList(); if (twoMinutesFiveDaysClosePrices.Count() > 0) { RelativeStrengthIndex.GetRSI(10, twoMinutesFiveDaysClosePrices, tick.Symbol, Periods.TwoMinutesFiveDays); MACD.GetMACDInfo(12, 26, 9, twoMinutesFiveDaysClosePrices, 5, tick.Symbol, Periods.TwoMinutesFiveDays); } #endregion } #endregion NotifSender.SendTickReportData(notificationsList, Delivery.FTP); }
protected override void OnCalculate() { Bollinger bol = Bollinger(this.Bollinger_stddev, this.Bollinger_Period); if (Close[0] < bol.Lower[0]) { longsignalbb = true; } else if (Close[0] > bol.Upper[0]) { shortsignalbb = true; } else { //nothing } MACD macd = MACD(this.MACD_Fast, this.MACD_Slow, this.MACD_Smooth); if (longsignalbb && CrossAbove(macd.Default, macd.Avg, 0)) { AddChartArrowUp(Time[0].ToString() + "long", 0, Low[0], this.ColorLongSignal); MyPlot1.Set(1); longsignalbb = false; } else if (shortsignalbb && CrossBelow(macd.Default, macd.Avg, 0)) { AddChartArrowDown(Time[0].ToString() + "short", 0, High[0], this.ColorShortSignal); MyPlot1.Set(-1); shortsignalbb = false; } else { MyPlot1.Set(0); } }
public override universe Pass(IEnumerable <string> stocks) { var client = new kdatadb(); log.Info("query D"); var D = stocks .AsParallel() .Select(code => client.kdata(code, "D")) .Where(p => p != null && p.Any()) .ToArray(); log.InfoFormat("D total {0}", D.Count()); var codes = D .Where(p => { if (!p.Any()) { return(false); } var close = p.close(); var cross = new MACD(p.volume()).cross(); return(cross.Any() && cross.Last().type == Interface.Data.crosstype.gold && cross.Last().value.Date.Date == DateTime.Today); }) .Select(p => p.Code) .Distinct() .ToArray(); log.InfoFormat("selected {0}", codes.Count()); return(new universe("volume", codes)); }
public override void Run(Account account) { var client = new kdatadb(); log.InfoFormat("total {0}", account.universe.Count); foreach (var stock in account.universe.AsParallel()) { log.InfoFormat("run {0}", stock.Code); var k = client.kdata(stock.Code, "15"); var kdj = new MACD(k.close()); var crossup = kdj.cross_gold(); var crossdown = kdj.cross_dead(); if (crossup.Any()) { var s = crossup.Last(); if (s.Date == k.Last().date&& s.Date.Date == DateTime.Today) { Buy(account, stock.Code, s.Date); continue; } } if (crossdown.Any()) { var s = crossdown.Last(); if (s.Date == k.Last().date&& s.Date.Date == DateTime.Today) { Sell(account, stock.Code, s.Date); continue; } } log.InfoFormat("no signal {0}", stock.Code); } }
public void MACD() { //File.Delete(@"MacdHData.xlsx"); //MACD macd = new MACD(); MACD macd = new MACD(false); //https://au.finance.yahoo.com/quote/VAS.AX/ //https://au.finance.yahoo.com/quote/STW.AX/ //https://au.finance.yahoo.com/quote/APT.AX //MACDSerie serie = GenerateMacdHistogramData(macd, "vas"); q q //macd = new MACD(false); //serie = GenerateMacdHistogramData(macd, "stw"); //macd = new MACD(false); //serie = GenerateMacdHistogramData(macd, "apt"); macd.Load(Directory.GetCurrentDirectory() + "\\" + "table" + ".csv"); MACDSerie serie = macd.Calculate(); Assert.IsNotNull(serie); Assert.IsTrue(serie.Signal.Count > 0); Assert.IsTrue(serie.MACDLine.Count > 0); Assert.IsTrue(serie.MACDHistogramDataList.Count > 0); //serie.MACDHistogram.Select((x,i) => new {i, value = x.GetValueOrDefault(),Consider = x != null && x.Value < 0 && x.Value >-1 }).Where(x => x.Consider) //serie.MACDHistogram.ElementAt(i-1) if its negative and > current negative value between 0 and -1 , good time to buy }
private void button11_Click(object sender, EventArgs e) { if (repository == null) { repository = new IndicatorRepository(textBox2.Text); repository.Initilization(); } SecurityPropertiesSet securities = repository.Securities; List <String> codes = securities.Codes; int num = 0; foreach (String code in codes) { if (code == null || code == "") { continue; } TimeSerialsDataSet tsd = repository[code]; if (tsd == null) { continue; } KLine dayLine = tsd.DayKLine; if (dayLine == null) { continue; } MACD macd = (MACD)tsd.Create("macd", TimeUnit.day, false); if (macd == null) { continue; } } }
private void DownloadTimer(DownloadEngine download, Formatting formatting, PeregrineOperation peregrine, MACD macd, Stochastic stochastic, TechnicalIndicators indicators, Transactions transactions, WebClient web, WebURIs uRIs, string Database, string downloadTime) { var DailyTime = downloadTime; //Time when method needs to be called var timeParts = DailyTime.Split(new char[1] { ':' }); var dateNow = DateTime.Now; var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2])); TimeSpan ts; if (date > dateNow) { ts = date - dateNow; } else { date = date.AddDays(1); ts = date - dateNow; } while (date != dateNow) { Console.WriteLine($"Waiting for {downloadTime}"); //waits certan time and run the code Task.Delay(ts).ContinueWith((x) => Download(date, download, formatting, peregrine, macd, stochastic, indicators, transactions, web, uRIs, Database)); Console.Read(); } }
protected override void Create() { // 初始化下單物件,Contracts.UserSpecified 可指定規模,OrderExit.FromAll 可一次全平 多單 = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.UserSpecified, EOrderAction.Buy)); 空單 = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.UserSpecified, EOrderAction.SellShort)); 多沖 = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.Default, EOrderAction.Sell, OrderExit.FromAll)); 空沖 = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.Default, EOrderAction.BuyToCover, OrderExit.FromAll)); __cService = OrderCreator as AbstractOrderService; __cTimer = new Timer(1); __cTimer.AutoReset = false; __cTimer.Elapsed += Timer_onElapsed; //__cTimer.Start(); //bbb = BarsOfData(2); cBuilder.AppendLine("[F000]"); __cKDSum = new VariableSeries<double>(this); __cMACD = new MACD(this); __cMACD.FastPeriod = 5; __cMACD.SlowPeriod = 10; __cMACD.MACDPeriod = 10; __cKD = new KD(this); __cKD.Length = 5; }
public override void Calculate(IDataSet dataSet) { DataSet = dataSet; // Reading the parameters var basePrice = (BasePrice)IndParam.ListParam[2].Index; var referencePeriod = (int)IndParam.NumParam[3].Value; int previous = IndParam.CheckParam[0].Checked ? 1 : 0; // Calculation // --------------------------------------------------------- var macd = new MACD(); macd.Initialize(SlotType); macd.IndParam.ListParam[1].Index = IndParam.ListParam[1].Index; macd.IndParam.ListParam[2].Index = IndParam.ListParam[2].Index; macd.IndParam.ListParam[3].Index = 0; macd.IndParam.NumParam[0].Value = IndParam.NumParam[0].Value; macd.IndParam.NumParam[1].Value = IndParam.NumParam[1].Value; macd.IndParam.NumParam[2].Value = IndParam.NumParam[2].Value; macd.IndParam.CheckParam[0].Checked = IndParam.CheckParam[0].Checked; macd.Calculate(DataSet); double[] indicatorMa = MovingAverage(referencePeriod, previous, MAMethod.Simple, macd.Component[0].Value); double[] marketMa = MovingAverage(referencePeriod, previous, MAMethod.Simple, Price(basePrice)); // ---------------------------------------------------------- int firstBar = macd.Component[0].FirstBar + referencePeriod + 2; var cd = new double[Bars]; if (IndParam.ListParam[0].Text == "Convergence") { for (int bar = firstBar; bar < Bars; bar++) { cd[bar] = IsConvergence(indicatorMa, marketMa, bar); } } else if (IndParam.ListParam[0].Text == "Divergence") { for (int bar = firstBar; bar < Bars; bar++) { cd[bar] = IsDivergence(indicatorMa, marketMa, bar); } } // Saving the components Component = new IndicatorComp[4]; Component[0] = new IndicatorComp { CompName = "MACD Histogram", DataType = IndComponentType.IndicatorValue, ChartType = IndChartType.Line, ChartColor = Color.RoyalBlue, FirstBar = firstBar, Value = macd.Component[0].Value }; Component[1] = new IndicatorComp { CompName = "MACD MA", DataType = IndComponentType.IndicatorValue, ChartType = IndChartType.Line, ChartColor = Color.Red, FirstBar = firstBar, Value = indicatorMa }; Component[2] = new IndicatorComp { ChartType = IndChartType.NoChart, FirstBar = firstBar, Value = cd }; Component[3] = new IndicatorComp { ChartType = IndChartType.NoChart, FirstBar = firstBar, Value = cd }; // Sets the Component's type if (SlotType == SlotTypes.OpenFilter) { Component[2].DataType = IndComponentType.AllowOpenLong; Component[2].CompName = "Is long entry allowed"; Component[3].DataType = IndComponentType.AllowOpenShort; Component[3].CompName = "Is short entry allowed"; } else if (SlotType == SlotTypes.CloseFilter) { Component[2].DataType = IndComponentType.ForceCloseLong; Component[2].CompName = "Close out long position"; Component[3].DataType = IndComponentType.ForceCloseShort; Component[3].CompName = "Close out short position"; } }
public override TradeRecords Execute(String code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null) { IndicatorRepository repository = (IndicatorRepository)backtestParam.Get <Object>("repository"); if (repository == null) { return(null); } //取得策略参数 double buy_mainlow = strategyParam.Get <double>("buy_mainlow"); //主力线低位买入 int buy_cross = strategyParam.Get <int>("buy_cross"); GetInMode p_getinMode = (GetInMode)strategyParam.Get <GetInMode>("getinMode"); //取得行情数据 TradeRecords tr = new TradeRecords(code); TimeSerialsDataSet ds = repository[code]; if (ds == null) { return(null); } KLine kline = ds.DayKLine; if (kline == null) { return(null); } MACD macd = (MACD)ds.Create("macd", TimeUnit.day, false); if (macd == null) { return(null); } //买入条件判定 for (int i = 0; i < macd.Count; i++) { MACDItem macdItem = macd[i]; if (macdItem.Date < backtestParam.BeginDate || macdItem.Date >= backtestParam.EndDate) { continue; } if (macdItem.CROSS <= 0) { continue; } if (macdItem.DIF > buy_mainlow) { continue; } DateTime d = macdItem.Date; KLineItem klineItem = kline[d]; if (klineItem == null) { continue; } TradeBout bout = new TradeBout(code); bout.RecordTrade(1, d, TradeDirection.Buy, klineItem.CLOSE, (int)(p_getinMode.Value / klineItem.CLOSE), backtestParam.Volumecommission, backtestParam.Stampduty, "低位金叉" + macdItem.DIF.ToString("F2")); tr.Bouts.Add(bout); } return(tr); }
public override void Initialize() { macd = this.MACD(this.Close, 13, 26, 9); }
/// Download and save to Database private void Download(DateTime date, DownloadEngine download, Formatting formatting, PeregrineOperation peregrine, MACD macd, Stochastic stochastic, TechnicalIndicators indicators, Transactions transactions, WebClient web, WebURIs uRIs, string Database) { List <string> Symbols = transactions.DatabaseSymbolListQuery(Database, stocks); transactions.TruncateStockTable(Database, "Clean Data"); // clears data from the clean data table. int count = 1; foreach (var stock in Symbols) { Console.Clear(); Console.WriteLine($"Downloading {stock} || {count} of {Symbols.Count}"); download.ToDatabase(date, formatting, peregrine, transactions, web, uRIs, stock, Database); count++; } Console.WriteLine("I'm Done"); //count = 1; //calls the list of stocks that have been data verified //List<string> CleanData = transactions.DatabaseSymbolListQuery(Database, stocks); //foreach (var stock in CleanData) //{ // Console.Clear(); // Console.WriteLine($"Doing Math {stock} || {count} of {CleanData.Count}"); // List<Results> results = MathPredictsTheFuture(download, macd, stochastic, transactions, indicators, stock); // transactions.SaveToTableResult(Database, results); // saves the calculations to the Results table in the database // count++; //} //// calls the stocks from the results list //List<PeregrineResults> todaysResults = transactions.DailyResultsQuery(peregrine.Database); //transactions.TruncateStockTable(database, peregrineresults); // clears the web results table. This table feeds the model for the ASP.Net interface. //transactions.SaveToTableWebResult(peregrine.Database, todaysResults); //Console.WriteLine("Peregrine Results Updated"); }
public override void OnBar(Bar bar) { { macd = new MACD(_1mlist); mv5 = new MA(_1mlist, BarData.Volume, 5); ma5 = new MA(_1mlist, 5);; AddIndicator(macd); AddIndicator(ma5); AddIndicator(mv5); /* Print("k:" + _1mlist.Ago(0).ToString()); * Print("ma: " + macd.Ago(0).ToString()); * Print("vma: " + mv5.Ago(0).ToString()); * Print("ma: " + ma5.Ago(0).ToString()); * Print("dif:" + macd.DIF(0).ToString() + "dea" + macd.DEA(0).ToString());*/ // Print(klist(0).) 生成(_1mlist); /* * Print("onbar bars[0]: " + bars[0].ToString()); * Print("onbar bars.Count: " + bars.Count.ToString()); * Print("onbar blist1.Count: " + blist1.Count.ToString());*/ for (int j = 0; j < blist1.Count; j++) { if (blist1[j].zd == 结构.顶) { Print("blist1" + "^|" + blist1[j].high.ToString() + "|" + blist1[j].ba.BeginTime.ToString()); } else { Print("blist1" + "v|" + blist1[j].low.ToString() + "|" + blist1[j].ba.EndTime.ToString()); } } } var 当前多头持仓 = GetPosition(EnumMarket.期货, DefaultAccount, DefaultFutureCode, EnumPositionDirection.多头); var 当前空头持仓 = GetPosition(EnumMarket.期货, DefaultAccount, DefaultFutureCode, EnumPositionDirection.空头); if (blist1.Last().zd == 结构.底) { if (当前空头持仓 != null) { Print(当前空头持仓.ToString()); if (当前空头持仓.YdPosition > 0) { order = LimitOrder(当前空头持仓.Volume, blist1.Last().ba.Close, EnumBuySell.买入, EnumOpenClose.平仓); } if (当前空头持仓.TodayPosition > 0) { order = LimitOrder(当前空头持仓.Volume, blist1.Last().ba.Close, EnumBuySell.买入, EnumOpenClose.平今仓); } } if (当前多头持仓 != null) { return; } else { order = LimitOrder(1, blist1.Last().ba.Close, EnumBuySell.买入, EnumOpenClose.开仓); } } if (blist1.Last().zd == 结构.顶) { if (当前多头持仓 != null) { Print(当前多头持仓.ToString()); if (当前多头持仓.YdPosition > 0) { order = LimitOrder(当前多头持仓.Volume, blist1.Last().ba.Close, EnumBuySell.卖出, EnumOpenClose.平仓); } if (当前多头持仓.TodayPosition > 0) { order = LimitOrder(当前多头持仓.Volume, blist1.Last().ba.Close, EnumBuySell.卖出, EnumOpenClose.平今仓); } } if (当前空头持仓 != null) { return; } else { order = LimitOrder(1, blist1.Last().ba.Close, EnumBuySell.卖出, EnumOpenClose.开仓); } } }
private void CalculateDaily(string code) { if (string.IsNullOrEmpty(code)) { return; } var scripts = Config.Instance.INFO.ScriptSetting.Scripts; var macdsetting = Config.Instance.INFO.MACDSetting; var rsisetting = Config.Instance.INFO.RSISetting; // Delete MACD, RSI values if ((CheckTable <DBStkMACDEntity>() && scripts.ContainsKey("DEL_MACD_BY_CD")) && (CheckTable <DBStkRSIEntity>() && scripts.ContainsKey("DEL_RSI_BY_CD"))) { var lprm_macd = accessor.CreateParameter("CODE", code); var lcmd_macd = accessor.CreateCommand(scripts["DEL_MACD_BY_CD"], new List <DbParameter>() { lprm_macd }); var lprm_rsi = accessor.CreateParameter("CODE", code); var lcmd_rsi = accessor.CreateCommand(scripts["DEL_RSI_BY_CD"], new List <DbParameter>() { lprm_rsi }); if (accessor.ExecuteSQLCommand(new List <DbCommand>() { lcmd_macd, lcmd_rsi }) < 0) { logger.Write(TYPE.ERROR, string.Format("delete MACD and RSI data failed.({0})", code)); logger.Write(TYPE.ERROR, accessor.LastError); return; } } else { return; } // Retrieve Stocks var page = new EntityPage <DBTStkDailyEntity>( new Clause("Code = {Code}").AddParam("Code", code), new Sort().Add("ID", Sort.Orientation.asc), 100, accessor); List <DBTStkDailyEntity> lst_daily = null; DateTime ldt_date = DateTime.Today; MACD macd = null; RSI rsi = null; AverageValue daily30 = null; #region Cache For MACD SegCache <LinearList <KeyValuePair <DateTime, decimal> >, KeyValuePair <DateTime, decimal> > cache1 = null; SegCache <LinearList <KeyValuePair <DateTime, decimal> >, KeyValuePair <DateTime, decimal> > cache2 = null; LinearList <KeyValuePair <DateTime, decimal> > list1 = null; LinearList <KeyValuePair <DateTime, decimal> > list2 = null; #endregion #region Cache For AVG SegCache <LinearList <KeyValuePair <DateTime, decimal> >, KeyValuePair <DateTime, decimal> > cache3 = null; SegCache <LinearList <KeyValuePair <DateTime, decimal> >, KeyValuePair <DateTime, decimal> > cache4 = null; LinearList <KeyValuePair <DateTime, decimal> > list3 = null; LinearList <KeyValuePair <DateTime, decimal> > list4 = null; #endregion Func <KeyValuePair <DateTime, decimal>, decimal> fValue = (pair) => { return(pair.Value); }; Func <KeyValuePair <DateTime, decimal>, KeyValuePair <DateTime, decimal>, LinearList <KeyValuePair <DateTime, decimal> >, bool> fSwitch1 = (v1, v2, segment) => { switch (segment.Orietion) { case 0: return(false); case 1: if (v2.Value >= v1.Value) { return(false); } break; case -1: if (v2.Value <= v1.Value) { return(false); } break; } return(true); }; Func <LinearList <KeyValuePair <DateTime, decimal> >, LinearList <KeyValuePair <DateTime, decimal> >, bool> fSwitch2 = (values, segment) => { if (segment.Orietion == 0 || segment.Orietion == values.Orietion) { return(false); } return(values.Count >= 10); }; int pageno = 0; var count = 0; while ((lst_daily = page.Retrieve(++pageno)).Count > 0) { for (int i = 0; i < lst_daily.Count; i++, count++) { try { var daily = lst_daily[i]; ldt_date = daily.Date; if (pageno == 1 && i == 0) { macd = new MACD(daily.Close); rsi = new RSI(rsisetting.N1, rsisetting.N2, rsisetting.N3, daily.Close); daily30 = new AverageValue(30, 4); daily30.Add(daily.Close); cache1 = new SegCache <LinearList <KeyValuePair <DateTime, decimal> >, KeyValuePair <DateTime, decimal> >( new LinearList <KeyValuePair <DateTime, decimal> >[] { new LinearList <KeyValuePair <DateTime, decimal> >(fValue), new LinearList <KeyValuePair <DateTime, decimal> >(fValue) }, fSwitch1, null); cache2 = new SegCache <LinearList <KeyValuePair <DateTime, decimal> >, KeyValuePair <DateTime, decimal> >( new LinearList <KeyValuePair <DateTime, decimal> >[] { new LinearList <KeyValuePair <DateTime, decimal> >(fValue), new LinearList <KeyValuePair <DateTime, decimal> >(fValue) }, null, fSwitch2); cache3 = new SegCache <LinearList <KeyValuePair <DateTime, decimal> >, KeyValuePair <DateTime, decimal> >( new LinearList <KeyValuePair <DateTime, decimal> >[] { new LinearList <KeyValuePair <DateTime, decimal> >(fValue), new LinearList <KeyValuePair <DateTime, decimal> >(fValue) }, fSwitch1, null); cache4 = new SegCache <LinearList <KeyValuePair <DateTime, decimal> >, KeyValuePair <DateTime, decimal> >( new LinearList <KeyValuePair <DateTime, decimal> >[] { new LinearList <KeyValuePair <DateTime, decimal> >(fValue), new LinearList <KeyValuePair <DateTime, decimal> >(fValue) }, null, fSwitch2); } else { macd.Add(daily.Close); rsi.Add(daily.Close); daily30.Add(daily.Close); if (cache1.Add(new KeyValuePair <DateTime, decimal>(daily.Date, macd.DEA), out list1)) { cache2.Add(list1, out list2); } if (cache3.Add(new KeyValuePair <DateTime, decimal>(daily.Date, daily30.Average), out list3)) { cache4.Add(list3, out list4); } } var lent_macd = new DBStkMACDEntity(daily.ID); lent_macd.EMA12 = macd.EMA12; lent_macd.EMA26 = macd.EMA26; lent_macd.DIFF = macd.DIFF; lent_macd.DEA = macd.DEA; lent_macd.BAR = macd.BAR; var lent_rsi = new DBStkRSIEntity(daily.ID); lent_rsi.RSI1 = rsi.RSI1; lent_rsi.RSI2 = rsi.RSI2; lent_rsi.RSI3 = rsi.RSI3; lent_rsi.RSI1MaxEma = rsi.RSI1MaxEma; lent_rsi.RSI1ABSEma = rsi.RSI1ABSEma; lent_rsi.RSI2MaxEma = rsi.RSI2MaxEma; lent_rsi.RSI2ABSEma = rsi.RSI2ABSEma; lent_rsi.RSI3MaxEma = rsi.RSI3MaxEma; lent_rsi.RSI3ABSEma = rsi.RSI3ABSEma; accessor.SaveEntity(lent_macd, lent_rsi); accessor.Commit(); } catch { } } } if (count > 120) { cache2.Add(cache1.Segment, out list2); cache4.Add(cache3.Segment, out list4); var lent_sum = new DBStkSummaryResultEntity(); lent_sum.Code = code; lent_sum.Time = DateTime.Now; lent_sum.PAVG30_ORIENT = cache4.Segment.Orietion; lent_sum.PAVG30_DAYS = cache4.Segment.Count; lent_sum.PAVG30_VALUE = cache4.Segment.Slope; lent_sum.PAVG30_Date1 = cache4.Segment[0].Key; lent_sum.PAVG30_Date2 = cache4.Segment[cache4.Segment.Count - 1].Key; lent_sum.DEA_ORIENT = cache2.Segment.Orietion; lent_sum.DEA_DAYS = cache2.Segment.Count; lent_sum.DEA_VALUE = cache2.Segment.Slope; lent_sum.DEA_Date1 = cache2.Segment[0].Key; lent_sum.DEA_Date2 = cache2.Segment[cache2.Segment.Count - 1].Key; lent_sum.RSI_Date = ldt_date; lent_sum.RSI_VALUE1 = rsi.RSI1; lent_sum.RSI_VALUE2 = rsi.RSI2; lent_sum.RSI_VALUE3 = rsi.RSI3; if (CheckTable <DBStkSummaryResultEntity>()) { accessor.SetDBAccessor2(lent_sum); lent_sum.GenerateID(); lent_sum.Save(); } } if (page != null) { page.Dispose(); } if (cache1 != null) { cache1.Dispose(); } if (cache2 != null) { cache2.Dispose(); } if (cache3 != null) { cache3.Dispose(); } if (cache4 != null) { cache4.Dispose(); } if (daily30 != null) { daily30.Dispose(); } }