public void PayloadEmptySourceFileAttribute() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(PayloadTests.TestDataDirectory, @"PayloadEmptySourceFileAttribute\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(6, "The Payload/@SourceFile attribute's value cannot be an empty string. If you want the value to be null or empty, simply remove the entire attribute.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 6; candle.Run(); }
public void ComponentSearchGuidMissing() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(ComponentSearchTests.TestDataDirectory, @"ComponentSearchGuidMissing\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(10, "The util:ComponentSearch/@Guid attribute was not found; it is required.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 10; candle.Extensions.Add("WixUtilExtension"); candle.Run(); }
// Use this for initialization void Start() { candle1 = GameObject.Find ("Candle1").GetComponent<Candle> (); candle2 = GameObject.Find ("Candle2").GetComponent<Candle> (); candle3 = GameObject.Find ("Candle3").GetComponent<Candle> (); candle4 = GameObject.Find ("Candle4").GetComponent<Candle> (); state = 0; }
public void DirectorySearchInvalidPath() { string sourceFile = Path.Combine(DirectorySearchTests.TestDataDirectory, @"DirectorySearchInvalidPath\Product.wxs"); Candle candle = new Candle(); candle.SourceFiles.Add(sourceFile); candle.Extensions.Add("WixUtilExtension"); candle.ExpectedWixMessages.Add(new WixMessage(346, "The util:DirectorySearch/@Path attribute's value, '%windir%\\System|*32', is not a valid relative long name because it contains illegal characters. Legal relative long names contain no more than 260 characters and must contain at least one non-period character. Any character except for the follow may be used: ? | > < : / * \".", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 346; candle.Run(); }
static void Main(string[] args) { var zoneDetector = new ZoneDetector(); var detector = new KangarooTailDetector(zoneDetector); detector.Start(); var firstCandle = new Candle(); detector.AddNewCandle(firstCandle); var secondCandle = new Candle(); detector.AddNewCandle(secondCandle); }
public void AddNewCandle(Candle candle) { if (_previousCandle == null) { _previousCandle = candle; _currentCandle = candle; return; } _previousCandle = _currentCandle; _currentCandle = candle; AnalyzeKangarooTailFormation(); }
public void AddNewCandle(Candle candle) { if (_previousCandle == null) { _previousCandle = candle; _currentCandle = candle; return; } _previousCandle = _currentCandle; _currentCandle = candle; AnalyzeBigShadowFormation(); }
public void ExampleTest2() { // Compile a wxs file Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(this.TestContext.DataDirectory, @"Examples\ExampleTest2\product.wxs")); candle.Run(); // Create a Light object that uses some properties of the Candle object Light light = new Light(candle); // Define the Light warning that we expect to see WixMessage LGHT1079 = new WixMessage(1079, WixMessage.MessageTypeEnum.Warning); light.ExpectedWixMessages.Add(LGHT1079); // Link light.Run(); // Query the resulting MSI for verification string query = "SELECT `Value` FROM `Property` WHERE `Property` = 'Manufacturer'"; Verifier.VerifyQuery(light.OutputFile, query, "Microsoft Corporation"); }
public void Activate(float speed, Vector3 distance, Vector3 aftaDistance, float afterWait, Candle resetCandle) { if (transform.position == distance + originalPosition) resetCandle.ResetActivation(true); else { if (this.resetCandle != null) this.resetCandle.ResetActivation(aftaDistances[aftaDistances.Count - 1] == Vector3.zero); this.resetCandle = resetCandle; this.speed = speed; this.afterWait = afterWait; this.distance = distance; finalPos = distance + transform.position; if (aftaDistance != Vector3.zero) moveBacks.Add(aftaDistance + finalPos); aftaDistances.Add(aftaDistance); originalPosition = transform.position; sign = distance.normalized; Debug.Log(aftaSign = aftaDistance.normalized); } }
public void ComponentSearchPredefinedVariable() { string expectedErrorMessage = @"The util:ComponentSearch/@Variable attribute's value, 'ProgramFilesFolder', is one of the illegal options: 'AdminToolsFolder', 'AppDataFolder', 'CommonAppDataFolder', 'CommonFilesFolder', 'CompatibilityMode', 'DesktopFolder', 'FavoritesFolder', 'FontsFolder', 'LocalAppDataFolder', 'MyPicturesFolder', 'NTProductType', 'NTSuiteBackOffice', 'NTSuiteDataCenter', 'NTSuiteEnterprise', 'NTSuitePersonal', 'NTSuiteSmallBusiness', 'NTSuiteSmallBusinessRestricted', 'NTSuiteWebServer', 'PersonalFolder', 'Privileged', 'ProgramFilesFolder', 'ProgramMenuFolder', 'SendToFolder', 'StartMenuFolder', 'StartupFolder', 'SystemFolder', 'TempFolder', 'TemplateFolder', 'VersionMsi', 'VersionNT', 'VersionNT64', 'WindowsFolder', or 'WindowsVolume'."; Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(ComponentSearchTests.TestDataDirectory, @"ComponentSearchPredefinedVariable\Product.wxs")); candle.OutputFile = "Setup.exe"; candle.Extensions.Add("WixUtilExtension"); candle.ExpectedWixMessages.Add(new WixMessage(348, expectedErrorMessage, Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 348; candle.Run(); }
Vector2 GetTargetPosition(Candle Target) { Vector2 MissVector = Random.insideUnitCircle; return ((Vector2)Target.transform.position) + (MissVector * Inaccuracy); }
/// <summary> /// take candles on instruments /// взять свечи по инструменту /// </summary> public List <Candle> GetCandleHistory(string securityName, TimeSpan seriesTimeFrameSpan, int count, DateTime start, DateTime end) { try { lock (_candlesLocker) { List <Candle> newCandles = null; int tf = Convert.ToInt32(seriesTimeFrameSpan.TotalMinutes); if (tf == 1 || tf == 2 || tf == 3) { // building candles from 1 minute / строим свечи из минуток var rawCandles = GetBitfinexCandles("1m", securityName, count, start, end); newCandles = TransformCandles(1, tf, rawCandles); } else if (tf == 5 || tf == 10 || tf == 20) { // building candles from 5 minutes / строим свечи из 5минуток var rawCandles = GetBitfinexCandles("5m", securityName, count, start, end); newCandles = TransformCandles(5, tf, rawCandles); } else if (tf == 15 || tf == 30 || tf == 45) { // building candles from 15 minutes / строим свечи из 15минуток var rawCandles = GetBitfinexCandles("15m", securityName, count, start, end); newCandles = TransformCandles(15, tf, rawCandles); } else if (tf == 60 || tf == 120 || tf == 240) { // building candles from 1 hour / строим свечи из часовиков var rawCandles = GetBitfinexCandles("1h", securityName, count, start, end); newCandles = TransformCandles(60, tf, rawCandles); } else if (tf == 1440) { // building candles from 1 day / строим свечи из дневок var rawCandles = GetBitfinexCandles("1D", securityName, count, start, end); List <Candle> daily = new List <Candle>(); for (int i = rawCandles.Count - 1; i > 0; i--) { Candle candle = new Candle(); candle.TimeStart = new DateTime(1970, 1, 1) + TimeSpan.FromMilliseconds(rawCandles[i][0]); candle.Open = Convert.ToDecimal(rawCandles[i][1]); candle.Close = Convert.ToDecimal(rawCandles[i][2]); candle.High = Convert.ToDecimal(rawCandles[i][3]); candle.Low = Convert.ToDecimal(rawCandles[i][4]); candle.Volume = Convert.ToDecimal(rawCandles[i][5]); daily.Add(candle); } newCandles = daily; } return(newCandles); } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); return(null); } }
public void PackageInvalidName() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(PackageTests.TestDataDirectory, @"PackageInvalidName\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(346, "The MsiPackage/@Name attribute's value, 'MsiPackage|*?.msi', is not a valid relative long name because it contains illegal characters. Legal relative long names contain no more than 260 characters and must contain at least one non-period character. Any character except for the follow may be used: ? | > < : / * \".", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(346, "The MspPackage/@Name attribute's value, 'MspPackage|*?.msp', is not a valid relative long name because it contains illegal characters. Legal relative long names contain no more than 260 characters and must contain at least one non-period character. Any character except for the follow may be used: ? | > < : / * \".", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(346, "The MsuPackage/@Name attribute's value, 'MsuPackage|*?.msu', is not a valid relative long name because it contains illegal characters. Legal relative long names contain no more than 260 characters and must contain at least one non-period character. Any character except for the follow may be used: ? | > < : / * \".", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(346, "The ExePackage/@Name attribute's value, 'ExePackage|*?.exe', is not a valid relative long name because it contains illegal characters. Legal relative long names contain no more than 260 characters and must contain at least one non-period character. Any character except for the follow may be used: ? | > < : / * \".", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 346; candle.Run(); }
public IEnumerable<ICandleBuilderSourceValue> GetValues(Candle candle) { if (candle == null) throw new ArgumentNullException("candle"); var trades = _candleValues.TryGetValue(candle); return trades != null ? trades.SyncGet(c => c.ToArray()) : Enumerable.Empty<ICandleBuilderSourceValue>(); }
public void LayoutFileInvalidName() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(LayoutTests.TestDataDirectory, @"LayoutFileInvalidName\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(27, "The LayoutFile/@Name attribute's value, 'File?*|Name.txt', is not a valid long name because it contains illegal characters. Legal long names contain no more than 260 characters and must contain at least one non-period character. Any character except for the follow may be used: \\ ? | > < : / * \".", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 27; candle.Run(); }
void HighlightCandle(Candle next_candle) { if(CurrentMarker == null) { CurrentMarker = Instantiate(NextCandlePrefab); } CurrentMarker.transform.parent = next_candle.transform; CurrentMarker.transform.localPosition = Vector3.zero; CurrentMarker.GetComponent<Animator> ().SetTrigger ("zoom_in"); }
private Candle GetCandle(NamedPipeClientStream pipe) { Candle candle = new Candle(); byte[] buffer; // Получение DateTime // bool checkDateTime = ReadPipeData(pipe, 8, out buffer); if (checkDateTime) { long fileTime = BitConverter.ToInt64(buffer, 0); candle.Date = DateTime.FromFileTimeUtc(fileTime); } else { throw new Exception("Ошибка: не удалось получить Date."); } // Получение Open // bool checkOpen = ReadPipeData(pipe, 8, out buffer); if (checkOpen) { candle.Open = BitConverter.ToDouble(buffer, 0); } else { throw new Exception("Ошибка: не удалось получить Open."); } // Получение High // bool checkHigh = ReadPipeData(pipe, 8, out buffer); if (checkHigh) { candle.High = BitConverter.ToDouble(buffer, 0); } else { throw new Exception("Ошибка: не удалось получить High."); } // Получение Low // bool checkLow = ReadPipeData(pipe, 8, out buffer); if (checkLow) { candle.Low = BitConverter.ToDouble(buffer, 0); } else { throw new Exception("Ошибка: не удалось получить Low."); } // Получение Close // bool checkClose = ReadPipeData(pipe, 8, out buffer); if (checkClose) { candle.Close = BitConverter.ToDouble(buffer, 0); } else { throw new Exception("Ошибка: не удалось получить Close."); } // Получение Volume // bool checkVolume = ReadPipeData(pipe, 8, out buffer); if (checkVolume) { candle.Volume = BitConverter.ToDouble(buffer, 0); } else { throw new Exception("Ошибка: не удалось получить Volume."); } return(candle); }
/// <summary> /// Формирование последней свечи по MarketHistory /// </summary> /// <returns></returns> private async Task <List <BaseTypes.Candle> > CandleByMarketHistory(BaseTypes.Market Market, Candle_Interval Interval, InvokePrint Print) { try { List <Trade> mhist = await GetMarketHistory(Market, Print); Candle lastCandle = await GetLastCandle(Market, Interval, Print); List <BaseTypes.Candle> resCandles = new List <BaseTypes.Candle>(); DateTime NTime = StrategyTool.AddPeriod(lastCandle.Time, Interval); if (mhist[0].Timestamp > NTime && ConvertTime(mhist[0].Timestamp) != ConvertTime(NTime)) { resCandles.Add(new BaseTypes.Candle { Open = mhist[0].Price, Low = mhist[0].Price, Hight = mhist[0].Price, Close = mhist[0].Price, Time = NTime }); } else { return(null); } List <DateTime> times = new List <DateTime>(); times.Add(NTime); while (times.Last() < mhist[0].Timestamp) { times.Add(StrategyTool.AddPeriod(times.Last(), Interval)); } times.RemoveAt(times.Count - 1); int Cpos = times.Count - 1; decimal Hval = mhist[0].Price; decimal Lval = mhist[0].Price; for (int i = 1; i < mhist.Count - 1; i++) { if (mhist[i].Timestamp < times[Cpos]) //оформление свечи { resCandles.Last().Hight = Hval; resCandles.Last().Low = Lval; resCandles.Last().Open = mhist[i - 1].Price; Hval = mhist[i].Price; Lval = mhist[i].Price; Cpos = Cpos - 1; if (Cpos < 0) { break; } resCandles.Add(new BaseTypes.Candle { Open = mhist[i].Price, Low = mhist[i].Price, Hight = mhist[i].Price, Close = mhist[i].Price, Time = times[Cpos] }); } else //обновление max/min текущей свечи { if (Hval < mhist[i].Price) { Hval = mhist[i].Price; } if (Lval > mhist[i].Price) { Lval = mhist[i].Price; } } } if (Cpos >= 0) { resCandles.Last().Hight = Hval; resCandles.Last().Low = Lval; resCandles.Last().Open = mhist[mhist.Count - 1].Price; } resCandles.Reverse(); if (resCandles.Count > 0) { var tmp = await bittrex.GetTicker(Market.MarketName); decimal lastValue = tmp.Last.Value; if (lastValue > resCandles.Last().Hight) { resCandles.Last().Hight = lastValue; } else if (lastValue < resCandles.Last().Low) { resCandles.Last().Low = lastValue; } else { resCandles.Last().Close = lastValue; } } return(resCandles); } catch (Exception ex) { System.Media.SystemSounds.Beep.Play(); Print("Ошибка BittrexApi CandleByMarketHistory: " + ex.Message); return(null); } }
/// <summary> /// Начать выгрузку данных по инструменту. /// </summary> /// <param name="namePaper">имя бумаги которую будем запускать</param> /// <param name="timeFrameBuilder">объект несущий </param> /// <returns>В случае удачи возвращает CandleSeries /// в случае неудачи null</returns> public CandleSeries StartThisSecurity(string namePaper, TimeFrameBuilder timeFrameBuilder) { try { if (_lastStartServerTime.AddSeconds(15) > DateTime.Now) { return(null); } lock (_lockerStarter) { if (namePaper == "") { return(null); } // надо запустить сервер если он ещё отключен if (ServerStatus != ServerConnectStatus.Connect) { //MessageBox.Show("Сервер не запущен. Скачивание данных прервано. Инструмент: " + namePaper); return(null); } if (_securities == null || _portfolios == null) { Thread.Sleep(5000); return(null); } if (_lastStartServerTime != DateTime.MinValue && _lastStartServerTime.AddSeconds(15) > DateTime.Now) { return(null); } Security security = null; for (int i = 0; _securities != null && i < _securities.Count; i++) { if (_securities[i].Name == namePaper) { security = _securities[i]; break; } } if (security == null) { return(null); } if (_connectedContracts == null) { _connectedContracts = new List <string>(); } if (_connectedContracts.Find(s => s == security.Name) == null) { _connectedContracts.Add(security.Name); } _tickStorage.SetSecurityToSave(security); // 2 создаём серию свечек CandleSeries series = new CandleSeries(timeFrameBuilder, security); if (NeadToGetCandles(timeFrameBuilder.TimeFrame)) { // подгружаем в серию свечки, если коннектор это позволяет short count = 500; string price = "MBA"; string instrument = security.Name; string granularity = GetTimeFrameInOandaFormat(timeFrameBuilder.TimeFrame).ToString(); var parameters = new Dictionary <string, string>(); parameters.Add("price", price); parameters.Add("granularity", granularity); parameters.Add("count", count.ToString()); Task <List <CandlestickPlus> > result = Rest20.GetCandlesAsync(instrument, parameters); while (!result.IsCanceled && !result.IsCompleted && !result.IsFaulted) { Thread.Sleep(10); } List <CandlestickPlus> candleOanda = result.Result; List <Candle> candlesOsEngine = new List <Candle>(); for (int i = 0; i < candleOanda.Count; i++) { Candle newCandle = new Candle(); newCandle.Open = Convert.ToDecimal(candleOanda[i].bid.o); newCandle.High = Convert.ToDecimal(candleOanda[i].bid.h); newCandle.Low = Convert.ToDecimal(candleOanda[i].bid.l); newCandle.Close = Convert.ToDecimal(candleOanda[i].bid.c); newCandle.TimeStart = DateTime.Parse(candleOanda[i].time); newCandle.State = CandleStates.Finished; newCandle.Volume = candleOanda[i].volume; candlesOsEngine.Add(newCandle); } series.CandlesAll = candlesOsEngine; } _candleManager.StartSeries(series); SendLogMessage("Инструмент " + series.Security.Name + "ТаймФрейм " + series.TimeFrame + " успешно подключен на получение данных и прослушивание свечек", LogMessageType.System); return(series); } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); return(null); } }
public override float Calc(Candle candle) { float r = GetFirstRSI(candle); return(r); }
public override bool Paint() { if (_series.OHLCType == SeriesTypeOHLC.Volume) { return(false); } //Find Series Series open = _series._chartPanel.GetSeriesOHLCV(_series, SeriesTypeOHLC.Open); if (open == null || open.RecordCount == 0 || open.Painted) { return(false); } Series high = _series._chartPanel.GetSeriesOHLCV(_series, SeriesTypeOHLC.High); if (high == null || high.RecordCount == 0 || high.Painted) { return(false); } Series low = _series._chartPanel.GetSeriesOHLCV(_series, SeriesTypeOHLC.Low); if (low == null || low.RecordCount == 0 || low.Painted) { return(false); } Series close = _series._chartPanel.GetSeriesOHLCV(_series, SeriesTypeOHLC.Close); if (close == null || close.RecordCount == 0 || close.Painted) { return(false); } _series = close; open.Painted = high.Painted = low.Painted = close.Painted = true; CalculateCandleSpacing(); if (ChartX._barSpacing < 0) { return(false); } _upColor = _series._upColor.HasValue ? _series._upColor.Value : ChartX.UpColor; _downColor = _series._downColor.HasValue ? _series._downColor.Value : ChartX.DownColor; if (_oldOptimizePainting.HasValue && _oldOptimizePainting.Value != ChartX.OptimizePainting) { if (!ChartX.OptimizePainting) { Canvas c = _series._chartPanel._rootCanvas; c.Children.Remove(_pathCandlesDown); c.Children.Remove(_pathCandlesUp); c.Children.Remove(_pathWicksUp); c.Children.Remove(_pathWicksDown); _pathCandlesDown = null; _pathCandlesUp = null; _pathWicksUp = null; _pathWicksDown = null; } else { _candles.RemoveAll(); } } _oldOptimizePainting = ChartX.OptimizePainting; if (ChartX.OptimizePainting) { return(PaintOptimized(new[] { open, high, low, close }, _series)); } if (!_subscribedToCustomBrush) { _subscribedToCustomBrush = true; ChartX.OnCandleCustomBrush += ChartX_OnCandleCustomBrush; } //bool setBrushes = false; if (!_old3DStyle.HasValue || _old3DStyle.Value != ChartX.ThreeDStyle || !_oldUpColor.HasValue || _oldUpColor.Value != _upColor || !_oldDownColor.HasValue || _oldDownColor.Value != _downColor || (ChartX._candleDownOutlineColor.HasValue && ChartX._candleDownOutlineColor.Value != _oldCandleDownOutline) || ChartX._candleUpOutlineColor.HasValue && ChartX._candleUpOutlineColor.Value != _oldCandleUpOutline) { //setBrushes = true; _old3DStyle = ChartX.ThreeDStyle; _oldUpColor = _upColor; _oldDownColor = _downColor; _upBrush = !ChartX.ThreeDStyle ? (Brush) new SolidColorBrush(_upColor) : new LinearGradientBrush { StartPoint = new Point(0, 0.5), EndPoint = new Point(1, 0.5), GradientStops = { new GradientStop { Color = _upColor, Offset = 0 }, new GradientStop { Color = Constants.FadeColor, Offset = 1.25 } } }; #if WPF _upBrush.Freeze(); #endif _downBrush = !ChartX.ThreeDStyle ? (Brush) new SolidColorBrush(_downColor) : new LinearGradientBrush { StartPoint = new Point(0, 0.5), EndPoint = new Point(1, 0.5), GradientStops = { new GradientStop { Color = _downColor, Offset = 0 }, new GradientStop { Color = Constants.FadeColor, Offset = 1.25 } } }; #if WPF _downBrush.Freeze(); #endif if (ChartX._candleDownOutlineColor.HasValue) { _oldCandleDownOutline = ChartX._candleDownOutlineColor.Value; _candleDownOutlineBrush = new SolidColorBrush(ChartX._candleDownOutlineColor.Value); #if WPF _candleDownOutlineBrush.Freeze(); #endif } if (ChartX._candleUpOutlineColor.HasValue) { _oldCandleUpOutline = ChartX._candleUpOutlineColor.Value; _candleUpOutlineBrush = new SolidColorBrush(ChartX._candleUpOutlineColor.Value); #if WPF _candleUpOutlineBrush.Freeze(); #endif } } int n; _candles.C = _series._chartPanel._rootCanvas; _candles.Start(); for (n = ChartX._startIndex; n < ChartX._endIndex; n++) { if (!open[n].Value.HasValue || !high[n].Value.HasValue || !low[n].Value.HasValue || !close[n].Value.HasValue) { continue; } Candle candle = _candles.GetPaintObject(_upBrush, _downBrush); candle.Init(_series); //if (setBrushes) //because if we have a small number of bars, then enlarge the new brushes won't be propagated to new candles. candle.SetBrushes(_upBrush, _downBrush, _candleUpOutlineBrush, _candleDownOutlineBrush); candle.SetValues(open[n].Value.Value, high[n].Value.Value, low[n].Value.Value, close[n].Value.Value, ChartX._barSpacing, _halfwick, n - ChartX._startIndex); } _candles.Stop(); _candles.Do(c => c.ZIndex = ZIndexConstants.PriceStyles1); return(true); }
public RenkoChart(ChartView BaseChart) { AuxChartView = new ChartView(); candle = new Candle(); renko = new Renko(); this.BaseChart = BaseChart; candle.FillSampleValues(12); BaseChart.Chart.Title.Text = "Renko"; BaseChart.Chart.Axes.Left.AxisPen.Visible = true; BaseChart.Chart.Axes.Left.Visible = true; BaseChart.Chart.Axes.Bottom.Visible = true; BaseChart.Chart.Series.Add(renko); BaseChart.Chart.Series.Add(candle); //renko.Clear(); for (int i = 0; i < candle.Count; i++) { renko.Add(candle.CloseValues[i]); } // box size set to 2 //renko.BoxSize = 5; //renko.Pointer.Style = PointerStyles.Rectangle; //renko.Title = "Renko (Close values)"; candle.Title = "Trading Data"; candle.HorizAxis = HorizontalAxis.Bottom; candle.VertAxis = VerticalAxis.Left; BaseChart.Chart.Axes.Left.Title.Visible = false; BaseChart.Chart.Axes.Bottom.Title.Visible = false; BaseChart.Chart.Axes.Bottom.Labels.Visible = true; BaseChart.Chart.Axes.Left.Labels.Visible = true; BaseChart.Chart.Axes.Left.AxisPen.Visible = true; BaseChart.Chart.Axes.Bottom.Visible = true; BaseChart.Chart.Axes.Bottom.Ticks.Visible = false; BaseChart.Chart.Axes.Left.Increment = 10; BaseChart.Chart.Panel.Left = 0; BaseChart.Chart.Axes.Bottom.RelativePosition = 53; BaseChart.Chart.Axes.Left.EndPosition = 47; customLeftRenko = CreateAxis(); customBottomRenko = CreateAxis(); //Themes.UpdateAxes(customLeftRenko, customBottomRenko); //BaseChart.Chart.Axes.Custom.Add(customLeftRenko); //BaseChart.Chart.Axes.Custom.Add(customBottomRenko); customLeftRenko.Horizontal = false; customLeftRenko.StartPosition = 53; customLeftRenko.EndPosition = 100; customLeftRenko.Grid = BaseChart.Chart.Axes.Left.Grid; customLeftRenko.AxisPen.Visible = true; customLeftRenko.Increment = 10; customLeftRenko.AxisPen.Color = customLeftRenko.AxisPen.GetColor().AddLuminosity(-0.2); customLeftRenko.Ticks.Transparency = 100; customBottomRenko.Horizontal = true; customBottomRenko.StartPosition = 0; customBottomRenko.EndPosition = 100; customBottomRenko.RelativePosition = 0; customBottomRenko.AxisPen.Visible = true; customBottomRenko.Ticks.Visible = false; customBottomRenko.AxisPen.Color = customBottomRenko.AxisPen.GetColor().AddLuminosity(-0.2); //renko.HorizAxis = HorizontalAxis.Bottom; //renko.VertAxis = VerticalAxis.Custom; //renko.CustomHorizAxis = customBottomRenko; //renko.CustomVertAxis = customLeftRenko; BaseChart.Chart.Axes.Bottom.Automatic = true; BaseChart.Chart.Axes.Bottom.AutomaticMaximum = true; BaseChart.Chart.Axes.Bottom.AutomaticMinimum = true; BaseChart.Chart.Axes.Left.SetMinMax(BaseChart.Chart.Axes.Left.MinYValue, BaseChart.Chart.Axes.Left.MaxYValue); customLeftRenko.SetMinMax(BaseChart.Chart.Axes.Left.MinYValue, BaseChart.Chart.Axes.Left.MaxYValue); customBottomRenko.Automatic = true; customBottomRenko.AutomaticMaximum = true; customBottomRenko.AutomaticMinimum = true; }
public void UpdateCandle(int id, Candle newCandleData) { _candleRepository.UpdateCandle(id, newCandleData); }
public void ComponentSearchInvalidGuid() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(ComponentSearchTests.TestDataDirectory, @"ComponentSearchInvalidGuid\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(9, "The util:ComponentSearch/@Guid attribute's value, 'Not_A_Product_Guid', is not a legal guid value.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 9; candle.Extensions.Add("WixUtilExtension"); candle.Run(); }
void Candle_OnCandleLit(Candle sender) { if(correct_sequence[0] == sender) { sender.CorrectCandle(); correct_sequence.RemoveAt(0); Summoner.sngl.CorrectCandle(); if(correct_sequence.Count > 0) { HighlightCandle(correct_sequence[0]); } } else { int i = correct_sequence.FindIndex(c => c == sender); // Remove the candle from the sequence, at this point... if (i < 0) return; correct_sequence.RemoveAt(i); Summoner.sngl.WrongCandleLit(); sender.IncorrectCandle(); } if (correct_sequence.Count == 0) { // Also hide highligher if (CurrentMarker != null) CurrentMarker.SetActive(false); Summoner.sngl.Summon(); } }
public List <Candle> GetStaticData(BarDataScale dataScale, string symbol, string suffix, out string securityName) { string pipeName = GetPipeName(dataScale, symbol, suffix, false); List <Candle> candles = new List <Candle>(); using (NamedPipeClientStream quikPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None)) { try { quikPipe.Connect(1000); } catch (TimeoutException) { throw new Exception("Не удалось подключиться к каналу передачи данных."); } catch (IOException) { throw new Exception("Канал передачи данных занят."); } // Проверка версии протокола CheckProtocolVersion(quikPipe); // Получение полного имени инструмента securityName = GetSymbolName(quikPipe); // Получение таймфрейма для инструмента BarDataScale pipeScale = GetDataScale(quikPipe); if (!pipeScale.Equals(dataScale)) { throw new Exception("Таймфрем запроса не совпадает с таймфреймом полученных котировок."); } bool update = true; while (update) { byte[] buffer; // Получение указателя // short pointer = 0; bool checkPointer = ReadPipeData(quikPipe, 2, out buffer); if (checkPointer) { pointer = BitConverter.ToInt16(buffer, 0); } else { throw new Exception("Не удалось получить указатель"); } switch (pointer) { // Неизвестный указатель: // не удалось установить назначение // в комментах была следующая строка "Stop Session for %s" // case unknownPointer: _logger.Debug(string.Format("[{0}.{1}] Неизвестный указатель в последовательности данных.", symbol, suffix)); break; // Получение количества свечей // case candlesCountPointer: bool checkCandlesCount = ReadPipeData(quikPipe, 4, out buffer); int candlesCount = 0; if (checkCandlesCount) { candlesCount = BitConverter.ToInt32(buffer, 0); } else { throw new Exception("Не удалось получить количество свечей."); } break; // Получение данных свечи // case candlesDataPointer: try { Candle candle = GetCandle(quikPipe); if (pipeScale.IsIntraday) { candle.Date = candle.Date.AddMinutes(pipeScale.BarInterval); } candles.Add(candle); } catch (Exception ex) { _logger.Debug(string.Format("[{0}.{1}] {2}", symbol, suffix, ex)); update = false; } break; // Получение количества оставшихся свечей // case candlesLeftPointer: bool chekCandlesLeft = ReadPipeData(quikPipe, 4, out buffer); int candlesLeft = 0; if (chekCandlesLeft) { candlesLeft = BitConverter.ToInt32(buffer, 0); } if (candlesLeft == 0) { update = false; } break; // Неверная последовательность // default: throw new Exception(string.Format("Неверная последовательность данных. Последняя метка: {0}", pointer)); } } } return(candles); }
/// <summary> /// Открытие по паттерну /// </summary> /// <param name="indicators">Индикаторы</param> /// <param name="candles">Свечи</param> /// <param name="patterns">Список паттернов</param> private void OpenByPattrn(List <IIndicator> indicators, List <Candle> candles, List <string> patterns) { if (!ValidateParams()) { return; } if (!CanOpenPosition()) { return; } if (candles.Count < 2) { return; } bool CanFindPattern = false; for (int i = 1; i <= 1; i++) { Candle candle = candles[candles.Count - i]; List <PriceLevleLine.levlel> lvl = PriceLevleLine.LevleData.FindAll(x => x.Value <= candle.High && x.Value >= candle.Low); if (lvl != null && lvl.Count > 0) { List <PriceLevleLine.levlel> filter = GetFilterlvl(); foreach (PriceLevleLine.levlel l in lvl) { if (filter != null && filter.Find(f => f.Value == l.Value) != null) { continue; } CanFindPattern = true; } } } if (TradeSide == Side.Buy && candles[candles.Count - 2].Close < LastSessionEndPrice) { CanFindPattern = false; } if (TradeSide == Side.Sell && candles[candles.Count - 2].Close > LastSessionEndPrice) { CanFindPattern = false; } if (!CanFindPattern) { return; } // открытие позиций по патерну List <Pattern> signal = Pattern.GetValidatePatterns(candles, indicators, patterns); if (signal.Count > 0 && signal[0].isPattern) { if (signal.Count != 0 && signal[0].isPattern) { if (signal[0].Side == TradeSide) { _tab.SetNewLogMessage("Открытие по патерну " + signal[0].GetType().Name, LogMessageType.Signal); OpenPosition(signal[0].Side, candles[candles.Count - 1].Close, signal[0].GetType().Name); } } } }
public void Stream(string symbol, CancellationToken token) { BarDataScale dataScale = new BarDataScale(BarScale.Minute, 1); string pipeName = GetPipeName(dataScale, symbol, string.Empty, false); using (NamedPipeClientStream quikPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None)) { try { quikPipe.Connect(1000); // Проверка версии протокола CheckProtocolVersion(quikPipe); // Получение полного имени инструмента string securityName = GetSymbolName(quikPipe); // Получение таймфрейма для инструмента BarDataScale pipeScale = GetDataScale(quikPipe); bool sendQuote = false; int candlesCount = -1; while (true) { token.ThrowIfCancellationRequested(); byte[] buffer; // Получение указателя // short pointer = 0; bool checkPointer = ReadPipeData(quikPipe, 2, out buffer); if (checkPointer) { pointer = BitConverter.ToInt16(buffer, 0); } else { throw new Exception("Не удалось получить указатель"); } switch (pointer) { // Неизвестный указатель: // не удалось установить назначение // в комментах была следующая строка "Stop Session for %s" // case unknownPointer: _logger.Debug(string.Format("[{0}] Неизвестный указатель в последовательности данных", symbol)); break; // Получение количества свечей // case candlesCountPointer: bool checkCandlesCount = ReadPipeData(quikPipe, 4, out buffer); if (!checkCandlesCount) { throw new Exception("Не удалось получить количество свечей"); } if (!sendQuote) { candlesCount = BitConverter.ToInt32(buffer, 0); } break; // Получение данных свечи // case candlesDataPointer: try { DateTime timeStamp = DateTime.Now; Candle candle = GetCandle(quikPipe); if (sendQuote && NewQuote != null) { Quote quote = new Quote() { Symbol = symbol, TimeStamp = timeStamp.Minute > candle.Date.Minute ? candle.Date.AddSeconds(59) : timeStamp, Price = candle.Close, Size = candle.Volume, }; NewQuote(quote, candle); } candlesCount--; if (!sendQuote && candlesCount == 0) { sendQuote = true; } } catch (Exception ex) { _logger.Debug(string.Format("[{0}] {1}", symbol, ex)); } break; // Получение количества оставшихся свечей // case candlesLeftPointer: ReadPipeData(quikPipe, 4, out buffer); break; // Неверная последовательность // default: break; } } } catch (OperationCanceledException) { } catch (Exception ex) { _logger.Error("[STREAM] " + ex); } } }
public CandleBuilder(Candle lastData, CandleType type) { this.LastData = lastData; this.type = type; }
/// <summary> /// To get the part value. /// </summary> /// <param name="current">The current candle.</param> /// <param name="prev">The previous candle.</param> /// <returns>Value.</returns> protected abstract decimal GetValue(Candle current, Candle prev);
/// <summary> /// To get all data by the candle. /// </summary> /// <param name="series">Candles series.</param> /// <param name="candle">The candle for which you need to find data.</param> /// <returns>Found data.</returns> public IEnumerable<ICandleBuilderSourceValue> GetValues(CandleSeries series, Candle candle) { return GetInfo(series).GetValues(candle); }
private void Update() { Ray ray = new Ray(transform.position, transform.forward); RaycastHit raycastHit; if (Physics.Raycast(ray, out raycastHit, interactDistance, layerMask)) { // если рука не отображается if (!handImage.gameObject.activeSelf) { // показать картинку handImage.gameObject.SetActive(true); } Debug.Log("Ray hit object: " + raycastHit.transform.name); // если нажата клавиша Е if (Input.GetKeyDown(KeyCode.E)) { // если смотрю на батарейки if (raycastHit.transform.tag == "Battery") { // пополнить заряд фонарика flashLight.AddEnergy(); // уничтожить батарейки Destroy(raycastHit.transform.gameObject); } if (raycastHit.transform.tag == "Paper") { //Включаем панель paperPanel.SetActive(true); //Отключаем игрока playerController.enabled = false; } //если смотрю на ключ if (raycastHit.transform.tag == "Key") { //вызов метода подбора в ключе Key key = raycastHit.transform.GetComponent <Key>(); if (key != null) { key.PickUp(); } } if (raycastHit.transform.tag == "Candle") { // получить объект свечу Candle candle = raycastHit.transform.GetComponent <Candle>(); if (candle != null) { // зажечь/потушить свечу candle.ChangeLight(); } } if (raycastHit.transform.tag == "Door") { if (hasKey == false) { //проиграть звук закрытой двери // AudioSource Door door = raycastHit.transform.GetComponent <Door>(); if (door != null) { door.ChangeDoorState(); } } } if (raycastHit.transform.tag == "FirstAid") { gameObject.GetComponentInParent <HealthHero>().Heal(); Destroy(raycastHit.transform.gameObject); } if (raycastHit.transform.tag == "WoodCodeBox") { gameObject.GetComponentsInParent <RigidbodyFirstPersonController>()[0].enabled = false; woodBoxPanel.SetActive(true); woodBox = raycastHit.transform.gameObject; } } else if (Input.GetKeyDown(KeyCode.Escape)) { if (raycastHit.transform.tag == "Paper" && isReading) { gameObject.GetComponentsInParent <RigidbodyFirstPersonController>()[0].enabled = true; isReading = false; paperPanel.SetActive(false); } else if (raycastHit.transform.tag == "WoodCodeBox") { woodBoxPanel.SetActive(false); gameObject.GetComponentsInParent <RigidbodyFirstPersonController>()[0].enabled = true; } } } else { //выключаем картинку handImage.gameObject.SetActive(false); } }
public void PackageSourceFileMissing() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(PackageTests.TestDataDirectory, @"PackageSourceFileMissing\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(10, "The MsiPackage/@SourceFile attribute was not found; it is required.", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(10, "The MspPackage/@SourceFile attribute was not found; it is required.", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(10, "The MsuPackage/@SourceFile attribute was not found; it is required.", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(10, "The ExePackage/@SourceFile attribute was not found; it is required.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 10; candle.Run(); }
//Логика торговой стратегии private void ProcessCandle(Candle candle) { try { //Добавляем новую свечку для расчетов в индикаторы //Добавляем до проверки актуальности данных, так как возможна предзагрузка исторических данных var top = _top.Add(candle.ClosePrice); var bottom = _bottom.Add(candle.ClosePrice); //Проверка актуальности данных if (!GetRealTimeData()) { return; } //Если индикаторы не сформированы, то ничего не делаем if (!_top.IsFormed || !_bottom.IsFormed) { return; } //Текущая позиция по выбранному коннектору и инструменту var position = GetTradeInfo().Position; if (candle.ClosePrice <= bottom && position <= 0) { var limitOrder = new Order { Type = OrderType.Limit, Direction = Direction.Buy, Volume = position < 0 ? -position : _volume, //Закрываем полностью позицию или открываем новую Price = candle.ClosePrice }; _customValuesBuy.Add(candle.CloseTime, (double)(limitOrder.Price + GetSecurity().Tick * 25), $"BUY ORDER\nTime: {candle.CloseTime.ToString("dd.MM.yyyy HH:mm:ss.fff")}\nVolume: {limitOrder.Volume}"); //Отправляем лимитную заявку на регистрацию RegisterOrder(limitOrder); } if (candle.ClosePrice >= top && position >= 0) { var limitOrder = new Order { Type = OrderType.Limit, Direction = Direction.Sell, Volume = position < 0 ? -position : _volume, Price = candle.ClosePrice }; _customValuesSell.Add(candle.CloseTime, (double)(limitOrder.Price - GetSecurity().Tick *25), $"SELL ORDER\nTime: {candle.CloseTime.ToString("dd.MM.yyyy HH:mm:ss.fff")}\nVolume: {limitOrder.Volume}"); //Отправляем лимитную заявку на регистрацию RegisterOrder(limitOrder); } } catch (Exception ex) { ExceptionMessage(ex, "ProcessCandle"); } }
public void VariableValueMissing() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(VariableTests.TestDataDirectory, @"VariableValueMissing\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(10, "The Variable/@Value attribute was not found; it is required.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 10; candle.Run(); }
DateTimeOffset IMarketDataStorageInfo <Candle> .GetTime(Candle data) { return(data.OpenTime); }
public void ComponentSearchInvalidResultValue() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(ComponentSearchTests.TestDataDirectory, @"ComponentSearchInvalidResultValue\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(21, "The util:ComponentSearch/@Result attribute's value, 'NotState', is not one of the legal options: 'Directory', 'State', or 'KeyPath'.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 21; candle.Extensions.Add("WixUtilExtension"); candle.Run(); }
public List <Candle> GetCandles(Security security, DateTime startTime, DateTime endTime, string minutesCount) { //http://mfd.ru/export/handler.ashx/temp.txt?TickerGroup=16&Tickers=1463 //&Alias=false&Period=1&timeframeValue=1 //&timeframeDatePart=day&StartDate=01.01.2010 //&EndDate=24.04.2020 //&SaveFormat=0&SaveMode=1&FileName=%D0%A1%D0%B1%D0%B5%D1%80%D0%B1%D0%B0%D0%BD%D0%BA_1min_01012010_24042020.txt //&FieldSeparator=%253b&DecimalSeparator=.&DateFormat=yyyyMMdd&TimeFormat=HHmmss&DateFormatCustom=&TimeFormatCustom=&AddHeader=true&RecordFormat=0&Fill=false string fileName = "tempFile" + ".txt"; string requestStr = "http://mfd.ru/export/handler.ashx/;" + fileName; requestStr += "?TickerGroup=" + security.NameClass.Split('#')[1]; requestStr += "&Tickers=" + security.NameId.Split('#')[1]; requestStr += "&Alias=false&Period=" + minutesCount; requestStr += "&timeframeValue =" + minutesCount; requestStr += "&timeframeDatePart=day&StartDate=" + startTime.Date.ToString("dd/MM/yyyy").Replace("/", "."); requestStr += "&EndDate=" + endTime.Date.ToString("dd/MM/yyyy").Replace("/", "."); requestStr += "&SaveFormat=0&SaveMode=1&FileName=" + fileName; requestStr += "&FieldSeparator=%253b&DecimalSeparator=.&DateFormat=yyyyMMdd&TimeFormat=HHmmss&DateFormatCustom=&TimeFormatCustom=&AddHeader=true&RecordFormat=0&Fill=false"; //https://mfd.ru/export/handler.ashx/_RTS_(RI)_1hour_01042010_28042020.txt? //TickerGroup=26 // &Tickers=5* // &Alias=false //&Period=6 // &timeframeValue=1 // &timeframeDatePart=day // &StartDate=01.04.2010 // &EndDate=28.04.2020 // &SaveFormat=0 // &SaveMode=0 // &FileName=_RTS_(RI)_1hour_01042010_28042020.txt // &FieldSeparator=%253b // &DecimalSeparator=. // &DateFormat=yyyyMMdd // &TimeFormat=HHmmss // &DateFormatCustom= // &TimeFormatCustom= // &AddHeader=false // &RecordFormat=3 // &Fill=false string response = GetFileRequest(requestStr); string[] lines = response.Split('\n'); List <Candle> result = new List <Candle>(); for (int i = 1; i < lines.Length; i++) { if (string.IsNullOrWhiteSpace(lines[i])) { continue; } string[] line = lines[i].Split(';'); int year = Convert.ToInt32(line[2].Substring(0, 4)); int month = Convert.ToInt32(line[2].Substring(4, 2)); int day = Convert.ToInt32(line[2].Substring(6, 2)); int hour = Convert.ToInt32(line[3].Substring(0, 2)); int minute = Convert.ToInt32(line[3].Substring(2, 2)); int second = Convert.ToInt32(line[3].Substring(4, 2)); DateTime timeStart = new DateTime(year, month, day, hour, minute, second); Candle candle = new Candle(); candle.Open = line[4].ToDecimal(); candle.High = line[5].ToDecimal(); candle.Low = line[6].ToDecimal(); candle.Close = line[7].ToDecimal(); candle.Volume = line[8].ToDecimal(); candle.TimeStart = timeStart; result.Add(candle); } return(result); }
// creating alerts // создание алертов /// <summary> /// load new data point from chart /// загрузить с чарта новую точку с данными /// </summary> /// <param name="arrayCandles">array of candles/массив свечек</param> /// <param name="numberCandle">candle index/индекс свечи</param> /// <param name="valueY">igrick value/значение игрик</param> public void SetFormChart(List <Candle> arrayCandles, int numberCandle, decimal valueY) { _arrayCandles = arrayCandles; if (_waitOne == false && _waitTwo == false && _waitHorisont == false) { return; } if (arrayCandles == null || numberCandle < 0 || numberCandle > arrayCandles.Count || valueY <= 0 || arrayCandles.Count < 10) { return; } // find candle, which stuck // находим свечку, в которую ткнули Candle candle = arrayCandles[numberCandle]; if (_waitOne) { if (candle.TimeStart == _candleTwoTime) { MessageBox.Show("Линия не может быть построена из двух точек на одной оси Х"); return; } _candleOneTime = candle.TimeStart; _candleOneValue = valueY; _candleOneNumber = numberCandle; _waitOne = false; _waitTwo = true; return; } else if (_waitTwo) { if (candle.TimeStart == _candleOneTime) { MessageBox.Show("Линия не может быть построена из двух точек на одной оси Х"); return; } _candleTwoTime = candle.TimeStart; _candleTwoValue = valueY; _candleTwoNumber = numberCandle; _waitTwo = false; } if (_waitHorisont) { _candleOneTime = candle.TimeStart; _candleOneValue = valueY; _candleOneNumber = numberCandle; if (numberCandle != 0) { _candleTwoTime = arrayCandles[0].TimeStart; _candleTwoValue = valueY; _candleTwoNumber = 0; } else { _candleTwoTime = arrayCandles[3].TimeStart; _candleTwoValue = valueY; _candleTwoNumber = 3; } _waitHorisont = false; } if (_candleOneTime != DateTime.MinValue && _candleTwoTime != DateTime.MinValue) { // swap points if they are not in correct order //меняем местами точки, если они установлены не в правильном порядке if (_candleOneNumber > _candleTwoNumber) { int glassNumber = _candleTwoNumber; DateTime glassTime = _candleTwoTime; decimal glassPoint = _candleTwoValue; _candleTwoNumber = _candleOneNumber; _candleTwoTime = _candleOneTime; _candleTwoValue = _candleOneValue; _candleOneNumber = glassNumber; _candleOneTime = glassTime; _candleOneValue = glassPoint; } SetReadyLineAlert(arrayCandles); } }
public virtual AlgResult Check(Candle candle) { return(AlgResult.Exit); }
static List <Candle> HA_W_Candles(Instrument instrument, out InstrumentDetails instrumentDetails) { instrumentDetails = new InstrumentDetails(); Candle haPreviounsCandle = null; Candle haCurrentCandle = null; List <Candle> haCandles = new List <Candle>(); int ema50Period = 50; int ema9Period = 9; List <Candle> candles = OANDA.Data.Prices.GetCandles(instrument.Name, ema50Period, "W"); instrumentDetails.Current = candles.LastOrDefault().Close; EMA ema50 = new EMA(ema50Period); EMA ema9 = new EMA(ema9Period); List <MyTrade.Core.Model.Candle> wcandles = MyTrade.Core.SqliteDataAccess.WeekyCandles.LoadCandles(instrument.Name); PivotPoints pps = new PivotPoints(); PivotPoint wpps = pps.Get(wcandles[wcandles.Count - 2], instrumentDetails.Current); instrumentDetails.W_PivotPoints = wpps; List <MyTrade.Core.Model.Candle> mcandles = MyTrade.Core.SqliteDataAccess.MonthlyCandles.LoadCandles(instrument.Name); PivotPoint mpps = pps.Get(mcandles[mcandles.Count - 2], instrumentDetails.Current); instrumentDetails.M_PivotPoints = mpps; instrumentDetails.TimeFrame = Core.Constants.TimeFrame.DAILY; for (int i = 0; i < candles.Count; i++) { instrumentDetails.Max = Math.Max(instrumentDetails.Max, candles[i].High); if (i == 0) { instrumentDetails.Min = candles[i].Low; instrumentDetails.Min = Math.Min(candles[i].Low, instrumentDetails.Min); haPreviounsCandle = HeikinAshi.GeneratePrevious(candles[i]); haCandles.Add(haPreviounsCandle); } else { haCurrentCandle = HeikinAshi.Generate(haPreviounsCandle, candles[i]); haCandles.Add(haCurrentCandle); haPreviounsCandle = haCurrentCandle; } if (i == (candles.Count - 1)) { if (instrumentDetails.EMAs == null) { instrumentDetails.EMAs = new List <Core.Model.Indicators.EMA>(); } ema50.AddDataPoint(candles[i].Close); ema9.AddDataPoint(candles[i].Close); instrumentDetails.EMAs.Add(new Core.Model.Indicators.EMA() { Period = 50, Value = ema50.Average }); instrumentDetails.EMAs.Add(new Core.Model.Indicators.EMA() { Period = 9, Value = ema9.Average }); } else { ema50.AddDataPoint(candles[i].Close); ema9.AddDataPoint(candles[i].Close); } } return(haCandles); }
private void RaiseCandleSeriesProcessing(CandleSeries series, Candle candle) { CandleSeriesProcessing?.Invoke(series, candle); }
void Candle_OnCandleExtinguished(Candle sender) { // Damn! Gotta put it back in place! // Also punish the player correct_sequence.Add(sender); Summoner.sngl.ExtinguishedCandle(); }
public abstract SignalAndValue Process(Candle candle);
public void PayloadGroupRefMissingId() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(PayloadTests.TestDataDirectory, @"PayloadGroupRefMissingId\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(10, @"The PayloadGroupRef/@Id attribute was not found; it is required.", WixMessage.MessageTypeEnum.Error)); candle.ExpectedExitCode = 10; candle.Run(); }
/// <summary> /// загрузить данные из папки /// </summary> private void LoadCandleFromFolder(string folderName) { string[] files = Directory.GetFiles(folderName); if (files.Length == 0) { return; } List <MinerCandleSeries> security = new List <MinerCandleSeries>(); for (int i = 0; i < files.Length; i++) { security.Add(new MinerCandleSeries()); security[security.Count - 1].FileAdress = files[i]; security[security.Count - 1].LogMessageEvent += TesterServer_LogMessageEvent; string name = files[i].Split('\\')[files[i].Split('\\').Length - 1]; security[security.Count - 1].Security = new Security(); security[security.Count - 1].Security.Name = name; security[security.Count - 1].Security.Lot = 1; security[security.Count - 1].Security.NameClass = "TestClass"; security[security.Count - 1].Security.Go = 1; security[security.Count - 1].Security.PriceStepCost = 1; security[security.Count - 1].Security.PriceStep = 1; // тф // шаг цены // начало // конец StreamReader reader = new StreamReader(files[i]); // свечи: 20110111,100000,19577.00000,19655.00000,19533.00000,19585.00000,2752 // тики 1 вар: 20150401,100000,86160.000000000,2 // тики 2 вар: 20151006,040529,3010,5,Buy/Sell/Unknown string str = reader.ReadLine(); try { // смотрим свечи ли в файле Candle candle = new Candle(); candle.SetCandleFromString(str); // в файле свечи. Смотрим какие именно security[security.Count - 1].TimeStart = candle.TimeStart; Candle candle2 = new Candle(); candle2.SetCandleFromString(reader.ReadLine()); security[security.Count - 1].TimeFrameSpan = candle2.TimeStart - candle.TimeStart; security[security.Count - 1].TimeFrame = GetTimeFrame(security[security.Count - 1].TimeFrameSpan); // шаг цены decimal minPriceStep = decimal.MaxValue; int countFive = 0; CultureInfo culture = new CultureInfo("ru-RU"); for (int i2 = 0; i2 < 20; i2++) { Candle candleN = new Candle(); candleN.SetCandleFromString(reader.ReadLine()); decimal open = (decimal)Convert.ToDouble(candleN.Open); decimal high = (decimal)Convert.ToDouble(candleN.High); decimal low = (decimal)Convert.ToDouble(candleN.Low); decimal close = (decimal)Convert.ToDouble(candleN.Close); if (open.ToString(culture).Split(',').Length > 1 || high.ToString(culture).Split(',').Length > 1 || low.ToString(culture).Split(',').Length > 1 || close.ToString(culture).Split(',').Length > 1) { // если имеет место вещественная часть int lenght = 1; if (open.ToString(culture).Split(',').Length > 1 && open.ToString(culture).Split(',')[1].Length > lenght) { lenght = open.ToString(culture).Split(',')[1].Length; } if (high.ToString(culture).Split(',').Length > 1 && high.ToString(culture).Split(',')[1].Length > lenght) { lenght = high.ToString(culture).Split(',')[1].Length; } if (low.ToString(culture).Split(',').Length > 1 && low.ToString(culture).Split(',')[1].Length > lenght) { lenght = low.ToString(culture).Split(',')[1].Length; } if (close.ToString(culture).Split(',').Length > 1 && close.ToString(culture).Split(',')[1].Length > lenght) { lenght = close.ToString(culture).Split(',')[1].Length; } if (lenght == 1 && minPriceStep > 0.1m) { minPriceStep = 0.1m; } if (lenght == 2 && minPriceStep > 0.01m) { minPriceStep = 0.01m; } if (lenght == 3 && minPriceStep > 0.001m) { minPriceStep = 0.001m; } if (lenght == 4 && minPriceStep > 0.0001m) { minPriceStep = 0.0001m; } if (lenght == 5 && minPriceStep > 0.00001m) { minPriceStep = 0.00001m; } if (lenght == 6 && minPriceStep > 0.000001m) { minPriceStep = 0.000001m; } if (lenght == 7 && minPriceStep > 0.0000001m) { minPriceStep = 0.0000001m; } } else { // если вещественной части нет int lenght = 1; for (int i3 = open.ToString(culture).Length - 1; open.ToString(culture)[i3] == '0'; i3--) { lenght = lenght * 10; } int lengthLow = 1; for (int i3 = low.ToString(culture).Length - 1; low.ToString(culture)[i3] == '0'; i3--) { lengthLow = lengthLow * 10; if (lenght > lengthLow) { lenght = lengthLow; } } int lengthHigh = 1; for (int i3 = high.ToString(culture).Length - 1; high.ToString(culture)[i3] == '0'; i3--) { lengthHigh = lengthHigh * 10; if (lenght > lengthHigh) { lenght = lengthHigh; } } int lengthClose = 1; for (int i3 = close.ToString(culture).Length - 1; close.ToString(culture)[i3] == '0'; i3--) { lengthClose = lengthClose * 10; if (lenght > lengthClose) { lenght = lengthClose; } } if (minPriceStep > lenght) { minPriceStep = lenght; } if (minPriceStep == 1 && open % 5 == 0 && high % 5 == 0 && close % 5 == 0 && low % 5 == 0) { countFive++; } } } if (minPriceStep == 1 && countFive == 20) { minPriceStep = 5; } security[security.Count - 1].Security.PriceStep = minPriceStep; security[security.Count - 1].Security.PriceStepCost = minPriceStep; // последняя дата string lastString = null; while (!reader.EndOfStream) { lastString = reader.ReadLine(); } Candle candle3 = new Candle(); candle3.SetCandleFromString(lastString); security[security.Count - 1].TimeEnd = candle3.TimeStart; reader.Close(); } catch (Exception) { security.Remove(security[security.Count - 1]); } finally { reader.Close(); } } // сохраняем бумаги if (security == null || security.Count == 0) { return; } if (_securities == null) { _securities = new List <Security>(); } for (int i = 0; i < security.Count; i++) { if (_securities.Find(security1 => security1.Name == security[i].Security.Name) == null) { _securities.Add(security[i].Security); } } // считаем время SecuritiesTester.AddRange(security); if (SecuritiesTester.Count != 0) { for (int i = 0; i < SecuritiesTester.Count; i++) { if ((TimeMin == DateTime.MinValue && SecuritiesTester[i].TimeStart != DateTime.MinValue) || (SecuritiesTester[i].TimeStart != DateTime.MinValue && SecuritiesTester[i].TimeStart < TimeMin)) { TimeMin = SecuritiesTester[i].TimeStart; TimeStart = SecuritiesTester[i].TimeStart; TimeNow = SecuritiesTester[i].TimeStart; } if (SecuritiesTester[i].TimeEnd != DateTime.MinValue && SecuritiesTester[i].TimeEnd > TimeMax) { TimeMax = SecuritiesTester[i].TimeEnd; TimeEnd = SecuritiesTester[i].TimeEnd; } SecuritiesTester[i].LoadCandles(); } } }
public void LayoutDirectoryRefIdMissing() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(LayoutTests.TestDataDirectory, @"LayoutDirectoryRefIdMissing\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(10, "The LayoutDirectoryRef/@Id attribute was not found; it is required.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 10; candle.Run(); }
private static void TestConnector_CandleSeriesProcessing(Candle obj) { Console.WriteLine($"Candle {{ OpenTime: {obj.OpenTime}, Pair: {obj.Pair}, OpenPrice: {obj.OpenPrice}, ClosePrice: {obj.ClosePrice} }}"); }
private void LoadNewCandle(Candle newCandle, int numberInArray) // добавить одну свечу на график { if (!CheckAccess()) { // перезаходим в метод потоком формы, чтобы не было исключения Dispatcher.Invoke(new Action <Candle, int>(LoadNewCandle), newCandle, numberInArray); return; } // свечи Series candleSeries = _chartForCandle.Series.FindByName("SeriesCandle"); if (candleSeries != null) { candleSeries.Points.RemoveAt(candleSeries.Points.Count - 1); // забиваем новую свечку candleSeries.Points.AddXY(numberInArray, newCandle.Low, newCandle.High, newCandle.Open, newCandle.Close); candleSeries.Points.Last().ToolTip = $"Low: {newCandle.Low}\nHigh: {newCandle.High}\nOpen: {newCandle.Open}\nClose: {newCandle.Close}\nVolume: {newCandle.Volume}"; // подписываем время candleSeries.Points[candleSeries.Points.Count - 1].AxisLabel = newCandle.Time.ToString(CultureInfo.InvariantCulture); // разукрышиваем в привычные цвета if (newCandle.Close > newCandle.Open) { candleSeries.Points[candleSeries.Points.Count - 1].Color = Color.Green; candleSeries.Points[candleSeries.Points.Count - 1].BorderWidth = 3; } else { candleSeries.Points[candleSeries.Points.Count - 1].Color = Color.Red; candleSeries.Points[candleSeries.Points.Count - 1].BackSecondaryColor = Color.Red; candleSeries.Points[candleSeries.Points.Count - 1].BorderWidth = 3; } ChartArea candleArea = _chartForCandle.ChartAreas.FindByName("ChartAreaCandle"); if (candleArea != null && candleArea.AxisX.ScrollBar.IsVisible) // если уже выбран какой-то диапазон { // сдвигаем представление вправо candleArea.AxisX.ScaleView.Scroll(_chartForCandle.ChartAreas[0].AxisX.Maximum); } } // объём Series volumeSeries = _chartForCandle.Series.FindByName("SeriesVolume"); if (volumeSeries != null) { volumeSeries.Points.AddXY(numberInArray, newCandle.Volume); // разукрышиваем в привычные цвета if (volumeSeries.Points.Count > 1) { if (volumeSeries.Points[volumeSeries.Points.Count - 2].YValues[0] < newCandle.Volume) { volumeSeries.Points[volumeSeries.Points.Count - 1].Color = Color.Green; } else { volumeSeries.Points[volumeSeries.Points.Count - 1].Color = Color.Red; } } } ChartResize(); // Выводим нормальные рамки }
//Test only on Candles private void ProcessOnlyCandle(Candle candle) { try { //Формируем индикаторы с задержкой на одну свечку if (_lastCandle != null) { _upperChannelOne.Add(_lastCandle); _lowerChannelOne.Add(_lastCandle); _upperChannelTwo.Add(_lastCandle); _lowerChannelTwo.Add(_lastCandle); _atr.Add(candle); } _lastCandle = candle; //Проверка актуальности данных if (!GetRealTimeData()) { return; } //Если индикаторы не сформированы, то ничего не делаем if (!_upperChannelOne.IsFormed || !_lowerChannelOne.IsFormed || !_upperChannelTwo.IsFormed || !_lowerChannelTwo.IsFormed || !_atr.IsFormed) { return; } //Текущая позиция по выбранному коннектору и инструменту var position = GetTradeInfo().Position; //Текущие доступные денежные средства доступные стратегии var currentFunds = GetStrategyInfo().CurrentFunds; //Цена последней свечки var lastPrice = GetLastCandle().ClosePrice; if (!CheckIntraDayTime(candle.CloseTime.TimeOfDay, position, lastPrice)) { return; } //Stop-Loss MarketToMarketCandle(candle, position, lastPrice); //Entry if (candle.HighPrice > _upperChannelOne.LastValue && position == 0) { _risk = _k * _atr.LastValue; var volume = (int)Math.Min(currentFunds * _riskPerTrade / _risk, currentFunds / GetSecurity().InitialMargin); var order = new Order { Type = OrderType.Limit, Direction = Direction.Buy, Price = lastPrice + _offset, Volume = volume, Comment = "Entry Buy" }; order.OrderChanged += newOrder => { if (newOrder.State == OrderState.Filled) { _entryPrice = newOrder.Price; } }; RegisterOrder(order); } else if (candle.LowPrice < _lowerChannelOne.LastValue && position == 0) { _risk = _k * _atr.LastValue; var volume = (int)Math.Min(currentFunds * _riskPerTrade / _risk, currentFunds / GetSecurity().InitialMargin); var order = new Order { Type = OrderType.Limit, Direction = Direction.Sell, Price = lastPrice - _offset, Volume = volume, Comment = "Entry Sell" }; order.OrderChanged += newOrder => { if (newOrder.State == OrderState.Filled) { _entryPrice = newOrder.Price; } }; RegisterOrder(order); } //Exit if (candle.LowPrice < _lowerChannelTwo.LastValue && position > 0) { RegisterOrder(new Order { Type = OrderType.Limit, Direction = Direction.Sell, Price = lastPrice - _offset, Volume = position, Comment = "Exit Sell" }); } else if (candle.HighPrice > _upperChannelTwo.LastValue && position < 0) { RegisterOrder(new Order { Type = OrderType.Limit, Direction = Direction.Buy, Price = lastPrice + _offset, Volume = -position, Comment = "Exit Buy" }); } } catch (Exception ex) { ExceptionMessage(ex, "ProcessOnlyCandle"); } }
/// <summary> /// Builds a patch using given paths for the target and upgrade packages. /// </summary> /// <param name="targetPath">The path to the target MSI.</param> /// <param name="upgradePath">The path to the upgrade MSI.</param> /// <param name="name">The name of the patch to build.</param> /// <param name="version">Optional version for the bundle.</param> /// <returns>The path to the patch.</returns> private string BuildPatch(string targetPath, string upgradePath, string name, string version) { // Get the name of the calling method. StackTrace stack = new StackTrace(); string caller = stack.GetFrame(1).GetMethod().Name; // Create paths. string source = Path.Combine(this.TestContext.TestDataDirectory, String.Concat(name, ".wxs")); string rootDirectory = FileUtilities.GetUniqueFileName(); string objDirectory = Path.Combine(rootDirectory, Settings.WixobjFolder); string msiDirectory = Path.Combine(rootDirectory, Settings.MsiFolder); string wixmst = Path.Combine(objDirectory, String.Concat(name, ".wixmst")); string wixmsp = Path.Combine(objDirectory, String.Concat(name, ".wixmsp")); string package = Path.Combine(msiDirectory, String.Concat(name, ".msp")); // Add the root directory to be cleaned up. this.TestArtifacts.Add(new DirectoryInfo(rootDirectory)); // Compile. Candle candle = new Candle(); candle.Extensions.AddRange(DependencyExtensionTests.Extensions); candle.OtherArguments = String.Concat("-dTestName=", caller); if (!String.IsNullOrEmpty(version)) { candle.OtherArguments = String.Concat(candle.OtherArguments, " -dVersion=", version); } candle.OutputFile = String.Concat(objDirectory, @"\"); candle.SourceFiles.Add(source); candle.WorkingDirectory = this.TestContext.TestDataDirectory; candle.Run(); // Make sure the output directory is cleaned up. this.TestArtifacts.Add(new DirectoryInfo(objDirectory)); // Link. Light light = new Light(); light.Extensions.AddRange(DependencyExtensionTests.Extensions); light.ObjectFiles = candle.ExpectedOutputFiles; light.OutputFile = wixmsp; light.SuppressMSIAndMSMValidation = true; light.WorkingDirectory = this.TestContext.TestDataDirectory; light.Run(); // Make sure the output directory is cleaned up. this.TestArtifacts.Add(new DirectoryInfo(msiDirectory)); // Torch. Torch torch = new Torch(); torch.TargetInput = Path.ChangeExtension(targetPath, "wixpdb"); torch.UpdatedInput = Path.ChangeExtension(upgradePath, "wixpdb"); torch.PreserveUnmodified = true; torch.XmlInput = true; torch.OutputFile = wixmst; torch.WorkingDirectory = this.TestContext.TestDataDirectory; torch.Run(); // Pyro. Pyro pyro = new Pyro(); pyro.Baselines.Add(torch.OutputFile, name); pyro.InputFile = light.OutputFile; pyro.OutputFile = package; pyro.WorkingDirectory = this.TestContext.TestDataDirectory; pyro.SuppressWarnings.Add("1079"); pyro.Run(); return pyro.OutputFile; }
private void ProcessCandle(Candle candle) { // если наша стратегия в процессе остановки if (ProcessState == ProcessStates.Stopping) { // отменяем активные заявки CancelActiveOrders(); return; } this.AddInfoLog(LocalizedStrings.Str3634Params.Put(candle.OpenTime, candle.OpenPrice, candle.HighPrice, candle.LowPrice, candle.ClosePrice, candle.TotalVolume, candle.Security)); // добавляем новую свечу var longValue = LongSma.Process(candle); var shortValue = ShortSma.Process(candle); // вычисляем новое положение относительно друг друга var isShortLessThenLong = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue(); // если произошло пересечение if (_isShortLessThenLong != isShortLessThenLong) { // если короткая меньше чем длинная, то продажа, иначе, покупка. var direction = isShortLessThenLong ? Sides.Sell : Sides.Buy; // вычисляем размер для открытия или переворота позы var volume = Position == 0 ? Volume : Position.Abs().Min(Volume) * 2; if (!SafeGetConnector().RegisteredMarketDepths.Contains(Security)) { var price = Security.GetMarketPrice(Connector, direction); // регистрируем псевдо-маркетную заявку - лимитная заявка с ценой гарантирующей немедленное исполнение. if (price != null) { RegisterOrder(this.CreateOrder(direction, price.Value, volume)); } } else { // регистрируем заявку (обычным способом - лимитированной заявкой) RegisterOrder(this.CreateOrder(direction, (decimal)(Security.GetCurrentPrice(this, direction) ?? 0), volume)); // переворачиваем позицию через котирование //var strategy = new MarketQuotingStrategy(direction, volume) //{ // WaitAllTrades = true, //}; //ChildStrategies.Add(strategy); } // запоминаем текущее положение относительно друг друга _isShortLessThenLong = isShortLessThenLong; } var trade = _myTrades.FirstOrDefault(); _myTrades.Clear(); var dict = new Dictionary <IChartElement, object> { { _candlesElem, candle }, { _shortElem, shortValue }, { _longElem, longValue }, { _tradesElem, trade } }; _chart.Draw(candle.OpenTime, dict); }
/// <summary> /// To add data for the candle. /// </summary> /// <param name="series">Candles series.</param> /// <param name="candle">The candle for which you need to add data.</param> /// <param name="value">New data.</param> public void AddValue(CandleSeries series, Candle candle, ICandleBuilderSourceValue value) { if (_valuesKeepTime == TimeSpan.Zero) return; GetInfo(series).AddValue(candle, value); }
public void RegistrySearchInvalidRootValue() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(RegistrySearchTests.TestDataDirectory, @"RegistrySearchInvalidRootValue\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(21, "The util:RegistrySearch/@Root attribute's value, 'HKEY_LOCAL_MACHINE', is not one of the legal options: 'HKCR', 'HKCU', 'HKLM', or 'HKU'.", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(10, "The util:RegistrySearch/@Root attribute was not found; it is required.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 10; candle.Extensions.Add("WixUtilExtension"); candle.Run(); }
public void AddValue(Candle candle, ICandleBuilderSourceValue value) { if (candle == null) throw new ArgumentNullException("candle"); if (value == null) throw new ArgumentNullException("value"); _candleValues.SafeAdd(candle).AddLast(value); _valuesStat.Add(value); if (_firstValueTime == 0) _firstValueTime = value.Time.UtcTicks; _lastValueTime = value.Time.UtcTicks; RecycleValues(); }
public override IEnumerable <Candle> GetCandles(Coin baseCoin, Coin coin, int periodSeconds, DateTime?startDate = null, DateTime?endDate = null) { // https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-WAVES&tickInterval=day // "{"success":true,"message":"","result":[{"O":0.00011000,"H":0.00060000,"L":0.00011000,"C":0.00039500,"V":5904999.37958770,"T":"2016-06-20T00:00:00","BV":2212.16809610} ] }" string periodString; switch (periodSeconds) { case 60: periodString = "oneMin"; break; case 300: periodString = "fiveMin"; break; case 1800: periodString = "thirtyMin"; break; case 3600: periodString = "hour"; break; case 86400: periodString = "day"; break; case 259200: periodString = "threeDay"; break; case 604800: periodString = "week"; break; default: if (periodSeconds > 604800) { periodString = "month"; } else { throw new ArgumentOutOfRangeException("Period seconds must be 60,300,1800,3600,86400, 259200 or 604800"); } break; } string symbol = NormalizeSymbol($"{baseCoin.Code}-{coin.Code}"); startDate = startDate ?? DateTime.UtcNow; endDate = endDate ?? startDate.Value.Subtract(TimeSpan.FromDays(1.0)); JToken result = MakeJsonRequest <JToken>("pub/market/GetTicks?marketName=" + symbol + "&tickInterval=" + periodString, BaseUrl2); CheckError(result); JArray array = result["result"] as JArray; foreach (JToken jsonCandle in array) { Candle candle = new Candle { ClosePrice = (decimal)jsonCandle["C"], ExchangeName = Name, HighPrice = (decimal)jsonCandle["H"], LowPrice = (decimal)jsonCandle["L"], Name = symbol, OpenPrice = (decimal)jsonCandle["O"], PeriodSeconds = periodSeconds, Timestamp = (DateTime)jsonCandle["T"], VolumePrice = (double)jsonCandle["BV"], VolumeQuantity = (double)jsonCandle["V"] }; if (candle.Timestamp >= startDate && candle.Timestamp <= endDate) { yield return(candle); } } }
public void PackageInvalidVital() { Candle candle = new Candle(); candle.SourceFiles.Add(Path.Combine(PackageTests.TestDataDirectory, @"PackageInvalidVital\Product.wxs")); candle.ExpectedWixMessages.Add(new WixMessage(15, "The MsiPackage/@Vital attribute's value, 'true', is not a legal yes/no value. The only legal values are 'no' and 'yes'.", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(15, "The MspPackage/@Vital attribute's value, 'false', is not a legal yes/no value. The only legal values are 'no' and 'yes'.", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(15, "The MsuPackage/@Vital attribute's value, 'vital', is not a legal yes/no value. The only legal values are 'no' and 'yes'.", Message.MessageTypeEnum.Error)); candle.ExpectedWixMessages.Add(new WixMessage(15, "The ExePackage/@Vital attribute's value, 'TRUE', is not a legal yes/no value. The only legal values are 'no' and 'yes'.", Message.MessageTypeEnum.Error)); candle.ExpectedExitCode = 15; candle.Run(); }
//This method measures and deconstructs last three candles to be used by kickass indicators protected void loadCandlesticks() { for(int i=0;i<3;i++){ candles[i]=new Candle(); candles[i].high=Highs[0][i]; //based on asks candles[i].low=Lows[0][i]; //based on bids candles[i].height=(int)((candles[i].high-candles[i].low)*tf); candles[i].top=Math.Max(Opens[0][i],Closes[0][i]); candles[i].bottom=Math.Min(Opens[0][i],Closes[0][i]); candles[i].body=(int)((candles[i].top-candles[i].bottom)*tf); candles[i].hair=(int)((candles[i].high-candles[i].top)*tf); candles[i].beard=(int)((candles[i].bottom-candles[i].low)*tf); if(Opens[0][i]>Closes[0][i]) candles[i].dir=-1; else candles[i].dir=1; double quarter=(candles[i].height/4)/tf; double bodyQuarter=(candles[i].body/4)/tf; candles[i].topQuarter=candles[i].high-quarter; candles[i].bottomQuarter=candles[i].low+quarter; candles[i].topBodyQuarter=candles[i].top-bodyQuarter; candles[i].bottomBodyQuarter=candles[i].bottom+bodyQuarter; candles[i].preaverage=0; int c=0; for(int j=i+1;j<i+8;j++){ candles[i].preaverage+=Lows[0][j]+(Highs[0][j]-Lows[0][j])/2; c++; } candles[i].preaverage/=c; candles[i].premin=MIN(Lows[0],6)[i+i]; candles[i].premax=MIN(Highs[0],6)[i+i]; } }
public Price CalcTrend(MarketData mktData, DateTime updateTime) { if (mktData.TimeSeries.Count < 2) { return(null); } var curVal = mktData.TimeSeries.Last().Mid(); if (updateTime >= _nextTime) { if (_nextTime == DateTime.MinValue) { _nextTime = updateTime.AddSeconds(_subPeriodSeconds); } else { _nextTime = _nextTime.AddSeconds(_subPeriodSeconds); } DateTime rsiTime = _nextTime.AddSeconds(-_subPeriodSeconds); if (mktData.TimeSeries.StartTime() > rsiTime) { return(null); } if (_candles.Count == _nbPeriods) { _candles.RemoveAt(0); } _curCandle = new Candle(curVal, curVal, updateTime, updateTime); _candles.Add(_curCandle); } else { _curCandle = _candles.Last(); } if (curVal > _curCandle.MaxValue) { _curCandle.MaxValue = curVal; _curCandle.EndTime = updateTime; } else if (curVal < _curCandle.MinValue) { _curCandle.MinValue = curVal; _curCandle.StartTime = updateTime; } if (_candles.Count < _nbPeriods) { return(null); } /* * List<KeyValuePair<DateTime, decimal>> centralValues = new List<KeyValuePair<DateTime, decimal>>(); * var startCenter = new KeyValuePair<DateTime, decimal>(new DateTime(_candles[0].StartTime.Ticks / 2 + _candles[0].EndTime.Ticks / 2), (_candles[0].Min + _candles[0].Max) / 2m); * centralValues.Add(startCenter); * centralValues.Add(new KeyValuePair<DateTime, decimal>(new DateTime(_candles[_candles.Count / 3].StartTime.Ticks / 2 + _candles[_candles.Count / 3].EndTime.Ticks / 2), * (_candles[_candles.Count / 3].Min + _candles[_candles.Count / 3].Max) / 2m)); * centralValues.Add(new KeyValuePair<DateTime, decimal>(new DateTime(_candles[_candles.Count * 2 / 3].StartTime.Ticks / 2 + _candles[_candles.Count * 2 / 3].EndTime.Ticks / 2), * (_candles[_candles.Count * 2 / 3].Min + _candles[_candles.Count * 2 / 3].Max) / 2m)); * centralValues.Add(new KeyValuePair<DateTime, decimal>(new DateTime(_candles[_candles.Count - 2].StartTime.Ticks / 2 + _candles[_candles.Count - 2].EndTime.Ticks / 2), * (_candles[_candles.Count - 2].Min + _candles[_candles.Count - 2].Max) / 2m)); * decimal centralCoeff = calcDirCoeff(centralValues, updateTime) / (decimal)(updateTime - centralValues[0].Key).TotalSeconds;*/ IEnumerable <KeyValuePair <decimal, DateTime> > topValues = null; IEnumerable <KeyValuePair <decimal, DateTime> > bottomValues = null; if (_simple) { var first = _candles.First(); var last = _candles.Last(); decimal timeLength = (decimal)(last.EndTime - first.EndTime).TotalSeconds; decimal topCoeff = timeLength < 1m ? 0m : (last.MaxValue - first.MaxValue) / (decimal)(last.EndTime - first.EndTime).TotalSeconds; timeLength = (decimal)(last.StartTime - first.StartTime).TotalSeconds; decimal bottomCoeff = timeLength < 1m ? 0m : (last.MinValue - first.MinValue) / (decimal)(last.StartTime - first.StartTime).TotalSeconds; if (topCoeff == 0m && bottomCoeff == 0m) { return(null); } return(new Price(100m * (topCoeff + bottomCoeff) / 2m)); } else { if (_candles.Count > _nbPeaks) { topValues = searchTopValues(); bottomValues = searchBottomValues(); } else { var candidateTopValues = new SortedDictionary <decimal, DateTime>(); var candidateBottomValues = new SortedDictionary <decimal, DateTime>(); foreach (var candle in _candles) { candidateTopValues[candle.MaxValue] = candle.EndTime; candidateBottomValues[candle.MinValue] = candle.StartTime; } topValues = candidateTopValues; bottomValues = candidateBottomValues; } decimal topCoeff = calcDirCoeff(topValues, updateTime); decimal bottomCoeff = calcDirCoeff(bottomValues, updateTime); Price trend = new Price(100m * (topCoeff + bottomCoeff) / 2m); return(trend); } }
/// <summary> /// transform candles /// преобразовать свечи /// </summary> /// <param name="tf">received timeframe / пришедший таймфрейм</param> /// <param name="needTf">needed timeframe / тф который нужно получить</param> /// <param name="rawCandles">raw candles / заготовки для свечей</param> /// <returns></returns> private List <Candle> TransformCandles(int tf, int needTf, List <List <double> > rawCandles) { var entrance = needTf / tf; List <Candle> newCandles = new List <Candle>(); //MTS, - 0 //OPEN, - 1 //CLOSE,- 2 //HIGH, - 3 //LOW, - 4 //VOLUME- 5 int count = 0; Candle newCandle = new Candle(); bool isStart = true; for (int i = rawCandles.Count - 1; i > 0; i--) { var time = new DateTime(1970, 1, 1) + TimeSpan.FromMilliseconds(rawCandles[i][0]); if (time.Minute % needTf != 0 && isStart) { continue; } if (needTf > 60) { if (time.Hour % (needTf / 60) != 0 && isStart) { continue; } } isStart = false; count++; if (count == 1) { newCandle = new Candle(); var resOpen = rawCandles[i]; newCandle.Open = Convert.ToDecimal(rawCandles[i][1]); newCandle.TimeStart = time; newCandle.Low = Decimal.MaxValue; newCandle.High = Decimal.MinValue; } newCandle.High = Convert.ToDecimal(rawCandles[i][3]) > newCandle.High ? Convert.ToDecimal(rawCandles[i][3]) : newCandle.High; newCandle.Low = Convert.ToDecimal(rawCandles[i][4]) < newCandle.Low ? Convert.ToDecimal(rawCandles[i][4]) : newCandle.Low; newCandle.Volume += Convert.ToDecimal(rawCandles[i][5]); if (i == 1 && count != entrance) { newCandle.Close = Convert.ToDecimal(rawCandles[i][2]); newCandle.State = CandleState.None; newCandles.Add(newCandle); } if (count == entrance) { newCandle.Close = Convert.ToDecimal(rawCandles[i][2]); newCandle.State = CandleState.Finished; newCandles.Add(newCandle); count = 0; } } if (newCandles.Count > 1) { newCandles.RemoveAt(0); } return(newCandles); }