public static Bar Map(Bars.Core.DomainModels.Bar source)
 {
     return new Bar(source.Name, source.Description, source.Address, source.Phone, source.Hours,
                     source.Latitude, source.Longitude, source.WebsiteUrl, source.CalendarUrl,
                     source.FacebookUrl, source.YelpUrl, source.ImageUrl, source.District,
                     source.MusicTypes, source.BarTypes, source.StatusFlag);
 }
Пример #2
0
		/// <summary>
		/// </summary>
		/// <param name="bars"></param>
		/// <param name="open"></param>
		/// <param name="high"></param>
		/// <param name="low"></param>
		/// <param name="close"></param>
		/// <param name="time"></param>
		/// <param name="volume"></param>
		/// <param name="isRealtime"></param>
		public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime)
		{
			
			if (volume <= bars.Period.Value2) return;
			
			if (bars.Count == 0)
			{
				while (volume > bars.Period.Value)
				{
					AddBar(bars, open, high, low, close, time, bars.Period.Value, isRealtime);
					volume -= bars.Period.Value;
				}

				if (volume > 0)
					AddBar(bars, open, high, low, close, time, volume, isRealtime);
			}
			else
			{
				long volumeTmp = 0;
				if (!bars.IsNewSession(time, isRealtime))
				{
					volumeTmp = Math.Min(bars.Period.Value - bars.GetVolume(bars.Count - 1), volume);
					if (volumeTmp > 0)
						UpdateBar(bars, open, high, low, close, time, volumeTmp, isRealtime);
				}

				volumeTmp = volume - volumeTmp;
				while (volumeTmp > 0)
				{
					AddBar(bars, open, high, low, close, time, Math.Min(volumeTmp, bars.Period.Value), isRealtime);
					volumeTmp -= bars.Period.Value;
				}
			}
		}
Пример #3
0
 public Bars RequestData(DataSource ds, string symbol, DateTime startDate, DateTime endDate, int maxBars, bool includePartialBar)
 {
     Bars bars = new Bars(symbol, ds.Scale, ds.BarInterval);
     //bars.Add(new DateTime(2012, 04, 07), 2, 5, 1, 3, 5);
     //bars.Add(new DateTime(2010, 09, 06), 3, 6, 2, 2, 6);
     return bars;
 }
Пример #4
0
		/// <summary>
		/// </summary>
		/// <param name="bars"></param>
		/// <param name="open"></param>
		/// <param name="high"></param>
		/// <param name="low"></param>
		/// <param name="close"></param>
		/// <param name="time"></param>
		/// <param name="volume"></param>
		/// <param name="isRealtime"></param>
		public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime)
		{
			if (bars.Count == 0)
				if (isRealtime && bars.Session.SessionsOfDay.Length > 0)
				{
					DateTime barTime;
					bars.Session.GetSessionDate(time, false, out barTime, out cacheSessionEnd);
					AddBar(bars, open, high, low, close, barTime, volume, true);
				}
				else
					AddBar(bars, open, high, low, close, time.Date, volume, isRealtime);
			else
			{
				DateTime barTime;
				if (!isRealtime)
					barTime = time.Date;
				else if (time >= cacheSessionEnd /* on realtime include60 is always false */)
				{
					bars.Session.GetSessionDate(time, false, out barTime, out cacheSessionEnd);
					if (barTime < bars.TimeLastBar.Date)
						barTime = bars.TimeLastBar.Date; // make sure timestamps are ascending
				}
				else
					barTime = bars.TimeLastBar.Date; // make sure timestamps are ascending

				if (bars.DayCount < bars.Period.Value
						|| (!isRealtime && bars.Count > 0 && barTime == bars.TimeLastBar.Date)
						|| (isRealtime && bars.Count > 0 && barTime <= bars.TimeLastBar.Date))
					UpdateBar(bars, open, high, low, close, barTime, volume, isRealtime);
				else
					AddBar(bars, open, high, low, close, barTime, volume, isRealtime);
			}
		}
Пример #5
0
        public AdaptiveLookback(Bars bars, int howManySwings, bool UseAll, string description)
            : base(bars, description)
        {
            this.bars = bars;

            bool SwingLo, SwingHi;
            double lastSL = bars.Low[1];
            double lastSH = bars.High[1];
            int firstSwingBarOnChart = 0;
            int lastSwingInCalc = 0;
            int swingCount = 0;
            DataSeries so = new DataSeries(bars.Close, "swing_oscillator");
            System.Collections.ArrayList SwingBarArray = new System.Collections.ArrayList();

            for (int bar = 5; bar < bars.Count; bar++)
            {
                SwingLo = (CumDown.Series(bars.Low, 1)[bar - 2] >= 2) &&
                    (CumUp.Series(bars.High, 1)[bar] == 2);
                SwingHi = (CumUp.Series(bars.High, 1)[bar - 2] >= 2) &&
                    (CumDown.Series(bars.Low, 1)[bar] == 2);

                if (SwingLo)
                    so[bar] = -1;
                else
                    if (SwingHi)
                        so[bar] = 1;
                    else
                        so[bar] = 0;

                if ((so[bar] != 0) & (swingCount == 0))
                {
                    firstSwingBarOnChart = bar;
                    swingCount++;
                    SwingBarArray.Add(bar);
                }
                else
                    if (swingCount > 0)
                    {
                        if (so[bar] != 0.0)
                        {
                            swingCount++;
                            SwingBarArray.Add(bar);
                        }

                        // 20090127 Added
                        if (swingCount == howManySwings)
                            base.FirstValidValue = bar;
                    }

                lastSwingInCalc = (SwingBarArray.Count - howManySwings);

                if (lastSwingInCalc >= 0)
                {
                    base[bar] = UseAll ? (int)(bars.Count / SwingBarArray.Count) :
                        (bar - (int)SwingBarArray[lastSwingInCalc]) / howManySwings;
                }
            }
        }
Пример #6
0
        static TestBars()
        {
            bars = new Bars("TestSymbol", BarScale.Second, 1);
            for (int i = 0; i < 10; ++i)
                NewTick(null, null);

            System.Timers.Timer t = new System.Timers.Timer();
            t.Elapsed += new System.Timers.ElapsedEventHandler(NewTick);
            t.Interval = 250;
            t.Enabled = true;
        }
Пример #7
0
        public static AdaptiveLookback Series(Bars bars, int howManySwings, bool UseAll)
        {
            string description = string.Concat(new object[] { "Adaptive Lookback(", bars.Symbol, ",", howManySwings.ToString(), ",", UseAll.ToString(), ")" });
            //string description = string.Concat(new object[] { "Adaptive Lookback(", bars.ToString(), ",", howManySwings.ToString(), ",", UseAll.ToString(), ")" });

            if (bars.Cache.ContainsKey(description))
            {
                return (AdaptiveLookback)bars.Cache[description];
            }

            AdaptiveLookback _AdaptiveLookback = new AdaptiveLookback(bars, howManySwings, UseAll, description);
            bars.Cache[description] = _AdaptiveLookback;
            return _AdaptiveLookback;
        }
Пример #8
0
        public override void Deserialize(GenericReader reader)
        {
            base.Deserialize(reader);

            int version = reader.ReadInt();

            switch (version)
            {
                case 0:
                    {
                        mBarType = (Bars)reader.ReadInt();
                        break;
                    }
            }
        }
Пример #9
0
        void BarsEnumeration()
        {
            var startTime = DateTime.Parse("2/1/2012 13:30:00", CultureInfo.InvariantCulture);
            var endTime = DateTime.Parse("2/1/2012 14:00:00", CultureInfo.InvariantCulture);

            var bars = new Bars(this.Feed, "EURUSD", PriceType.Bid, BarPeriod.S1, startTime, endTime, 1024);

            var averageDeviation = 0D;
            var count = 0;

            foreach (var element in bars)
            {
                averageDeviation += (element.High - element.Low);
                count++;
            }

            averageDeviation /= count;
            Console.WriteLine("BarsEnumeration(): average deviation = {0}", averageDeviation);
        }
Пример #10
0
		/// <summary>
		/// Default constructor.
		/// </summary>
		public WOutlookBar()
		{
			// This call is required by the Windows.Forms Form Designer.
			InitializeComponent();

			// TODO: Add any initialization after the InitForm call

			SetStyle(ControlStyles.ResizeRedraw,true);
			SetStyle(ControlStyles.DoubleBuffer  | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint,true);
		
			m_pBars = new Bars(this);						
			m_ViewStyle = new ViewStyle();

			m_ViewStyle.StyleChanged += new ViewStyleChangedEventHandler(this.OnViewStyleChanged);
			ViewStyle.staticViewStyle.StyleChanged += new ViewStyleChangedEventHandler(this.OnStaticViewStyleChanged);

			m_UpButtonIcon   = Core.LoadIcon("up.ico");
			m_DownButtonIcon = Core.LoadIcon("down.ico");

		}
Пример #11
0
 public static int Hue(Bars barType)
 {
     switch (barType)
     {
         case Bars.Adamantite:
             return 0x363;
         case Bars.Steel:
             return 0x47F;
         case Bars.Bronze:
             return 0x466;
         case Bars.Gold:
             return 0x501;
         case Bars.Iron:
             return 0x21F;
         case Bars.Mithril:
             return 0x18A;
         case Bars.Rune:
             return 0xBC;
         case Bars.Silver:
             return 0x47E;
     }
     return 0;
 }
Пример #12
0
        public static IIndicator CreateIndicator(Bars bars, IndicatorInfo info)
        {
            Log.Instance.Trace("CreateIndicator {0}", info);
            IIndicator indicator;
            BarsSingleValues baseIndicator;
            switch (info.Base)
            {
                case IndicatorBase.Open:
                    baseIndicator = new BarsOpen(bars);
                    break;
                case IndicatorBase.Close:
                    baseIndicator = new BarsClose(bars);
                    break;
                case IndicatorBase.High:
                    baseIndicator = new BarsHigh(bars);
                    break;
                case IndicatorBase.Low:
                    baseIndicator = new BarsLow(bars);
                    break;
                default:
                    return null;
            }

            switch (info.Type)
            {
                case IndicatorType.EMA:
                    indicator = new Ema(baseIndicator, info.Period);
                    break;
                case IndicatorType.Simple:
                    indicator = new Simple(baseIndicator, info.Period);
                    break;
                default:
                    return null;
            }

            return indicator;
        }
Пример #13
0
        /// <summary>
        /// Called on each incoming tick
        /// </summary>
        void OnTick(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime)
        {
            // ensure xml config loaded
            ConfigCheck();

            // create initial bar on first tick and handle NT7 session-break issue (note: removing IsNewSession() creates invalid bars; remove if preferred)
            if ((bars.Count == 0) || bars.IsNewSession(time, isRealtime))
            {
                // set class fields
                tickSize = bars.Instrument.MasterInstrument.TickSize;

                // calculate bear/bull min/max
                RangeInit();

                // update class fields
                AdjustOpenClose(bars, close, close);
                prevClose = close;

                // add first bar
                AddBar(bars, thisOpen, thisOpen, thisOpen, thisOpen, time, volume, isRealtime);

                // add EmProps
                AddEmProps(thisOpen, volume, thisCloseDown, thisCloseUp, time);
            }

            // continue all subsequent ticks/bars
            else
            {
                // local variables
                Bar bar              = (Bar)bars.Get(bars.Count - 1);
                int compareCloseUp   = bars.Instrument.MasterInstrument.Compare(close, thisCloseUp);
                int compareCloseDown = bars.Instrument.MasterInstrument.Compare(close, thisCloseDown);

                // range exceeded; create new bar(s)
                if (((compareCloseUp > 0 || compareCloseDown < 0) && CloseOption == EmCloses.TickThru) || ((compareCloseUp >= 0 || compareCloseDown <= 0) && CloseOption == EmCloses.OnTouch))
                {
                    // local variables
                    bool   newBar    = true;
                    double thisClose = (compareCloseUp > 0) ? Math.Min(close, thisCloseUp) : (compareCloseDown < 0) ? Math.Max(close, thisCloseDown) : close;

                    // close current bar; volume included for on-touch only
                    // see this post for more info on volume calculation: http://www.ninjatrader.com/support/forum/showthread.php?p=302208#post302208
                    UpdateBar(bars, bar.Open, ((compareCloseUp > 0) ? thisClose : bar.High), ((compareCloseDown < 0) ? thisClose : bar.Low), thisClose, time, ((CloseOption == EmCloses.OnTouch) ? volume : 0), isRealtime);
                    barProps.Finalize(thisClose, prevClose, ((CloseOption == EmCloses.OnTouch) ? volume : 0), time, ((close > bar.Open) ? 1 : (close < bar.Open) ? -1 : 0));

                    // add next bar and loop phantom bars, if needed
                    do
                    {
                        // update class fields
                        thisBias  = (close > bar.Open) ? 1 : (close < bar.Open) ? -1 : 0;
                        tickRange = EmMath.RangeValidate(Math.Abs(AddTwoDoubles(bars, bar.Open, -thisClose)), (thisBias == -1) ? tickBearRangeMax : tickBullRangeMax, (thisBias == -1) ? tickBearRangeMin : tickBullRangeMin);
                        AdjustOpenClose(bars, thisClose, close);
                        thisClose = (compareCloseUp > 0) ? Math.Min(close, thisCloseUp) : (compareCloseDown < 0) ? Math.Max(close, thisCloseDown) : close;

                        // add new bar; include volume once (except for on-touch), then create phantom bars
                        // see this post for more info on volume calculation: http://www.ninjatrader.com/support/forum/showthread.php?p=302208#post302208
                        AddBar(bars, thisOpen, ((compareCloseUp > 0) ? thisClose : thisOpen), ((compareCloseDown < 0) ? thisClose : thisOpen), thisClose, time, ((CloseOption == EmCloses.TickThru && newBar) ? volume : 0), isRealtime);

                        // add EmProps
                        AddEmProps(thisOpen, ((compareCloseUp > 0) ? thisClose : thisOpen), ((compareCloseDown < 0) ? thisClose : thisOpen), thisClose, ((CloseOption == EmCloses.TickThru && newBar) ? volume : 0), time, thisBias, thisCloseDown, thisCloseUp);

                        // update class fields
                        newBar           = false;
                        compareCloseUp   = bars.Instrument.MasterInstrument.Compare(close, thisCloseUp);
                        compareCloseDown = bars.Instrument.MasterInstrument.Compare(close, thisCloseDown);
                    }while (((compareCloseUp > 0 || compareCloseDown < 0) && CloseOption == EmCloses.TickThru) || ((compareCloseUp >= 0 || compareCloseDown <= 0) && CloseOption == EmCloses.OnTouch));
                }

                // range not exceeded; continue current bar
                else
                {
                    // update current bar
                    UpdateBar(bars, bar.Open, ((close > bar.High) ? close : bar.High), ((close < bar.Low) ? close : bar.Low), close, time, volume, isRealtime);

                    // update EmProps
                    barProps.Update(close, prevClose, volume, time);
                }
            }

            // update prevClose and last price
            bars.LastPrice = prevClose = close;
        }
        protected override void CalcBar()
        {
            // strategy logic
            if (!Bars.LastBarOnChart)
            {
                return;
            }
            if (Bars.CurrentBar <= trainingSize)
            {
                Output.WriteLine("Not enough bars on chart. Waiting for new data");
                return;
            }

            if (train)
            {
                int interval = Bars.CurrentBar - prevTrain;
                if (Bars.Status == EBarState.Close && (!isTrained || isTrained && interval == retrainInterval))
                {
                    Output.WriteLine(Bars.CurrentBarAbsolute().ToString());
                    // Establishing connection
                    socket = new TcpClient();
                    socket.Connect("localhost", 9090);                              // Connecting to python server on localhost
                    stream = socket.GetStream();                                    // Creating stream to read and write data

                    if (socket.Connected)
                    {
                        Output.WriteLine("connected!");

                        // Collecting close Price and Dates data
                        List <string> closePrice = new List <string>();
                        List <string> time       = new List <string>();
                        for (int index = 0; index < trainingSize; index++)
                        {
                            closePrice.Add(Bars.Close[index].ToString());
                            time.Add(Bars.Time[index].ToString());
                        }

                        closePrice.Reverse();
                        time.Reverse();

                        // Creating dynamic object to store model parameters
                        var jsonObject = new TrainParameters();

                        jsonObject.Data          = closePrice;
                        jsonObject.Time          = time;
                        jsonObject.FileName      = fileName;
                        jsonObject.GPU           = gpu;
                        jsonObject.Train         = train;
                        jsonObject.Architecture  = (int)architecture;
                        jsonObject.Optimizer     = (int)optimizer;
                        jsonObject.Loss          = (int)loss;
                        jsonObject.LearningRate  = learningRate;
                        jsonObject.Epochs        = epochs;
                        jsonObject.Scale         = scale;
                        jsonObject.Momentum      = momentum;
                        jsonObject.TestingPart   = testingPart;
                        jsonObject.TestingWeight = testingWeight;
                        jsonObject.Bars          = bars;

                        string jsonString = JsonConvert.SerializeObject(jsonObject);
                        Byte[] data       = Encoding.UTF8.GetBytes(jsonString);

                        stream.Write(data, 0, data.Length);

                        //Output.WriteLine("Sent : " + jsonString);

                        Output.WriteLine("Sent!");
                        isTrained = true;
                        prevTrain = Bars.CurrentBar;
                    }
                    else
                    {
                        Output.WriteLine("connection failed!");
                    }
                }

                if (isTrained && socket.Connected)
                {
                    if (stream.DataAvailable)
                    {
                        //socket.ReceiveTimeout = 20000;
                        byte[] data     = new Byte[2 * 256];
                        string response = string.Empty;
                        Int32  bytes    = stream.Read(data, 0, data.Length);
                        response = Encoding.UTF8.GetString(data, 0, bytes);

                        if (response != string.Empty)
                        {
                            Output.WriteLine("Received!");
                            var jsonObject = new PredictionParameters();
                            jsonObject = JsonConvert.DeserializeObject <PredictionParameters>(response);

                            // Plotting the predictions on  the chart
                            for (int i = 0; i < bars; i++)
                            {
                                double       ypred      = double.Parse(jsonObject.Pred[i].ToString());
                                IArrowObject arrowData1 = DrwArrow.Create(new ChartPoint(Bars.Time[0].AddMinutes(i), ypred), true);
                                arrowData1.Color = Color.Aqua;
                                arrowData1.Style = EArrowForms.ArrowForm6;
                                //Draw.Dot(this, "Prediction " + i.ToString(), true, i, ypred, Brushes.Aqua);
                            }

                            stream.Close();
                            socket.Close();
                        }
                        else
                        {
                            Output.WriteLine("No response");
                        }
                    }
                    else
                    {
                        Output.WriteLine("Prediction Data Not Available!");
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                if (Bars.Status == EBarState.Close && !isForecasted)
                {
                    socket = new TcpClient();
                    socket.Connect("localhost", 9090);
                    stream = socket.GetStream();

                    if (socket.Connected)
                    {
                        Output.WriteLine("Connected!");

                        isForecasted = true;

                        var jsonObject = new SavedModelParameters();
                        jsonObject.FileName = fileName;
                        jsonObject.Train    = train;
                        jsonObject.Bars     = bars;

                        string jsonString = JsonConvert.SerializeObject(jsonObject);
                        Byte[] sentData   = Encoding.UTF8.GetBytes(jsonString);

                        Debug.Assert(!jsonObject.Train);
                        stream.Write(sentData, 0, sentData.Length);
                    }
                    else
                    {
                        Output.WriteLine("Connection Failed");
                    }
                }

                if (isForecasted && socket.Connected && !isPlotted)
                {
                    if (stream.DataAvailable)
                    {
                        //socket.ReceiveTimeout = 20000;
                        byte[] recievedData = new Byte[2 * 256];
                        string response     = string.Empty;
                        Int32  bytes        = stream.Read(recievedData, 0, recievedData.Length);
                        response = Encoding.UTF8.GetString(recievedData, 0, bytes);

                        if (response != string.Empty)
                        {
                            var resJsonObject = new SavedModelPredictionParameters();
                            resJsonObject = JsonConvert.DeserializeObject <SavedModelPredictionParameters>(response);

                            Output.WriteLine("Received Data");
                            // Plotting the predictions on  the chart
                            for (int i = 0; i < bars; i++)
                            {
                                Output.WriteLine(resJsonObject.Pred[i].ToString());
                                double       ypred      = double.Parse(resJsonObject.Pred[i].ToString());
                                IArrowObject arrowData1 = DrwArrow.Create(new ChartPoint(Bars.Time[0].AddMinutes(i), ypred), true);
                                arrowData1.Color = Color.Aqua;
                                arrowData1.Style = EArrowForms.ArrowForm6;
                                //Draw.Dot(this, "Prediction " + i.ToString(), true, i, ypred, Brushes.Aqua);
                            }
                            isPlotted = true;
                        }
                        else
                        {
                            Output.WriteLine("No response");
                        }
                    }
                    else
                    {
                        Output.WriteLine("Prediction Data Not Available!");
                    }
                }

                // Already forecasted based on saved model
                else
                {
                    return;
                }
            }
        }
Пример #15
0
		protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
		{
			if (IsInHitTest) return;

			int		lastBar		= ChartBars.ToIndex;
			int		firstBar	= ChartBars.FromIndex;
			double	highPrice	= 0;
			double	lowPrice	= double.MaxValue;

			SharpDX.Direct2D1.Brush brushDown	= BarDownBrush.ToDxBrush(RenderTarget);
			SharpDX.Direct2D1.Brush lineBrush	= LineBrush.ToDxBrush(RenderTarget);
			SharpDX.Direct2D1.Brush brushUp		= BarUpBrush.ToDxBrush(RenderTarget);
			brushDown.Opacity					= (float)(Opacity / 100.0);
			brushUp.Opacity						= (float)(Opacity / 100.0);

			for (int idx = firstBar; idx <= lastBar && idx >= 0; idx++)
			{
				highPrice	= Math.Max(highPrice, Bars.GetHigh(idx));
				lowPrice	= Math.Min(lowPrice, Bars.GetLow(idx));
			}

			int		volumeBarCount	= BarCount;
			double	priceRange		= highPrice - lowPrice;
			double	priceBoxSize	= priceRange / volumeBarCount;
			double	volumeMax		= 0;

			// Pass 1: Fill all VolumeInfo structures with appropriate data
			for (int i = 0; i < volumeBarCount; i++)
			{

				double priceUpper = lowPrice + priceBoxSize * (i + 1);
				double priceLower = lowPrice + priceBoxSize * i;

				double priceVolumeUp   = 0;
				double priceVolumeDown = 0;

				for (int idx = firstBar; idx <= lastBar; idx++)
				{
					double checkPrice;

					PriceSeries series = (Inputs[0] as PriceSeries);

					switch (series.PriceType)
					{
						case PriceType.Open:		checkPrice = Bars.GetOpen(idx); break;
						case PriceType.Close:		checkPrice = Bars.GetClose(idx); break;
						case PriceType.High:		checkPrice = Bars.GetHigh(idx); break;
						case PriceType.Low:			checkPrice = Bars.GetLow(idx); break;
						case PriceType.Median:		checkPrice = (Bars.GetHigh(idx) + Bars.GetLow(idx)) / 2; break;
						case PriceType.Typical:		checkPrice = (Bars.GetHigh(idx) + Bars.GetLow(idx) + Bars.GetClose(idx)) / 3; break;
						case PriceType.Weighted:	checkPrice = (Bars.GetHigh(idx) + Bars.GetLow(idx) + 2 * Bars.GetClose(idx)) / 4; break;
						default:					checkPrice = Bars.GetClose(idx); break;
					}

					if (checkPrice >= priceLower && checkPrice < priceUpper)
					{
						if (Bars.GetOpen(idx) < Bars.GetClose(idx))
							priceVolumeUp += Bars.GetVolume(idx);
						else
							priceVolumeDown += Bars.GetVolume(idx);
					}
				}

				volumeInfo[i].up	= priceVolumeUp;
				volumeInfo[i].down	= priceVolumeDown;
				volumeInfo[i].total = priceVolumeUp + priceVolumeDown;

				volumeMax = Math.Max(volumeMax, volumeInfo[i].total);
			}

			// Pass 2: Paint the volume bars
			for (int i = 0; i < Math.Min(volumeBarCount, lastBar - firstBar + 1); i++)
			{
				double	priceUpper		= lowPrice + priceBoxSize * (i + 1);
				double	priceLower		= lowPrice + priceBoxSize * i;
				int		yUpper			= Convert.ToInt32(chartScale.GetYByValue(priceUpper)) + BarSpacing;
				int		yLower			= Convert.ToInt32(chartScale.GetYByValue(priceLower));
				int		barWidthUp		= (int)((chartScale.Height / 2) * (volumeInfo[i].up / volumeMax));
				int		barWidthDown	= (int)((chartScale.Height / 2) * (volumeInfo[i].down / volumeMax));

				SharpDX.RectangleF rect = new SharpDX.RectangleF(ChartPanel.X, yUpper, barWidthUp, Math.Abs(yUpper - yLower));
				RenderTarget.FillRectangle(rect, brushUp);
				RenderTarget.DrawRectangle(rect, brushUp);

				SharpDX.RectangleF rect2 = new SharpDX.RectangleF(ChartPanel.X + barWidthUp, yUpper, barWidthDown, Math.Abs(yUpper - yLower));
				RenderTarget.DrawRectangle(rect2, brushDown);
				RenderTarget.FillRectangle(rect2, brushDown);

				if (DrawLines)
				{
					RenderTarget.DrawLine(new SharpDX.Vector2(ChartPanel.X, yLower), new SharpDX.Vector2(ChartPanel.X + ChartPanel.W, yLower), lineBrush);
					if( i == volumeBarCount - 1)
						RenderTarget.DrawLine(new SharpDX.Vector2(ChartPanel.X, yUpper), new SharpDX.Vector2(ChartPanel.X + ChartPanel.W, yUpper), lineBrush);
				}
			}

			lineBrush.Dispose();
			brushDown.Dispose();
			brushUp.Dispose();
		}
Пример #16
0
 protected override void Subscribe(string symbol)
 {
     bars = new Bars(symbol, rayProvider.scale, rayProvider.barinterval);
     barsNew = new Bars(symbol, BarScale.Tick, 1);
     rayclient = new AsynchronousClient(11000);
     q = new Quote();
     q.Symbol = symbol;
     this.symbol = symbol;
 }
Пример #17
0
        public override double SizePosition(Position currentPos, Bars bars, int bar, double basisPrice, PositionType pt, double riskStopLevel, double equity, double cash)
        {
            double risksizeprecent = Math.Abs((riskStopLevel - basisPrice) / basisPrice - 1);

            if (_settings == null)
                _settings = new myPosSizerSettings();
            this.InitializeSettings(_settings);
            _maxRisk = _settings.MaxRiskSize;

            //MessageBox.Show("MaxRisk:"+_maxRisk,ToString());
            double capfortrade = equity *0.99*_maxRisk/100;
            capfortrade = capfortrade/Math.Abs(riskStopLevel - basisPrice);
            if (capfortrade > equity)
                capfortrade = equity;
            return (int) (Math.Min(capfortrade,equity*0.99/basisPrice));
        }
Пример #18
0
        protected override void CalcData(UIOption option)
        {
            Bars.Clear();
            NeedDraw = false;
            UIBarOption o = (UIBarOption)option;

            if (o == null || o.Series == null || o.SeriesCount == 0)
            {
                return;
            }

            DrawOrigin = new Point(BarOption.Grid.Left, Height - BarOption.Grid.Bottom);
            DrawSize   = new Size(Width - BarOption.Grid.Left - BarOption.Grid.Right,
                                  Height - BarOption.Grid.Top - BarOption.Grid.Bottom);

            if (DrawSize.Width <= 0 || DrawSize.Height <= 0)
            {
                return;
            }
            if (o.XAxis.Data.Count == 0)
            {
                return;
            }

            NeedDraw     = true;
            DrawBarWidth = DrawSize.Width * 1.0f / o.XAxis.Data.Count;

            double min = double.MaxValue;
            double max = double.MinValue;

            foreach (var series in o.Series)
            {
                min = Math.Min(min, series.Data.Min());
                max = Math.Max(max, series.Data.Max());
            }

            if (min > 0 && max > 0 && !o.YAxis.Scale)
            {
                min = 0;
            }

            if (min < 0 && max < 0 && !o.YAxis.Scale)
            {
                max = 0;
            }

            UIChartHelper.CalcDegreeScale(min, max, o.YAxis.SplitNumber,
                                          out int start, out int end, out double interval);

            YAxisStart    = start;
            YAxisEnd      = end;
            YAxisInterval = interval;

            float x1 = DrawBarWidth / ((o.SeriesCount * 2) + o.SeriesCount + 1);
            float x2 = x1 * 2;

            for (int i = 0; i < o.SeriesCount; i++)
            {
                float barX   = DrawOrigin.X;
                var   series = o.Series[i];
                Bars.TryAdd(i, new List <BarInfo>());

                for (int j = 0; j < series.Data.Count; j++)
                {
                    if (YAxisStart >= 0)
                    {
                        float h = Math.Abs((float)(DrawSize.Height * (series.Data[j] - start * interval) / ((end - start) * interval)));

                        Bars[i].Add(new BarInfo()
                        {
                            Rect = new RectangleF(
                                barX + x1 * (i + 1) + x2 * i,
                                DrawOrigin.Y - h,
                                x2, h)
                        });
                    }
                    else if (YAxisEnd <= 0)
                    {
                        float h = Math.Abs((float)(DrawSize.Height * (end * interval - series.Data[j]) / ((end - start) * interval)));
                        Bars[i].Add(new BarInfo()
                        {
                            Rect = new RectangleF(
                                barX + x1 * (i + 1) + x2 * i,
                                BarOption.Grid.Top + 1,
                                x2, h - 1)
                        });
                    }
                    else
                    {
                        float lowH          = 0;
                        float highH         = 0;
                        float DrawBarHeight = DrawSize.Height * 1.0f / (YAxisEnd - YAxisStart);
                        float lowV          = 0;
                        float highV         = 0;
                        for (int k = YAxisStart; k <= YAxisEnd; k++)
                        {
                            if (k < 0)
                            {
                                lowH += DrawBarHeight;
                            }
                            if (k > 0)
                            {
                                highH += DrawBarHeight;
                            }
                            if (k < 0)
                            {
                                lowV += (float)YAxisInterval;
                            }
                            if (k > 0)
                            {
                                highV += (float)YAxisInterval;
                            }
                        }

                        lowH.ConsoleWriteLine();
                        highH.ConsoleWriteLine();

                        if (series.Data[j] >= 0)
                        {
                            float h = Math.Abs((float)(highH * series.Data[j] / highV));
                            Bars[i].Add(new BarInfo()
                            {
                                Rect = new RectangleF(
                                    barX + x1 * (i + 1) + x2 * i,
                                    DrawOrigin.Y - lowH - h,
                                    x2, h)
                            });
                        }
                        else
                        {
                            float h = Math.Abs((float)(lowH * series.Data[j] / lowV));
                            Bars[i].Add(new BarInfo()
                            {
                                Rect = new RectangleF(
                                    barX + x1 * (i + 1) + x2 * i,
                                    DrawOrigin.Y - lowH + 1,
                                    x2, h - 1)
                            });
                        }
                    }

                    barX += DrawBarWidth;
                }
            }

            if (BarOption.ToolTip != null)
            {
                for (int i = 0; i < BarOption.XAxis.Data.Count; i++)
                {
                    string str = BarOption.XAxis.Data[i];
                    foreach (var series in BarOption.Series)
                    {
                        str += '\n';
                        str += series.Name + " : " + series.Data[i].ToString(BarOption.ToolTip.ValueFormat);
                    }

                    Bars[0][i].Tips = str;
                }
            }
        }
Пример #19
0
        // Override OnBarUpdate method
        protected override void OnBarUpdate()
        {
            // Protect against too few bars
            if (Bars == null)
            {
                return;
            }
            if (!Data.BarsType.GetInstance(Bars.Period.Id).IsIntraday)
            {
                return;
            }
            if (Bars.Period.Id == PeriodType.Minute && Bars.Period.Value > timeFrame / 2)
            {
                return;
            }
            if (!full && !apt)
            {
                apt        = true;
                periodBars = Data.Bars.GetBars(Bars.Instrument, new Period(PeriodType.Minute, timeFrame, MarketDataType.Last), Bars.From, Bars.To, (Session)Bars.Session.Clone(), Data.Bars.SplitAdjust, Data.Bars.DividendAdjust);
                apt        = false;
                full       = true;
            }

            // Remove calculation for first time span after open
            IBar periodBar;

            Bars.Session.GetNextBeginEnd(Time[0], out sessionBegin, out sessionEnd);
            if (Time[0] >= sessionBegin && Time[0] <= sessionBegin.AddMinutes(timeFrame))
            {
                Pivot.Reset();
                Resistance1.Reset();
                Support1.Reset();
                Resistance2.Reset();
                Support2.Reset();
                Resistance3.Reset();
                Support3.Reset();
                Resistance4.Reset();
                Support4.Reset();
                Resistance5.Reset();
                Support5.Reset();
            }
            else
            {
                // Determine open, high, low, and close
                DateTime intradayBarTime = Time[0].AddMinutes(-timeFrame);
                periodBar = periodBars.Get(periodBars.GetBar(intradayBarTime));
                double Open  = periodBar.Open;
                double High  = periodBar.High;
                double Low   = periodBar.Low;
                double Close = periodBar.Close;
                double pivot = periodBar.Close;

                // Switch central pivot calculation
                switch (centralPivotCalculation)
                {
                // Standard calculation case
                case CentralPivotCalculation.Standard:
                {
                    pivot = (High + Low + Close) / 3;
                    break;
                }

                // Open included calculation case
                case CentralPivotCalculation.OpenIncluded:
                {
                    pivot = (Open + High + Low + Close) / 4;
                    break;
                }

                // Close weighted calculation case
                case CentralPivotCalculation.CloseWeighted:
                {
                    pivot = (High + Low + Close + Close) / 4;
                    break;
                }

                // High weighted calculation case
                case CentralPivotCalculation.HighWeighted:
                {
                    pivot = (High + High + Low + Close) / 4;
                    break;
                }

                // Low weighted calculation case
                case CentralPivotCalculation.LowWeighted:
                {
                    pivot = (High + Low + Low + Close) / 4;
                    break;
                }
                }

                // Switch round to tick option
                switch (roundToTick)
                {
                // Rounding case
                case RoundToTick.Yes:
                {
                    // Set all additional pivots, rounded
                    Pivot.Set(Instrument.MasterInstrument.Round2TickSize(pivot));
                    Resistance1.Set(Instrument.MasterInstrument.Round2TickSize(2 * Pivot[0] - Low));
                    Support1.Set(Instrument.MasterInstrument.Round2TickSize(2 * Pivot[0] - High));
                    Resistance2.Set(Instrument.MasterInstrument.Round2TickSize(Pivot[0] + (High - Low)));
                    Support2.Set(Instrument.MasterInstrument.Round2TickSize(Pivot[0] - (High - Low)));
                    Resistance3.Set(Instrument.MasterInstrument.Round2TickSize(High + 2 * (Pivot[0] - Low)));
                    Support3.Set(Instrument.MasterInstrument.Round2TickSize(Low - 2 * (High - Pivot[0])));
                    Resistance4.Set(Instrument.MasterInstrument.Round2TickSize(Pivot[0] + 2 * (High - Low)));
                    Support4.Set(Instrument.MasterInstrument.Round2TickSize(Pivot[0] - 2 * (High - Low)));
                    Resistance5.Set(Instrument.MasterInstrument.Round2TickSize(2 * (Pivot[0] + High) - 3 * Low));
                    Support5.Set(Instrument.MasterInstrument.Round2TickSize(2 * (Pivot[0] + Low) - 3 * High));
                    break;
                }

                // No rounding case
                case RoundToTick.No:
                {
                    // Set all additional pivots, not rounded
                    Pivot.Set(pivot);
                    Resistance1.Set(2 * Pivot[0] - Low);
                    Support1.Set(2 * Pivot[0] - High);
                    Resistance2.Set(Pivot[0] + (High - Low));
                    Support2.Set(Pivot[0] - (High - Low));
                    Resistance3.Set(High + 2 * (Pivot[0] - Low));
                    Support3.Set(Low - 2 * (High - Pivot[0]));
                    Resistance4.Set(Pivot[0] + 2 * (High - Low));
                    Support4.Set(Pivot[0] - 2 * (High - Low));
                    Resistance5.Set(2 * (Pivot[0] + High) - 3 * Low);
                    Support5.Set(2 * (Pivot[0] + Low) - 3 * High);
                    break;
                }
                }
            }
        }
Пример #20
0
 public ChandelierLong(Bars bars, double Factor)
     : base(bars, "Chandelier Long")
 {
     int period = 14;	// ATR lookback
     for (int bar = period; bar < bars.Count; bar++)
         this[bar] = Highest.Value(bar, bars.High, period) - Factor * ATR.Value(bar, bars, period);
 }
Пример #21
0
		/// <summary>
		/// </summary>
		public override double GetPercentComplete(Bars bars, DateTime now)
		{
			return (double) bars.Get(bars.CurrentBar).Volume / bars.Period.Value;
		}
Пример #22
0
 /// <summary>
 /// Returns the hash code for this instance.
 /// </summary>
 /// <returns>A 32-bit signed integer hash code.</returns>
 public override int GetHashCode()
 {
     return(Bars.GetHashCode() ^ Beats.GetHashCode());
 }
Пример #23
0
        protected override void OnDataPoint(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isBar, double bid, double ask)
        {
            if (SessionIterator == null)
            {
                SessionIterator = new SessionIterator(bars);
            }

            double haClose = 0.0;
            double haHigh  = 0.0;
            double haLow   = 0.0;
            double haOpen  = 0.0;

            switch (BarsPeriod.BaseBarsPeriodType)
            {
            case BarsPeriodType.Day:
            {
                if (bars.Count == 0)
                {
                    if (isBar || bars.TradingHours.Sessions.Count == 0)
                    {
                        AddBar(bars, open, high, low, close, time.Date, volume);
                    }
                    else
                    {
                        SessionIterator.CalculateTradingDay(time, false);
                        AddBar(bars, open, high, low, close, SessionIterator.ActualTradingDayExchange, volume);
                    }
                }
                else
                {
                    DateTime barTime;
                    if (isBar)
                    {
                        barTime = time.Date;
                    }
                    else
                    {
                        if (bars.TradingHours.Sessions.Count > 0 && SessionIterator.IsNewSession(time, false))
                        {
                            SessionIterator.CalculateTradingDay(time, false);
                            barTime = SessionIterator.ActualTradingDayExchange;
                            if (barTime < bars.LastBarTime.Date)
                            {
                                barTime = bars.LastBarTime.Date;                                                 // Make sure timestamps are ascending
                            }
                        }
                        else
                        {
                            barTime = bars.LastBarTime.Date;                                             // Make sure timestamps are ascending
                        }
                    }

                    if (bars.DayCount < bars.BarsPeriod.BaseBarsPeriodValue ||
                        isBar && bars.Count > 0 && barTime == bars.LastBarTime.Date ||
                        !isBar && bars.Count > 0 && barTime <= bars.LastBarTime.Date)
                    {
                        haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                        UpdateBar(bars, haHigh, haLow, haClose, barTime, volume);
                    }
                    else
                    {
                        haOpen  = bars.Instrument.MasterInstrument.RoundToTickSize((bars.GetOpen(bars.Count - 1) + bars.GetClose(bars.Count - 1)) / 2.0);
                        haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                        AddBar(bars, haOpen, haHigh, haLow, haClose, barTime, volume);
                    }
                }

                break;
            }

            case BarsPeriodType.Minute:
            {
                if (bars.Count == 0)
                {
                    AddBar(bars, open, high, low, close, TimeToBarTimeMinute(bars, time, isBar), volume);
                }
                else if (!isBar && time < bars.LastBarTime)
                {
                    haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                    UpdateBar(bars, haHigh, haLow, haClose, bars.LastBarTime, volume);
                }
                else if (isBar && time <= bars.LastBarTime)
                {
                    haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                    UpdateBar(bars, haHigh, haLow, haClose, bars.LastBarTime, volume);
                }
                else
                {
                    haOpen  = bars.Instrument.MasterInstrument.RoundToTickSize((bars.GetOpen(bars.Count - 1) + bars.GetClose(bars.Count - 1)) / 2.0);
                    haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                    time    = TimeToBarTimeMinute(bars, time, isBar);
                    AddBar(bars, haOpen, haHigh, haLow, haClose, time, volume);
                }

                break;
            }

            case BarsPeriodType.Month:
            {
                if (bars.Count == 0)
                {
                    AddBar(bars, open, high, low, close, TimeToBarTimeMonth(time, bars.BarsPeriod.BaseBarsPeriodValue), volume);
                }
                else if (time.Month <= bars.LastBarTime.Month && time.Year == bars.LastBarTime.Year || time.Year < bars.LastBarTime.Year)
                {
                    if (high.ApproxCompare(bars.GetHigh(bars.Count - 1)) != 0 || low.ApproxCompare(bars.GetLow(bars.Count - 1)) != 0 || close.ApproxCompare(bars.GetClose(bars.Count - 1)) != 0 || volume > 0)
                    {
                        haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                        UpdateBar(bars, haHigh, haLow, haClose, bars.LastBarTime, volume);
                    }
                }
                else
                {
                    haOpen  = bars.Instrument.MasterInstrument.RoundToTickSize((bars.GetOpen(bars.Count - 1) + bars.GetClose(bars.Count - 1)) / 2.0);
                    haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                    AddBar(bars, haOpen, haHigh, haLow, haClose, TimeToBarTimeMonth(time, bars.BarsPeriod.BaseBarsPeriodValue), volume);
                }
                break;
            }

            case BarsPeriodType.Second:
            {
                if (bars.Count == 0)
                {
                    DateTime barTime = TimeToBarTimeSecond(bars, time, isBar);
                    AddBar(bars, open, high, low, close, barTime, volume);
                }
                else
                {
                    if (bars.BarsPeriod.BaseBarsPeriodValue > 1 && time < bars.LastBarTime || bars.BarsPeriod.BaseBarsPeriodValue == 1 && time <= bars.LastBarTime)
                    {
                        haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                        UpdateBar(bars, haHigh, haLow, haClose, bars.LastBarTime, volume);
                    }
                    else
                    {
                        haOpen  = bars.Instrument.MasterInstrument.RoundToTickSize((bars.GetOpen(bars.Count - 1) + bars.GetClose(bars.Count - 1)) / 2.0);
                        haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                        time    = TimeToBarTimeSecond(bars, time, isBar);
                        AddBar(bars, haOpen, haHigh, haLow, haClose, time, volume);
                    }
                }
                break;
            }

            case BarsPeriodType.Tick:
            {
                bool isNewSession = false;
                if (bars.BarsPeriod.BaseBarsPeriodValue == 1)
                {
                    haOpen  = haOpen.ApproxCompare(0.0) == 0 ? open : (haOpen + haClose) / 2.0;
                    haClose = haClose.ApproxCompare(0.0) == 0 ? close : bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                    AddBar(bars, haOpen, haHigh, haLow, haClose, time, volume);
                }
                else if (bars.Count == 0)
                {
                    SessionIterator.GetNextSession(time, isBar);
                    AddBar(bars, open, high, low, close, time, volume);
                }
                else if (bars.Count > 0 && !((isNewSession = SessionIterator.IsNewSession(time, isBar)) && bars.IsResetOnNewTradingDay) && bars.BarsPeriod.BaseBarsPeriodValue > 1 && bars.TickCount < bars.BarsPeriod.BaseBarsPeriodValue)
                {
                    if (isNewSession)
                    {
                        SessionIterator.GetNextSession(time, isBar);
                    }
                    haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                    UpdateBar(bars, haHigh, haLow, haClose, bars.LastBarTime, volume);
                }
                else
                {
                    if (isNewSession)
                    {
                        SessionIterator.GetNextSession(time, isBar);
                    }
                    haOpen  = bars.Instrument.MasterInstrument.RoundToTickSize((bars.GetOpen(bars.Count - 1) + bars.GetClose(bars.Count - 1)) / 2.0);
                    haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                    AddBar(bars, haOpen, haHigh, haLow, haClose, time, volume);
                }
                break;
            }

            case BarsPeriodType.Volume:
            {
                if (bars.Count == 0)
                {
                    while (volume > bars.BarsPeriod.BaseBarsPeriodValue)
                    {
                        haOpen  = haOpen.ApproxCompare(0.0) == 0 ? open : (haOpen + haClose) / 2.0;
                        haClose = haClose.ApproxCompare(0) == 0 ? close : bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                        AddBar(bars, haOpen, haHigh, haLow, haClose, time, bars.BarsPeriod.BaseBarsPeriodValue);
                        volume -= bars.BarsPeriod.BaseBarsPeriodValue;
                    }
                    if (volume > 0)
                    {
                        haOpen  = haOpen.ApproxCompare(0.0) == 0 ? open : bars.Instrument.MasterInstrument.RoundToTickSize((haOpen + haClose) / 2.0);
                        haClose = haClose.ApproxCompare(0.0) == 0 ? close : bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                        AddBar(bars, haOpen, haHigh, haLow, haClose, time, volume);
                    }
                }
                else
                {
                    long volumeTmp    = 0;
                    bool isNewSession = SessionIterator.IsNewSession(time, isBar);
                    if (!bars.IsResetOnNewTradingDay || !isNewSession)
                    {
                        volumeTmp = Math.Min(bars.BarsPeriod.BaseBarsPeriodValue - bars.GetVolume(bars.Count - 1), volume);
                        if (volumeTmp > 0)
                        {
                            haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                            haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                            haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                            UpdateBar(bars, haHigh, haLow, haClose, time, volumeTmp);
                        }
                    }

                    if (isNewSession)
                    {
                        SessionIterator.GetNextSession(time, isBar);
                    }

                    volumeTmp = volume - volumeTmp;
                    while (volumeTmp > 0)
                    {
                        haOpen  = bars.Instrument.MasterInstrument.RoundToTickSize((bars.GetOpen(bars.Count - 1) + bars.GetClose(bars.Count - 1)) / 2.0);
                        haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                        AddBar(bars, haOpen, haHigh, haLow, haClose, time, Math.Min(volumeTmp, bars.BarsPeriod.BaseBarsPeriodValue));
                        volumeTmp -= bars.BarsPeriod.BaseBarsPeriodValue;
                    }
                }

                break;
            }

            case BarsPeriodType.Week:
            {
                if (bars.Count == 0)
                {
                    AddBar(bars, open, high, low, close, TimeToBarTimeWeek(time, time.AddDays(6 - ((int)time.DayOfWeek + 1) % 7 + (bars.BarsPeriod.BaseBarsPeriodValue - 1) * 7), bars.BarsPeriod.BaseBarsPeriodValue), volume);
                }
                else if (time.Date <= bars.LastBarTime.Date)
                {
                    haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                    UpdateBar(bars, haHigh, haLow, haClose, bars.LastBarTime, volume);
                }
                else
                {
                    haOpen  = bars.Instrument.MasterInstrument.RoundToTickSize((bars.GetOpen(bars.Count - 1) + bars.GetClose(bars.Count - 1)) / 2.0);
                    haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                    haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                    haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                    AddBar(bars, haOpen, haHigh, haLow, haClose, TimeToBarTimeWeek(time.Date, bars.LastBarTime.Date, bars.BarsPeriod.BaseBarsPeriodValue), volume);
                }

                break;
            }

            case BarsPeriodType.Year:
            {
                if (bars.Count == 0)
                {
                    AddBar(bars, open, high, low, close, TimeToBarTimeYear(time, bars.BarsPeriod.BaseBarsPeriodValue), volume);
                }
                else
                {
                    if (time.Year <= bars.LastBarTime.Year)
                    {
                        haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, bars.GetOpen(bars.Count - 1)));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, bars.GetOpen(bars.Count - 1)));
                        UpdateBar(bars, haHigh, haLow, haClose, bars.LastBarTime, volume);
                    }
                    else
                    {
                        haOpen  = bars.Instrument.MasterInstrument.RoundToTickSize((bars.GetOpen(bars.Count - 1) + bars.GetClose(bars.Count - 1)) / 2.0);
                        haClose = bars.Instrument.MasterInstrument.RoundToTickSize((open + high + low + close) / 4.0);
                        haHigh  = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Max(high, haOpen));
                        haLow   = bars.Instrument.MasterInstrument.RoundToTickSize(Math.Min(low, haOpen));
                        AddBar(bars, haOpen, haHigh, haLow, haClose, TimeToBarTimeYear(time.Date, bars.BarsPeriod.BaseBarsPeriodValue), volume);
                    }
                }

                break;
            }
            }

            bars.LastPrice = haClose;
        }
Пример #24
0
        public override void OnRender(ChartControl chartControl, ChartScale chartScale, ChartBars chartBars)
        {
            Bars       bars      = chartBars.Bars;
            float      chartMinX = ConvertToHorizontalPixels(chartControl, chartControl.CanvasLeft + chartControl.Properties.BarMarginRight);
            RectangleF rect      = new RectangleF();
            int        toIndex   = chartBars.ToIndex;

            if (toIndex >= 0 && toIndex < bars.Count - 1)
            {
                toIndex++;
            }

            for (int idx = chartBars.FromIndex; idx <= toIndex; idx++)
            {
                double closeValue             = bars.GetClose(idx);
                float  high                   = chartScale.GetYByValue(bars.GetHigh(idx));
                float  low                    = chartScale.GetYByValue(bars.GetLow(idx));
                double openValue              = bars.GetOpen(idx);
                Brush  overriddenBarBrush     = chartControl.GetBarOverrideBrush(chartBars, idx);
                Brush  overriddenOutlineBrush = chartControl.GetCandleOutlineOverrideBrush(chartBars, idx);
                float  x = chartControl.GetXByBarIndex(chartBars, idx);
                float  boxStartPosition;

                if (idx == chartBars.FromIndex && (toIndex == 0 || idx == 0))
                {
                    if (toIndex == 0)
                    {
                        boxStartPosition = chartMinX;
                    }
                    else
                    {
                        boxStartPosition = 2 * x - chartControl.GetXByBarIndex(chartBars, idx + 1);
                    }
                }
                else
                {
                    boxStartPosition = chartControl.GetXByBarIndex(chartBars, idx - 1);
                }

                if (Math.Abs(x - boxStartPosition) < 0.2)
                {
                    continue;
                }

                float width = Math.Max(2f, Math.Abs(x - boxStartPosition));

                if (closeValue > openValue)
                {
                    width      -= Stroke.Width;
                    rect.X      = boxStartPosition;
                    rect.Y      = high;
                    rect.Width  = width;
                    rect.Height = low - high;
                    TransformBrush(overriddenBarBrush ?? UpBrushDX, rect);
                    TransformBrush(overriddenOutlineBrush ?? Stroke.BrushDX, rect);
                    RenderTarget.FillRectangle(rect, overriddenBarBrush ?? UpBrushDX);
                    RenderTarget.DrawRectangle(rect, overriddenOutlineBrush ?? Stroke.BrushDX, Stroke.Width, Stroke.StrokeStyle);
                }
                else
                {
                    width      -= Stroke2.Width;
                    rect.X      = boxStartPosition;
                    rect.Y      = high;
                    rect.Width  = width;
                    rect.Height = low - high;
                    TransformBrush(overriddenBarBrush ?? DownBrushDX, rect);
                    TransformBrush(overriddenOutlineBrush ?? Stroke2.BrushDX, rect);
                    RenderTarget.FillRectangle(rect, overriddenBarBrush ?? DownBrushDX);
                    RenderTarget.DrawRectangle(rect, overriddenOutlineBrush ?? Stroke2.BrushDX, Stroke2.Width, Stroke2.StrokeStyle);
                }
            }
        }
Пример #25
0
 protected override void StartCalc()
 {
     m_volume = Bars.TrueVolume();
 }
Пример #26
0
        public void TestCurrentBarEmpty()
        {
            var bars = new Bars();

            Assert.Throws <IndexOutOfRangeException>(() => bars.CurrentBar);
        }
Пример #27
0
        protected override List <Order> PreparePlaceOrders()
        {
            WriteToLogDB("PreparePlaceOrders", "Started");
            if (Bars.Count < 3)
            {
                throw new SmartException(ExceptionImportanceLevel.MEDIUM, "PreparePlaceOrders", "TrendStrat", Symbol + ": Bars are empty or has less than three elements!");
            }
            if (AmountOfVolatEstim() > AmountOfSkipBars())
            {
                throw new SmartException(ExceptionImportanceLevel.MEDIUM, "PreparePlaceOrders", "TrendStrat", Symbol + ": AmountOfVolatEstim > AmountOfSkipBars");
            }
            double[] closes = Bars.Select(bar => bar.Close).ToArray();
            double[] ys     = new double[Bars.Count - 1];
            for (int i = 0; i < Bars.Count - 1; i++)
            {
                ys[i] = closes[i + 1] / closes[i] - 1;
            }
            ys = ys.Skip(Bars.Count - 1 - AmountOfVolatEstim()).ToArray();
            double sdev  = CalcVolat(ys);
            double alpha = AlphaSpread() * Math.Sqrt(AmountOfSkipBars()) * sdev;
            //double lastPrice = Bars.Last().Close;
            double lastPrice = 0.0;

            try
            {
                Bar bar = DatabaseReader.SelectLastPrice(Symbol);
                lastPrice = bar.Close;
            }
            catch (Exception e)
            {
                lastPrice = Bars.Last().Close;
            }
            double buyStopPrice  = RoundToStep(lastPrice * (1 + alpha));
            double sellStopPrice = RoundToStep(lastPrice * (1 - alpha));
            int    buyVol        = 0;
            int    sellVol       = 0;

            if (CurrentState.Position == 0)
            {
                buyVol  = ContractsToTrade;
                sellVol = ContractsToTrade;
            }
            else if (CurrentState.Position < 0)
            {
                buyVol  = ContractsToTrade;
                sellVol = ContractsToTrade - Math.Abs(CurrentState.Position);
            }
            else
            {
                buyVol  = ContractsToTrade - Math.Abs(CurrentState.Position);
                sellVol = ContractsToTrade;
            }
            double buyPrice  = buyStopPrice + Slip();
            double sellPrice = sellStopPrice - Slip();

            if (buyStopPrice <= sellStopPrice || (buyStopPrice <= 0 && buyVol != 0) || (sellStopPrice <= 0 && sellVol != 0))
            {
                throw new SmartException(ExceptionImportanceLevel.HIGH, "PreparePlaceOrders", "TrendStrat", "buyPrice = " + buyStopPrice + ", sellPrice = " + sellStopPrice);
            }
            WriteToLogDB("PreparePlaceOrders", "Buy: Price = " + buyStopPrice + ", Volume = " + buyVol + "; Sell: Price = " + sellStopPrice + ", Volume = " + sellVol);
            List <Order> placeOrders = new List <Order>();

            DateTime dTime = ServerTime.GetRealTime();

            DatabaseWriter.InsertDecision(dTime, Symbol, ActionEnum.BUY, buyPrice, buyVol, buyStopPrice);
            DatabaseWriter.InsertDecision(dTime, Symbol, ActionEnum.SELL, sellPrice, sellVol, sellStopPrice);

            if (buyVol > 0)
            {
                placeOrders.Add(new Order(Symbol, GenerateCookie(), "", buyVol, 0, buyPrice, buyStopPrice, ActionEnum.BUY, OrderTypeEnum.STOP));
            }
            if (sellVol > 0)
            {
                placeOrders.Add(new Order(Symbol, GenerateCookie(), "", sellVol, 0, sellPrice, sellStopPrice, ActionEnum.SELL, OrderTypeEnum.STOP));
            }

            WriteToLogDB("PreparePlaceOrders", "Finished");
            return(placeOrders);
        }
Пример #28
0
 public override double GetPercentComplete(Bars bars, DateTime now)
 {
     return(0);
 }
Пример #29
0
 protected BarsSingleValues(Bars bars)
 {
     Bars = bars;
     Bars.UpdatedEvent += BarsUpdatedEvent;
 }
Пример #30
0
        protected override void OnDataPoint(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isBar, double bid, double ask)
        {
            if (SessionIterator == null)
            {
                SessionIterator = new SessionIterator(bars);
            }

            #region Building Bars from Base Period
            if (bars.Count != tmpCount)             // Reset cache when bars are trimmed
            {
                if (bars.Count == 0)
                {
                    tmpTime      = Core.Globals.MinDate;
                    tmpVolume    = 0;
                    tmpDayCount  = 0;
                    tmpTickCount = 0;
                }
                else
                {
                    tmpTime        = bars.GetTime(bars.Count - 1);
                    tmpVolume      = bars.GetVolume(bars.Count - 1);
                    tmpTickCount   = bars.TickCount;
                    tmpDayCount    = bars.DayCount;
                    bars.LastPrice = bars.GetClose(bars.Count - 1);
                    anchorPrice    = bars.LastPrice;
                }
            }

            bool isNewSession = SessionIterator.IsNewSession(time, isBar);
            bool isCalculateTradingDayDone = false;

            switch (bars.BarsPeriod.BaseBarsPeriodType)
            {
            case BarsPeriodType.Day:
                tmpTime = time.Date;                         // Will be modified for realtime only
                if (!isBar && time >= cacheSessionEnd /* on realtime includesEndTimeStamp is always false */)
                {
                    if (isNewSession)
                    {
                        SessionIterator.GetNextSession(time, isBar);
                        isCalculateTradingDayDone = true;
                    }
                    cacheSessionEnd = SessionIterator.ActualSessionEnd;
                    if (tmpTime < time.Date)
                    {
                        tmpTime = time.Date;                                                  // Make sure timestamps are ascending
                    }
                }

                if (prevTime != tmpTime)
                {
                    tmpDayCount++;
                }

                if (tmpDayCount < bars.BarsPeriod.BaseBarsPeriodValue ||
                    isBar && bars.Count > 0 && tmpTime == bars.LastBarTime.Date ||
                    !isBar && bars.Count > 0 && tmpTime <= bars.LastBarTime.Date)
                {
                    endOfBar = false;
                }
                else
                {
                    prevTime = tmpTime;
                    endOfBar = true;
                }

                break;

            case BarsPeriodType.Minute:

                if (tmpTime == Core.Globals.MinDate)
                {
                    prevTime = tmpTime = TimeToBarTimeMinute(bars, time, isBar);
                }

                if (isBar && time <= tmpTime || !isBar && time < tmpTime)
                {
                    endOfBar = false;
                }
                else
                {
                    prevTime = tmpTime;
                    tmpTime  = TimeToBarTimeMinute(bars, time, isBar);
                    endOfBar = true;
                }
                break;

            case BarsPeriodType.Volume:
                if (tmpTime == Core.Globals.MinDate)
                {
                    tmpVolume = volume;
                    endOfBar  = tmpVolume >= bars.BarsPeriod.BaseBarsPeriodValue;
                    prevTime  = tmpTime = time;
                    if (endOfBar)
                    {
                        tmpVolume = 0;
                    }
                    break;
                }

                tmpVolume += volume;
                endOfBar   = tmpVolume >= bars.BarsPeriod.BaseBarsPeriodValue;
                if (endOfBar)
                {
                    prevTime  = tmpTime;
                    tmpVolume = 0;
                }
                tmpTime = time;
                break;

            case BarsPeriodType.Tick:
                if (tmpTime == Core.Globals.MinDate || bars.BarsPeriod.BaseBarsPeriodValue == 1)
                {
                    prevTime     = tmpTime == Core.Globals.MinDate ? time : tmpTime;
                    tmpTime      = time;
                    tmpTickCount = bars.BarsPeriod.BaseBarsPeriodValue == 1 ? 0 : 1;
                    endOfBar     = bars.BarsPeriod.BaseBarsPeriodValue == 1;
                    break;
                }

                if (tmpTickCount < bars.BarsPeriod.BaseBarsPeriodValue)
                {
                    tmpTime  = time;
                    endOfBar = false;
                    tmpTickCount++;
                }
                else
                {
                    prevTime     = tmpTime;
                    tmpTime      = time;
                    endOfBar     = true;
                    tmpTickCount = 1;
                }
                break;

            case BarsPeriodType.Month:
                if (tmpTime == Core.Globals.MinDate)
                {
                    prevTime = tmpTime = TimeToBarTimeMonth(time, bars.BarsPeriod.BaseBarsPeriodValue);
                }

                if (time.Month <= tmpTime.Month && time.Year == tmpTime.Year || time.Year < tmpTime.Year)
                {
                    endOfBar = false;
                }
                else
                {
                    prevTime = tmpTime;
                    endOfBar = true;
                    tmpTime  = TimeToBarTimeMonth(time, bars.BarsPeriod.BaseBarsPeriodValue);
                }
                break;

            case BarsPeriodType.Second:
                if (tmpTime == Core.Globals.MinDate)
                {
                    prevTime = tmpTime = TimeToBarTimeSecond(bars, time, isBar);
                }
                if (bars.BarsPeriod.BaseBarsPeriodValue > 1 && time < tmpTime || bars.BarsPeriod.BaseBarsPeriodValue == 1 && time <= tmpTime)
                {
                    endOfBar = false;
                }
                else
                {
                    prevTime = tmpTime;
                    tmpTime  = TimeToBarTimeSecond(bars, time, isBar);
                    endOfBar = true;
                }
                break;

            case BarsPeriodType.Week:
                if (tmpTime == Core.Globals.MinDate)
                {
                    prevTime = tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.BarsPeriod.BaseBarsPeriodValue);
                }
                if (time.Date <= tmpTime.Date)
                {
                    endOfBar = false;
                }
                else
                {
                    prevTime = tmpTime;
                    endOfBar = true;
                    tmpTime  = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.BarsPeriod.BaseBarsPeriodValue);
                }
                break;

            case BarsPeriodType.Year:
                if (tmpTime == Core.Globals.MinDate)
                {
                    prevTime = tmpTime = TimeToBarTimeYear(time, bars.BarsPeriod.Value);
                }
                if (time.Year <= tmpTime.Year)
                {
                    endOfBar = false;
                }
                else
                {
                    prevTime = tmpTime;
                    endOfBar = true;
                    tmpTime  = TimeToBarTimeYear(time, bars.BarsPeriod.Value);
                }
                break;
            }
            #endregion
            #region Kagi Logic

            reversalPoint = bars.BarsPeriod.ReversalType == ReversalType.Tick ? bars.BarsPeriod.Value * bars.Instrument.MasterInstrument.TickSize : bars.BarsPeriod.Value / 100.0 * anchorPrice;

            if (bars.Count == 0 || IsIntraday && (bars.BarsPeriod.BaseBarsPeriodType != BarsPeriodType.Second && bars.IsResetOnNewTradingDay && isNewSession ||
                                                  bars.BarsPeriod.BaseBarsPeriodType == BarsPeriodType.Second && bars.IsResetOnNewTradingDay && isNewSession))
            {
                if (isNewSession && !isCalculateTradingDayDone)
                {
                    SessionIterator.GetNextSession(tmpTime, isBar);
                }

                if (bars.Count > 0)
                {
                    double lastOpen  = bars.GetOpen(bars.Count - 1);
                    double lastHigh  = bars.GetHigh(bars.Count - 1);
                    double lastLow   = bars.GetLow(bars.Count - 1);
                    double lastClose = bars.GetClose(bars.Count - 1);

                    if (bars.Count == tmpCount)
                    {
                        CalculateKagiBar(bars, lastOpen, lastHigh, lastLow, lastClose, prevTime, volume);
                    }
                }

                AddBar(bars, close, close, close, close, tmpTime, volume);
                anchorPrice    = close;
                trend          = Trend.Undetermined;
                prevTime       = tmpTime;
                volumeCount    = 0;
                bars.LastPrice = close;
                tmpCount       = bars.Count;
                return;
            }

            double c = bars.GetClose(bars.Count - 1);
            double o = bars.GetOpen(bars.Count - 1);
            double h = bars.GetHigh(bars.Count - 1);
            double l = bars.GetLow(bars.Count - 1);

            if (endOfBar)
            {
                CalculateKagiBar(bars, o, h, l, c, prevTime, volume);
            }
            else
            {
                volumeCount += volume;
            }

            bars.LastPrice = close;
            tmpCount       = bars.Count;
            #endregion
        }
Пример #31
0
		/// <summary>
		/// Have the .GetBars() call in a seperate thread. Reason: NT internal pool locking would not work if called in main thread.
		/// </summary>
		/// <param name="state"></param>
		private void GetBarsNow(object state)
		{
			if (Disposed)
				return;

			dailyBars			= Data.Bars.GetBars(Bars.Instrument, new Period(PeriodType.Day, 1, Bars.Period.MarketDataType), Bars.From, Bars.To, (Session) Bars.Session.Clone(), Data.Bars.SplitAdjust, Data.Bars.DividendAdjust);
			existsHistDailyData	= (dailyBars.Count <= 1) ? false : true;
			isDailyDataLoaded	= true;
			Enabled				= true;

			Cbi.Globals.SynchronizeInvoke.AsyncInvoke(new System.Windows.Forms.MethodInvoker(InvalidateNow), null);
		}
Пример #32
0
 private void AiLong()
 {
     EnterLong(lotSize, "Long");
     Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " Server Signal=" + svrSignal + " Long");
 }
Пример #33
0
        void ForwardAndBackwardBarsEnumerationConsistency(ConnectionStringBuilder builder)
        {
            var connectionString = builder.ToString();
            this.dataFeed = new DataFeed(connectionString);
            this.dataFeed.Logon += this.OnLogon;
            this.dataFeed.Start();

            var status = this.logonEvent.WaitOne(LogonWaitingTimeout);
            Assert.IsTrue(status, "Timeout of logon event");


            var startTime = new DateTime(2011, 10, 10, 12, 0, 0, 0, DateTimeKind.Utc);
            var endTime = new DateTime(2011, 10, 10, 12, 1, 0, 0, DateTimeKind.Utc);


            var forwardBars = new Bars(this.dataFeed, "EURUSD", PriceType.Bid, BarPeriod.S1, startTime, endTime);
            var forwardData = forwardBars.ToList();

            var backwardBars = new Bars(this.dataFeed, "EURUSD", PriceType.Bid, BarPeriod.S1, endTime, startTime);
            var backwardData = backwardBars.ToList();

            var count = forwardData.Count;
            Assert.IsTrue(forwardData.Count == backwardData.Count, "forwardData.Count == backwardData.Count");
            for (var index = 0; index < count; ++index)
            {
                var first = forwardData[index];
                var second = backwardData[count - 1 - index];
                Assert.IsTrue(first.From == second.From);
                Assert.IsTrue(first.To == second.To);
            }
        }
Пример #34
0
 public override double GetPercentComplete(Bars bars, DateTime now)
 {
     return(now <= bars.LastBarTime ? 1.0 - (bars.LastBarTime.Subtract(now).TotalMinutes / bars.BarsPeriod.Value) : 1);
 }
Пример #35
0
 public static ChandelierLong Series(Bars bars, double Factor)
 {
     ChandelierLong _ChandelierLong = new ChandelierLong(bars, Factor);
     return _ChandelierLong;
 }
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            //If we are not processing the current bar, return
            if (CurrentBar != Bars.GetBar(DateTime.Now))
            {
                return;
            }

            //Get current bid
            double bid = Bars.GetClose(Bars.GetBar(DateTime.Now));

            if (previous_bid < 0)
            {
                previous_bid = bid;
            }


            IDrawObject drawing_object = DrawObjects[trendLineTag];

            //Reset if drawing object is deleted or does not exist...
            if (drawing_object == null)
            {
                Type = null; AlertDone = false;
            }

            if (drawing_object != null && (drawing_object.DrawType == DrawType.Ray ||
                                           drawing_object.DrawType == DrawType.ExtendedLine ||
                                           drawing_object.DrawType == DrawType.Line))
            {
                double y1, y2;
                //int bar1,bar2;
                DateTime time1, time2;

                double end_bar_double   = (double)typeof(ChartLine).GetProperty("endBarDouble", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(drawing_object, null);
                double start_bar_double = (double)typeof(ChartLine).GetProperty("startBarDouble", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(drawing_object, null);

                if (drawing_object.DrawType == DrawType.Ray)
                {
                    IRay ray = (IRay)drawing_object;
                    y1    = ray.Anchor1Y;
                    y2    = ray.Anchor2Y;
                    time1 = ray.Anchor1Time;
                    time2 = ray.Anchor2Time;
                    //bar1 = ray.Anchor1BarsAgo;
                    //bar2 = ray.Anchor2BarsAgo;
                }
                else if (drawing_object.DrawType == DrawType.ExtendedLine)
                {
                    IExtendedLine line = (IExtendedLine)drawing_object;
                    y1    = line.StartY;
                    y2    = line.EndY;
                    time1 = line.StartTime;
                    time2 = line.EndTime;
                    //bar1 = line.StartBarsAgo;
                    //bar2 = line.EndBarsAgo;
                }
                else
                {
                    ILine line = (ILine)drawing_object;
                    y1    = line.StartY;
                    y2    = line.EndY;
                    time1 = line.StartTime;
                    time2 = line.EndTime;
                    //bar1 = line.StartBarsAgo;
                    //bar2 = line.EndBarsAgo;
                }


                //Reset alert if object has moved
                if ((time1 != this.sTime1 || time2 != this.sTime2 || y1 != this.sY1 || y2 != this.sY2) && this.sTime1 != null && this.sTime2 != null)
                {
                    Type = null; AlertDone = false;
                }

                if (AlertDone == false)
                {
                    //Store anchor to detect if object has moved
                    this.sTime1 = time1; this.sTime2 = time2; this.sY1 = y1; this.sY2 = y2;

                    //Calculate price target
                    double y     = y2 - y1;
                    double x     = end_bar_double - start_bar_double;
                    double slope = y / x;

                    //double deltaY = bar2*slope;   //time difference in ticks * slope
                    double price_target = Math.Round(y1 + slope * (CurrentBar - start_bar_double), 5);

                    //IF price is below current price target or straddles it, THEN we alert when the bid>=price_target
                    if (Type == null && (price_target - previous_bid) >= 0)
                    {
                        Type = "up";
                    }
                    if (Type == null && (previous_bid - price_target) >= 0)
                    {
                        Type = "down";
                    }

                    previous_bid = bid;

                    if (Type == "up" && bid >= price_target)
                    {
                        Alert("TrendLineAlert", NinjaTrader.Cbi.Priority.High, "Reached Trend Line @ " + price_target, AlertSound, 10, Color.Black, Color.Yellow);
                        AlertDone = true;
                    }
                    if (Type == "down" && bid <= price_target)
                    {
                        Alert("TrendLineAlert", NinjaTrader.Cbi.Priority.High, "Reached Trend Line @ " + price_target, AlertSound, 10, Color.Black, Color.Yellow);
                        AlertDone = true;
                    }
                }
            }
        }
Пример #37
0
        protected override void CalcData()
        {
            Bars.Clear();
            NeedDraw = false;
            if (Option == null || Option.Series == null || Option.SeriesCount == 0)
            {
                return;
            }
            if (DrawSize.Width <= 0 || DrawSize.Height <= 0)
            {
                return;
            }
            if (Option.XAxis.Data.Count == 0)
            {
                return;
            }

            NeedDraw     = true;
            DrawBarWidth = DrawSize.Width * 1.0f / Option.XAxis.Data.Count;

            double min = double.MaxValue;
            double max = double.MinValue;

            foreach (var series in Option.Series)
            {
                if (series.Data.Count > 0)
                {
                    min = Math.Min(min, series.Data.Min());
                    max = Math.Max(max, series.Data.Max());
                }
            }

            if (min > 0 && max > 0 && !Option.YAxis.Scale)
            {
                min = 0;
            }
            if (min < 0 && max < 0 && !Option.YAxis.Scale)
            {
                max = 0;
            }
            if (!Option.YAxis.MaxAuto)
            {
                max = Option.YAxis.Max;
            }
            if (!Option.YAxis.MinAuto)
            {
                min = Option.YAxis.Min;
            }

            if ((max - min).IsZero())
            {
                if (min.IsZero())
                {
                    max = 100;
                    min = 0;
                }
                else if (max > 0)
                {
                    max = max * 2;
                    min = 0;
                }
                else
                {
                    max = 0;
                    min = min * 2;
                }
            }

            CalcDegreeScale(min, max, Option.YAxis.SplitNumber,
                            out int start, out int end, out double interval, out int decimalCount);

            YAxisStart        = start;
            YAxisEnd          = end;
            YAxisInterval     = interval;
            YAxisDecimalCount = decimalCount;

            float x1 = DrawBarWidth / (Option.SeriesCount * 2 + Option.SeriesCount + 1);
            float x2 = x1 * 2;

            for (int i = 0; i < Option.SeriesCount; i++)
            {
                float barX   = DrawOrigin.X;
                var   series = Option.Series[i];
                Bars.TryAdd(i, new List <BarInfo>());
                for (int j = 0; j < series.Data.Count; j++)
                {
                    Color color = ChartStyle.GetColor(i);
                    if (series.Colors.Count > 0 && j >= 0 && j < series.Colors.Count)
                    {
                        color = series.Colors[j];
                    }

                    float xx = barX + x1 * (i + 1) + x2 * i + x1;
                    float ww = Math.Min(x2, series.MaxWidth);
                    xx -= ww / 2.0f;

                    if (YAxisStart >= 0)
                    {
                        float h = Math.Abs((float)(DrawSize.Height * (series.Data[j] - start * interval) / ((end - start) * interval)));

                        Bars[i].Add(new BarInfo()
                        {
                            Rect  = new RectangleF(xx, DrawOrigin.Y - h, ww, h),
                            Value = series.Data[j],
                            Color = color,
                            Top   = true
                        });
                    }
                    else if (YAxisEnd <= 0)
                    {
                        float h = Math.Abs((float)(DrawSize.Height * (end * interval - series.Data[j]) / ((end - start) * interval)));
                        Bars[i].Add(new BarInfo()
                        {
                            Rect  = new RectangleF(xx, Option.Grid.Top + 1, ww, h - 1),
                            Value = series.Data[j],
                            Color = color,
                            Top   = false
                        });
                    }
                    else
                    {
                        float lowH          = 0;
                        float highH         = 0;
                        float DrawBarHeight = DrawSize.Height * 1.0f / (YAxisEnd - YAxisStart);
                        float lowV          = 0;
                        float highV         = 0;
                        for (int k = YAxisStart; k <= YAxisEnd; k++)
                        {
                            if (k < 0)
                            {
                                lowH += DrawBarHeight;
                            }
                            if (k > 0)
                            {
                                highH += DrawBarHeight;
                            }
                            if (k < 0)
                            {
                                lowV += (float)YAxisInterval;
                            }
                            if (k > 0)
                            {
                                highV += (float)YAxisInterval;
                            }
                        }

                        // lowH.ConsoleWriteLine();
                        // highH.ConsoleWriteLine();

                        if (series.Data[j] >= 0)
                        {
                            float h = Math.Abs((float)(highH * series.Data[j] / highV));
                            Bars[i].Add(new BarInfo()
                            {
                                Rect  = new RectangleF(xx, DrawOrigin.Y - lowH - h, ww, h),
                                Value = series.Data[j],
                                Color = color,
                                Top   = true
                            });
                        }
                        else
                        {
                            float h = Math.Abs((float)(lowH * series.Data[j] / lowV));
                            Bars[i].Add(new BarInfo()
                            {
                                Rect  = new RectangleF(xx, DrawOrigin.Y - lowH + 1, ww, h - 1),
                                Value = series.Data[j],
                                Color = color,
                                Top   = false
                            });
                        }
                    }

                    barX += DrawBarWidth;
                }
            }

            if (Option.ToolTip != null)
            {
                for (int i = 0; i < Option.XAxis.Data.Count; i++)
                {
                    string str = Option.XAxis.Data[i];
                    foreach (var series in Option.Series)
                    {
                        str += '\n';
                        str += series.Name + " : " + series.Data[i].ToString(Option.ToolTip.ValueFormat);
                    }

                    Bars[0][i].Tips = str;
                }
            }
        }
Пример #38
0
        public void VerifyBarData()
        {
            Bars bars = strategy.Bars;

            Assert.AreEqual(153, bars.BarCount);
        }
Пример #39
0
        protected override void OnCalculate()
        {
            DoubleTop_DS.Set(0);

            double   HighestHighFromEchoBars;
            double   HighestHighFromEchoBarsIndex;
            DateTime HighestHighFromEchoBarsDate;

            //Get the highest Price/Index from our Echo-Period
            if (ProcessingBarIndex >= (Bars.Count - 1))
            {
                HighestHighFromEchoBars      = HighestHighPrice(this.Candles)[0];
                HighestHighFromEchoBarsIndex = HighestHighIndex(this.Candles)[0];
                HighestHighFromEchoBarsDate  = Bars[(int)HighestHighFromEchoBarsIndex].Time;
            }
            else
            {
                return;  //Just the Last Bar plus the Echo-Bars
            }


            //check if datafeed is providing appropriate data
            if (Bars[BarsAgo + (int)HighestHighFromEchoBarsIndex] == null)
            {
                return;
            }

            //Calculate the minimum distance from current low to the next low
            DateTime MinBarsAgoDateTime = Bars[BarsAgo + (int)HighestHighFromEchoBarsIndex].Time;

            //Calculate Tolerance
            double tolerance     = HighestHighFromEchoBars * (TolerancePercentage / 100);
            double tolerance_min = HighestHighFromEchoBars - tolerance;
            double tolerance_max = HighestHighFromEchoBars + tolerance;


            Print(Bars.Instrument + " Bar {0}, Tol+{1}, Tol-{2}",
                  Bars[0].Time.ToString(), Math.Round(tolerance_max, 2), Math.Round(tolerance_min, 2));



            //Check, when the chart was the last time above our current high. That period becomes irrelevant for us and gets ignored
            IEnumerable <IBar> aboveHigh = Bars.Where(y => y.High >= tolerance_max)
                                           .Where(x => x.Time < HighestHighFromEchoBarsDate)
                                           .OrderByDescending(x => x.Time);

            DateTime IgnoreFromHereOn = DateTime.MinValue.AddDays(1);

            //if there is no other High and the chart is coming all the way from a lower price, than just leave this indicator
            //if (!aboveHigh.Any())
            //{
            //    return;
            //}

            if (aboveHigh.GetEnumerator().MoveNext())
            {
                IgnoreFromHereOn = aboveHigh.FirstOrDefault().Time;
            }


            //Draw ToleranceArea for the respected timeperiod
            if (DrawTolerance)
            {
                //AddChartRectangle("ToleranceRectangle", true, Bars.GetBarsAgo(IgnoreFromHereOn), tolerance_max, 0, tolerance_min, Color.Yellow, Color.Yellow, 50);
                AddChartRectangle("ToleranceRectangle", true, IgnoreFromHereOn.AddDays(-1), tolerance_max, Bars[0].Time.AddDays(1), tolerance_min, Color.Yellow, Color.Yellow, 50);
            }

            //Check, if the time period between the highes Echo-Candle and the MinBarsAgo has any higher price. then we are not at a current high, we are just in strange time situations
            if (HighestHighPrice(this.Candles + BarsAgo)[0] > HighestHighFromEchoBars)
            {
                return;
            }

            //find previous highs
            //Select all data and find highs.
            IEnumerable <IBar> lastTops = Bars.Where(x => x.Time <= MinBarsAgoDateTime &&        //older than x Bars, so we have a arch in between the two low points
                                                     x.Time >= IgnoreFromHereOn)                 //but younger than the timeperiod when the chart was below our low
                                          .Where(y => y.High <= tolerance_max &&                 // Low <= current Low + Tolerance
                                                 y.High >= tolerance_min                         // Low >= current Low + Tolerance
                                                 )
                                          .OrderBy(x => x.High)
            ;

            int HighestHighBarsBefore = 5;

            foreach (IBar bar in lastTops)
            {
                double HighestHigh       = HighestHighPrice(Bars.GetBarsAgo(bar.Time))[0];                         //calculate the HighestHigh between current bar and potential bottom
                double HighestHighBefore = HighestHighPrice(Bars.GetBarsAgo(bar.Time) + HighestHighBarsBefore)[0]; //calculate the HighestHigh before the potential top. this is to make sure that there is no higher price leading up to the top

                //now check, if the current bar is on the same price level as the potential top. just to make sure, there is no higher price in that period.
                if (HighestHigh <= (tolerance_max) &&                     //check if that HighestHigh is inside tolerance levels
                    HighestHigh >= (tolerance_min) &&
                    HighestHighBefore <= (tolerance_max) &&               //check if the HighestHighBefore is inside tolerance levels
                    HighestHighBefore >= (tolerance_min) &&
                    (HighestHigh == HighestHighBefore ||                  //HighestHigh has to be either current bar or the current bottom from loop
                     HighestHigh == HighestHighFromEchoBars)
                    )
                {
                    Print("DoubleTop  High: {0}, Time: {1}, HighestHigh: {2}, HighestHighBefore: {3}",
                          bar.High, bar.Time.ToString(), HighestHigh, HighestHighBefore);

                    //Drawings
                    //Red Connection Line of the Bottoms
                    string strdoubleTopConnecter = "DoubleTopConnecter_" + Bars[0].Time.ToString() + "_" + bar.Time.ToString();
                    AddChartLine(strdoubleTopConnecter, Bars.GetBarsAgo(bar.Time), bar.High, (int)HighestHighFromEchoBarsIndex, HighestHighFromEchoBars, Color.Red);

                    //High and Breakthrough
                    double BreakThrough    = LowestLowPrice(Bars.GetBarsAgo(bar.Time))[0];
                    double BreakThroughAgo = LowestLowIndex(Bars.GetBarsAgo(bar.Time))[0];

                    string strBreakThrough     = strdoubleTopConnecter + "BreakThrough";
                    string strBreakThroughVert = strdoubleTopConnecter + "BreakThroughVert";
                    AddChartLine(strBreakThrough, (int)BreakThroughAgo, BreakThrough, 0, BreakThrough, Color.Aquamarine, DashStyle.Solid, 2);
                    AddChartLine(strBreakThroughVert, (int)BreakThroughAgo, bar.High, (int)BreakThroughAgo, BreakThrough, Color.Aquamarine, DashStyle.Solid, 2);

                    //Mark current High
                    DoubleTop_DS.Set((int)HighestHighFromEchoBarsIndex, 1);
                    //Mark previous High(s)
                    DoubleTop_DS.Set(Bars.GetBarsAgo(bar.Time), 0.5);
                    SetSuccessFromEcho = true;
                }
            }
            if (SetSuccessFromEcho)
            {
                DoubleTop_DS.Set(1);
            }
            else
            {
                DoubleTop_DS.Set(0);
            }
        }
Пример #40
0
 public void LoadAndUpdateBars(ref Bars bars, Bars barsUpdate)
 {
     this._dataStore.LoadBarsObject(bars);
     bars.Append(barsUpdate);
     this._dataStore.SaveBarsObject(bars);
 }
Пример #41
0
 /// methods
 /// <summary>
 /// add two doubles and return double rounded to ticksize
 /// </summary>
 /// <param name="bars">bars array</param>
 /// <param name="d1">first double input</param>
 /// <param name="d2">second double input</param>
 /// <returns>double that has been rounded to ticksize</returns>
 internal static double AddTwoDoubles(Bars bars, double d1, double d2)
 {
     return(bars.Instrument.MasterInstrument.Round2TickSize((Math.Floor(10000000.0 * d1) + Math.Floor(10000000.0 * d2)) / 10000000.0));
 }
Пример #42
0
        public override Bars RequestData(DataSource ds, string symbol, DateTime startDate, DateTime endDate, int maxBars, bool includePartialBar)
        {
            Bars bars = new Bars(symbol.Trim(new char[] { ' ', '"' }), ds.Scale, ds.BarInterval);

            if (this._dataStore.ContainsSymbol(symbol, ds.Scale, ds.BarInterval))
            {

                if ((base.DataHost.OnDemandUpdateEnabled || this._updating) && this.UpdateRequired(ds, symbol))
                {
                    DateTime lastBar = this._dataStore.SymbolLastUpdated(symbol, scale, barinterval);

                    Bars barsNew = zaglushka.RequestData(ds, symbol, startDate, endDate, maxBars, includePartialBar);

                    if (barsNew != null)
                        this.LoadAndUpdateBars(ref bars, barsNew);
                }

                _dataStore.LoadBarsObject(bars, startDate, DateTime.MaxValue, maxBars);
            }
            else
                if (base.DataHost.OnDemandUpdateEnabled || this._updating)
                {
                    bars = zaglushka.RequestData(ds, symbol, startDate, endDate, maxBars, includePartialBar);
                    this._dataStore.SaveBarsObject(bars);
                    this._dataStore.LoadBarsObject(bars);
                }

            return bars;
        }
Пример #43
0
        public void TestHighValueEmpty()
        {
            var bars = new Bars();

            Assert.Throws <IndexOutOfRangeException>(() => bars.HighValue);
        }
Пример #44
0
        public override void UpdateDataSource(DataSource ds, IDataUpdateMessage dataUpdateMsg)
        {
            this._dataUpdateMsg = dataUpdateMsg;
            this._cancelUpdate = false;
            this._updating = true;
            Bars barsNew; // The Bars object for a newly downloaded symbol, or just the new data for an existing/updated symbol

            /* Main loop */
            try
            {
                // User requested 'Cancel update'
                if (this._cancelUpdate) return;

                List<string> up2date = new List<string>();
                List<string> updateRequired = new List<string>();
                List<string> newSymbols = new List<string>();
                string sym;

                foreach (string s in ds.Symbols)
                {
                    sym = s;

                    if (!this.UpdateRequired(ds, sym))
                        up2date.Add(sym);
                    else if (this._dataStore.ContainsSymbol(sym, ds.Scale, ds.BarInterval))
                        updateRequired.Add(sym);
                    else
                        if (!this._dataStore.ContainsSymbol(sym, ds.Scale, ds.BarInterval))
                            newSymbols.Add(sym);

                }
                // For debugging:
                dataUpdateMsg.DisplayUpdateMessage(
                    "Up-to-date symbols: " + up2date.Count.ToString() + ", " +
                    "Update required for: " + updateRequired.Count.ToString() + ", " +
                    "New symbols: " + newSymbols.Count.ToString());

                /* 1. Symbols already up-to-date */

                // Process symbols which require no data update
                if (up2date.Count > 0)
                {
                    string alreadyUp2Date = null;
                    foreach (string str in up2date)
                        alreadyUp2Date += str + ",";

                    dataUpdateMsg.DisplayUpdateMessage("Symbols already up to date: " + alreadyUp2Date);
                    dataUpdateMsg.ReportUpdateProgress((up2date.Count * 100) / ds.Symbols.Count);
                }

                /* 2. Symbols to update */

                Bars bars1;

                if (updateRequired.Count > 0)
                {
                    foreach (string s in updateRequired)
                    {
                        try
                        {
                            if (!this._cancelUpdate)
                            {
                                bars1 = new Bars(s, scale, barinterval);

                                if (_dataStore.ContainsSymbol(s, ds.Scale, ds.BarInterval))
                                    _dataStore.LoadBarsObject(bars1);

                                barsNew = zaglushka.RequestData(ds, s, bars1.Date[bars1.Count - 1], DateTime.Now, int.MaxValue, true);
                                this.LoadAndUpdateBars(ref bars1, barsNew);
                            }
                            else
                                return;
                        }
                        catch (Exception e)
                        {
                            dataUpdateMsg.DisplayUpdateMessage("Error: " + e.Message);
                        }
                    }
                }

                DateTime maxValue = DateTime.MaxValue;
                string[] newSymbolsArray = new string[newSymbols.Count];

                if (newSymbols.Count > 0)
                {
                    foreach (string str in newSymbols)
                    {
                        DateTime timeOfNewSymbol = this._dataStore.SymbolLastUpdated(str, ds.Scale, ds.BarInterval); //.Date;
                        if (timeOfNewSymbol < maxValue)
                            maxValue = timeOfNewSymbol;
                    }
                }

                dataUpdateMsg.DisplayUpdateMessage("Updating...");

                /* 3. New symbols */

                // Load the Bars object from BarDataStore for updating
                Bars bars2;

                foreach (string s in newSymbols)
                {
                    try
                    {
                        if (!this._cancelUpdate)
                        {
                            bars2 = new Bars(s, ds.Scale, ds.BarInterval);
                            _dataStore.LoadBarsObject(bars2);

                            // Google doesn't provide company names, so we'll get them from Yahoo!
                            if (zaglushka.GetCompanyName(s) != null)
                                bars2.SecurityName = zaglushka.GetCompanyName(s);

                            // After some trial and error, I figured out that setting the starting date to 1/1/1971 allows to fetch all available data
                            barsNew = zaglushka.RequestData(ds, s, DateTime.MinValue, DateTime.Now, int.MaxValue, true);
                            dataUpdateMsg.DisplayUpdateMessage("Symbol: " + s + ", existing bars : " + bars2.Count + ", new bars: " + barsNew.Count);
                            this.LoadAndUpdateBars(ref bars2, barsNew);
                        }
                        else
                            return;
                    }
                    catch (Exception e)
                    {
                        dataUpdateMsg.DisplayUpdateMessage("Error: " + e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                dataUpdateMsg.DisplayUpdateMessage("Error: " + e.Message);
            }
            finally
            {
                this._updating = false;
            }
        }
        private void SetValue(IndicatorDataSeries View, int index, string CROSSSymbol, string[] cross)
        {
            double crosspips = 0.0;

            // --> Devo fare un ciclio per valutare i cross

            foreach (string onecross in cross)
            {
                try
                {
                    double opendayprice = GetOpenDayPrice(onecross);

                    Symbol tmpcross = Symbols.GetSymbol(onecross);

                    Bars tmpcrosssr = MarketData.GetBars(TimeFrame, tmpcross.Name);

                    int index2 = GetIndexByDate(tmpcrosssr, Bars.OpenTimes[index]);

                    if (tmpcrosssr.OpenTimes[index2].Hour == EndOfDay && tmpcrosssr.OpenTimes[index2].Minute >= 0 && tmpcrosssr.OpenTimes[index2].Minute <= 1)
                    {
                        SetOpenDayPrice(onecross, tmpcrosssr.OpenPrices[index2]);
                        opendayprice = tmpcrosssr.OpenPrices[index2];
                    }

                    if (opendayprice == -1)
                    {
                        havecurr = 1;
                        return;
                    }

                    double tmpcrosspips = 0.0;

                    if (onecross.IndexOf(CROSSSymbol) == 0)
                    {
                        if (tmpcrosssr.ClosePrices[index2] > opendayprice)
                        {
                            tmpcrosspips = (tmpcrosssr.ClosePrices[index2] - opendayprice) / tmpcross.PipSize;
                            crosspips   += tmpcrosspips;
                        }
                        else if (opendayprice > tmpcrosssr.ClosePrices[index2])
                        {
                            tmpcrosspips = (opendayprice - tmpcrosssr.ClosePrices[index2]) / tmpcross.PipSize;
                            crosspips   -= tmpcrosspips;
                        }
                    }
                    else if (onecross.IndexOf(CROSSSymbol) > 0)
                    {
                        if (tmpcrosssr.ClosePrices[index2] > opendayprice)
                        {
                            tmpcrosspips = (tmpcrosssr.ClosePrices[index2] - opendayprice) / tmpcross.PipSize;
                            crosspips   -= tmpcrosspips;
                        }
                        else if (opendayprice > tmpcrosssr.ClosePrices[index2])
                        {
                            tmpcrosspips = (opendayprice - tmpcrosssr.ClosePrices[index2]) / tmpcross.PipSize;
                            crosspips   += tmpcrosspips;
                        }
                    }
                    else
                    {
                        Print(string.Format("Errore : {0} non esiste", CROSSSymbol));
                    }
                }
                catch (Exception)
                {
                    //Print(string.Format("Errore : {0}", exc.Message));
                }
            }

            View[index] = crosspips;

            havecurr = 1;
        }
Пример #46
0
        /// <summary>
        /// </summary>
        /// <param name="graphics"></param>
        /// <param name="bounds"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        public override void Plot(Graphics graphics, Rectangle bounds, double min, double max)
        {
            if (Bars == null || ChartControl == null)
            {
                return;
            }

            // plot error if data not complete
            if (textBrush.Color != ChartControl.AxisColor || textFont != ChartControl.Font)
            {
                textBrush.Color = ChartControl.AxisColor;
                textFont        = ChartControl.Font;

                SizeF errorSize = graphics.MeasureString(errorData, textFont);
                errorTextWidth  = errorSize.Width + 5;
                errorTextHeight = errorSize.Height + 5;
            }

            if (priorDayHLC == HLCCalculationMode.CalcFromIntradayData)
            {
                DateTime lastBarDate = (Bars.Count == 0) ? Cbi.Globals.MaxDate : ChartControl.EquidistantBars ?
                                       Bars.GetTime(Math.Min(Bars.Count - 1, ChartControl.LastBarPainted)).Date
                                                                                : Bars.GetTime(Math.Min(Bars.Count - 1, Bars.GetBar(ChartControl.LastBarTimePainted))).Date;
                if ((lastBarDate == Cbi.Globals.MaxDate) ||
                    (Bars.BarsType.BuiltFrom == PeriodType.Minute &&
                     ((pivotRangeType == PivotRange.Monthly && Bars.Count > 0 && Bars.GetTime(0).AddSeconds(-1).Date >= new DateTime(lastBarDate.Year, lastBarDate.Month, 1).AddMonths(-1)) ||
                      (pivotRangeType == PivotRange.Weekly && Bars.Count > 0 && Bars.GetTime(0).AddSeconds(-1).Date >= lastBarDate.AddDays(-(((int)lastBarDate.DayOfWeek) + 1) % 7).AddDays(-7)) ||
                      (pivotRangeType == PivotRange.Daily && Bars.Count > 0 && Bars.GetTime(0).AddSeconds(-1).Date >= lastBarDate.AddDays(-1)))) ||
                    (Bars.BarsType.BuiltFrom != PeriodType.Minute &&
                     ((pivotRangeType == PivotRange.Monthly && Bars.Count > 0 && Bars.GetTime(0).Date >= new DateTime(lastBarDate.Year, lastBarDate.Month, 1).AddMonths(-1)) ||
                      (pivotRangeType == PivotRange.Weekly && Bars.Count > 0 && Bars.GetTime(0).Date >= lastBarDate.AddDays(-(((int)lastBarDate.DayOfWeek) + 1) % 7).AddDays(-7)) ||
                      (pivotRangeType == PivotRange.Daily && Bars.Count > 0 && Bars.GetTime(0).Date >= lastBarDate.AddDays(-1)))))
                {
                    graphics.DrawString(errorData, ChartControl.Font, textBrush, bounds.X + bounds.Width - errorTextWidth, bounds.Y + bounds.Height - errorTextHeight, stringFormatNear);
                }
            }
            else if (priorDayHLC == HLCCalculationMode.DailyBars && existsHistDailyData)
            {
                DateTime lastBarDate = (dailyBars.Count == 0) ? Cbi.Globals.MaxDate : ChartControl.EquidistantBars ?
                                       dailyBars.GetTime(Math.Min(dailyBars.Count - 1, ChartControl.LastBarPainted)).Date
                                        : dailyBars.GetTime(Math.Min(dailyBars.Count - 1, dailyBars.GetBar(ChartControl.LastBarTimePainted))).Date;
                if ((lastBarDate == Cbi.Globals.MaxDate) ||
                    (pivotRangeType == PivotRange.Monthly && dailyBars.GetTime(0).Date >= new DateTime(lastBarDate.Year, lastBarDate.Month, 1).AddMonths(-1)) ||
                    (pivotRangeType == PivotRange.Weekly && dailyBars.GetTime(0).Date >= lastBarDate.AddDays(-(((int)lastBarDate.DayOfWeek) + 1) % 7).AddDays(-7)) ||
                    (pivotRangeType == PivotRange.Daily && dailyBars.GetTime(0).Date >= lastBarDate.AddDays(-1)))
                {
                    graphics.DrawString(errorData, ChartControl.Font, textBrush, bounds.X + bounds.Width - errorTextWidth, bounds.Y + bounds.Height - errorTextHeight, stringFormatNear);
                }
            }

            float textHeight = ChartControl.Font.GetHeight();

            for (int seriesCount = 0; seriesCount < Values.Length; seriesCount++)
            {
                SolidBrush     brush = brushes[seriesCount];
                int            firstBarIdxToPaint = -1;
                int            lastX            = -1;
                int            lastY            = -1;
                SmoothingMode  oldSmoothingMode = graphics.SmoothingMode;
                Gui.Chart.Plot plot             = Plots[seriesCount];
                DataSeries     series           = (DataSeries)Values[seriesCount];

                for (int i = newSessionBarIdxArr.Count - 1; i >= 0; i--)
                {
                    int prevSessionBreakIdx = (int)newSessionBarIdxArr[i];
                    if (prevSessionBreakIdx <= this.LastBarIndexPainted)
                    {
                        firstBarIdxToPaint = prevSessionBreakIdx;
                        break;
                    }
                }

                using (GraphicsPath path = new GraphicsPath())
                {
                    if (brush.Color != plot.Pen.Color)
                    {
                        brush = new SolidBrush(plot.Pen.Color);
                    }

                    for (int idx = this.LastBarIndexPainted; idx >= Math.Max(this.FirstBarIndexPainted, this.LastBarIndexPainted - Width); idx--)
                    {
                        if (idx - Displacement < 0 || idx - Displacement >= Bars.Count || (!ChartControl.ShowBarsRequired && idx - Displacement < BarsRequired))
                        {
                            continue;
                        }
                        else if (!series.IsValidPlot(idx))
                        {
                            continue;
                        }

                        if (idx < firstBarIdxToPaint)
                        {
                            break;
                        }

                        double val = series.Get(idx);
                        int    x   = ChartControl.GetXByBarIdx(BarsArray[0], idx);
                        int    y   = ChartControl.GetYByValue(this, val);

                        if (lastX >= 0)
                        {
                            if (y != lastY)                             // Problem here is, that last bar of old day has date of new day
                            {
                                y = lastY;
                            }
                            path.AddLine(lastX - plot.Pen.Width / 2, lastY, x - plot.Pen.Width / 2, y);
                        }
                        lastX = x;
                        lastY = y;
                    }

                    graphics.SmoothingMode = SmoothingMode.AntiAlias;
                    graphics.DrawPath(plot.Pen, path);
                    graphics.SmoothingMode = oldSmoothingMode;
                    graphics.DrawString(plot.Name, ChartControl.Font, brush, lastX, lastY - textHeight / 2, stringFormatFar);
                }
            }
        }
Пример #47
0
 public BarsHigh(Bars bars)
     : base(bars)
 {
 }
Пример #48
0
        protected override void OnBarUpdate()
        {
            /* When working with multiple bar series objects it is important to understand the sequential order in which the
             * OnBarUpdate() method is triggered. The bars will always run with the primary first followed by the secondary and
             * so on.
             *
             * Important: Primary bars will always execute before the secondary bar series.
             * If a bar is timestamped as 12:00PM on the 5min bar series, the call order between the equally timestamped 12:00PM
             * bar on the 1min bar series is like this:
             *  12:00PM 5min
             *  12:00PM 1min
             *  12:01PM 1min
             *  12:02PM 1min
             *  12:03PM 1min
             *  12:04PM 1min
             *  12:05PM 5min
             *  12:05PM 1min
             *
             * When the OnBarUpdate() is called from the primary bar series (2000 ticks series in this example), do the following */
            if (BarsInProgress == 0)
            {
                if (CurrentBar < BarsRequiredToTrade)
                {
                    return;
                }

                // if the bar elapsed time span across 12 mid night
                DateTime t1 = Bars.GetTime(CurrentBar - 1);
                DateTime t2 = Bars.GetTime(CurrentBar);
                if (TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay) > 0)
                {
                    Print(Bars.GetTime(CurrentBar).ToString("yyyy-MM-ddTHH:mm:ss.ffffffK") + " EOD Session");
                    AiFlat(); // flatten the current position before going over to the next day
                    lineNo = 0;
                    return;
                }

                // construct the string buffer to be sent to DLNN
                string bufString = lineNo.ToString() + ',' +
                                   Bars.GetTime(CurrentBar - 1).ToString("HHmmss") + ',' + Bars.GetTime(CurrentBar).ToString("HHmmss") + ',' +
                                   Bars.GetOpen(CurrentBar).ToString() + ',' + Bars.GetClose(CurrentBar).ToString() + ',' +
                                   Bars.GetHigh(CurrentBar).ToString() + ',' + Bars.GetLow(CurrentBar).ToString() + ',' +
                                   Bars.GetVolume(CurrentBar).ToString() + ',' +
                                   SMA(9)[0].ToString() + ',' + SMA(20)[0].ToString() + ',' + SMA(50)[0].ToString() + ',' +
                                   MACD(12, 26, 9).Diff[0].ToString() + ',' + RSI(14, 3)[0].ToString() + ',' +
                                   Bollinger(2, 20).Lower[0].ToString() + ',' + Bollinger(2, 20).Upper[0].ToString() + ',' +
                                   CCI(20)[0].ToString() + ',' +
                                   Bars.GetHigh(CurrentBar).ToString() + ',' + Bars.GetLow(CurrentBar).ToString() + ',' +
                                   Momentum(20)[0].ToString() + ',' +
                                   DM(14).DiPlus[0].ToString() + ',' + DM(14).DiMinus[0].ToString() + ',' +
                                   VROC(25, 3)[0].ToString() + ',' +
                                   '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' +
                                   '0' + ',' + '0' + ',' + '0' + ',' + '0' + ',' + '0';

                //Print("CurrentBar = " + CurrentBar + ": " + "bufString = " + bufString);

                byte[] msg = Encoding.UTF8.GetBytes(bufString);

                // Send the data through the socket.
                int bytesSent = sender.Send(msg);

                // Receive the response from the remote device.
                int bytesRec = sender.Receive(bytes);

                svrSignal = ExtractResponse(System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length));


                //Print("Server response= " + svrSignal);

                // Return signal from DLNN is not we expected, close outstanding position and restart
                if (bytesRec == -1)
                {
                    lineNo = 0;
                    // TODO: close current position
                }
                else
                {
                    lineNo++;
                }

                // Start processing signal after 8th signal and beyond, otherwise ignore
                if (lineNo >= 8)
                {
                    ExecuteAITrade(svrSignal);
                }
            }
            // When the OnBarUpdate() is called from the secondary bar series, in our case for each tick, handle stop loss and profit chasing accordingly
            else
            {
                // if position is flat, no need to do anything
                if (currPos == Position.posFlat)
                {
                    return;
                }

                // handle stop loss or proft chasing if there is existing position and order action is either SellShort or Buy
                if (entryOrder != null && (entryOrder.OrderAction == OrderAction.Buy || entryOrder.OrderAction == OrderAction.SellShort) && (entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled))
                {
                    // if Close[0] violates soft deck, if YES handle stop loss accordingly
                    if (ViolateSoftDeck())
                    {
                        HandleSoftDeck(svrSignal);
                    }

                    // if profitChasingFlag is TRUE or Close[0] TouchedProfitChasing then handle profit chasing
                    if ((profitChasingFlag || TouchedProfitChasing()))
                    {
                        HandleProfitChasing();
                    }
                }
                return;
            }
        }
Пример #49
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="bars"></param>
		/// <param name="open"></param>
		/// <param name="high"></param>
		/// <param name="low"></param>
		/// <param name="close"></param>
		/// <param name="time"></param>
		/// <param name="volume"></param>
		/// <param name="isRealtime"></param>
		public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime)
		{
			if (bars.Count == 0 && tmpTime != Cbi.Globals.MinDate) // reset caching when live request trimmed existing bars
				tmpTime = Cbi.Globals.MinDate;

			bool endOfBar = true;
			if (tmpTime == Cbi.Globals.MinDate)
			{
				tmpTime			= time;
				tmpDayCount		= 1;
				tmpTickCount	= 1;
			}
			else if (bars.Count < tmpCount && bars.Count == 0) // reset cache when bars are trimmed
			{
				tmpTime			= Cbi.Globals.MinDate;
				tmpVolume		= 0;
				tmpDayCount		= 0;
				tmpTickCount	= 0;
			}
			else if (bars.Count < tmpCount && bars.Count > 0) // reset cache when bars are trimmed
			{
				tmpTime			= bars.GetTime(bars.Count - 1); 
				tmpVolume		= bars.GetVolume(bars.Count - 1);
				tmpTickCount	= bars.TickCount;
				tmpDayCount		= bars.DayCount;
			}

			switch (bars.Period.BasePeriodType)
			{
				case PeriodType.Day:
					{
						if (bars.Count == 0 || (bars.Count > 0 && (bars.TimeLastBar.Month < time.Month || bars.TimeLastBar.Year < time.Year)))
						{
							tmpTime			= time.Date;
							bars.LastPrice	= close;
							newSession		= true;
						}
						else
						{
							tmpTime			= time.Date;
							tmpVolume		+= volume;
							bars.LastPrice	= close;
							tmpDayCount++;

							if (tmpDayCount < bars.Period.BasePeriodValue || (bars.Count > 0 && bars.TimeLastBar.Date == time.Date))
								endOfBar = false;
						}
						break;
					}
				case PeriodType.Minute:
					{
						if (bars.Count == 0 || bars.IsNewSession(time, isRealtime))
						{
							tmpTime		= TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime);
							newSession	= true;
							tmpVolume	= 0;
						}
						else
						{
							if (isRealtime && time < bars.TimeLastBar || !isRealtime && time <= bars.TimeLastBar)
							{
								tmpTime		= bars.TimeLastBar;
								endOfBar	= false;
							}
							else
								tmpTime		= TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime);

							tmpVolume		+= volume;
						}
						break;
					}
				case PeriodType.Month:
					{
						if (tmpTime == Cbi.Globals.MinDate)
						{
							tmpTime		= TimeToBarTimeMonth(time, bars.Period.BasePeriodValue);

							if (bars.Count == 0)
								break;

							endOfBar = false;
						}
						else if ((time.Month <= tmpTime.Month && time.Year == tmpTime.Year) || time.Year < tmpTime.Year)
						{
							tmpVolume		+= volume;
							bars.LastPrice	= close;
							endOfBar		= false;
						}
						break;
					}
				case PeriodType.Second:
					{
						if (bars.IsNewSession(time, isRealtime))
						{
							tmpTime = TimeToBarTimeSecond(bars, time, new DateTime(bars.Session.NextBeginTime.Year, bars.Session.NextBeginTime.Month, bars.Session.NextBeginTime.Day, bars.Session.NextBeginTime.Hour, bars.Session.NextBeginTime.Minute, 0), bars.Period.BasePeriodValue);

							if (bars.Count == 0)
								break;

							endOfBar	= false;
							newSession	= true;
						}
						else if (time <= tmpTime)
						{
							tmpVolume		+= volume;
							bars.LastPrice	= close;
							endOfBar		= false;
						}
						else
							tmpTime = TimeToBarTimeSecond(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue);
						break;
					}
				case PeriodType.Tick:
					{
						if (bars.IsNewSession(time, isRealtime))
						{
							newSession = true;
							tmpTime = time;
							tmpTickCount = 1;

							if (bars.Count == 0)
								break;

							endOfBar = false;
						}
						else if (bars.Period.BasePeriodValue > 1 && tmpTickCount < bars.Period.BasePeriodValue)
						{
							tmpTime			= time;
							tmpVolume		+= volume;
							tmpTickCount++;
							bars.LastPrice	= close;
							endOfBar		= false;
						}
						else
							tmpTime = time; // there can't be a situation when new ticks go into old bar, this would mean peeking into future. Fixed in NT7B14 20100416 CH
						break;
					}
				case PeriodType.Volume:
					{
						if (bars.IsNewSession(time, isRealtime))
							newSession = true;
						else if (bars.Count == 0 && volume > 0)
							break;
						else
						{
							tmpVolume += volume;
							if (tmpVolume < bars.Period.BasePeriodValue)
							{
								bars.LastPrice = close;
								endOfBar = false;
							}
							else if (tmpVolume == 0)
								endOfBar = false;
						}

						tmpTime = time; // there can't be a situation when new ticks go into old bar, this would mean peeking into future. Fixed in NT7B14 20100416 CH

						break;
					}
				case PeriodType.Week:
					{
						if (tmpTime == Cbi.Globals.MinDate)
						{
							tmpTime			= TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue);

							if (bars.Count == 0)
								break;

							endOfBar = false;
						}
						else if (time.Date <= tmpTime.Date)
						{
							tmpVolume		+= volume;
							bars.LastPrice	= close;
							endOfBar		= false;
						}
						break;
					}
				case PeriodType.Year:
					{
						if (tmpTime == Cbi.Globals.MinDate)
						{
							tmpTime			= TimeToBarTimeYear(time, bars.Period.Value);

							if (bars.Count == 0)
								break;

							endOfBar = false;
						}
						else if (time.Year <= tmpTime.Year)
						{
							tmpVolume		+= volume;
							bars.LastPrice	= close;
							endOfBar		= false;
						}
						break;
					}
				default:
					break;
			}

			if (bars.Count == 0 || (newSession && IsIntraday))
			{
				AddBar(bars, open, close, close, close, tmpTime, volume, isRealtime);
				upTrend				= (open < close);
				newSessionIdx		= bars.Count - 1;
				newSession			= false;
				firstBarOfSession	= true;
				anchorPrice			= close;
				switchPrice			= open;
			}
			else if (firstBarOfSession && endOfBar == false)
			{
				double prevOpen		= bars.GetOpen(bars.Count - 1);
				bars.RemoveLastBar(isRealtime);
				AddBar(bars, prevOpen, close, close, close, tmpTime, tmpVolume, isRealtime);
				upTrend				= (prevOpen < close);
				anchorPrice			= close;
			}
			else
			{
				int		breakCount		= bars.Period.Value;
				Bar		bar				= (Bar)bars.Get(bars.Count - 1);
				double	breakMax		= double.MinValue;
				double	breakMin		= double.MaxValue;

				if (firstBarOfSession)
				{
					AddBar(bars, anchorPrice, close, close, close, tmpTime, volume, isRealtime);
					firstBarOfSession	= false;
					tmpVolume			= volume;
					tmpTime				= Cbi.Globals.MinDate;
					return;
				}

				if (bars.Count - newSessionIdx - 1 < breakCount)
					breakCount = bars.Count - (newSessionIdx + 1);

				for (int k = 1; k <= breakCount; k++)
				{
					Bar tmp			= (Bar)bars.Get(bars.Count - k - 1);
					breakMax		= Math.Max(breakMax, tmp.Open);
					breakMax		= Math.Max(breakMax, tmp.Close);
					breakMin		= Math.Min(breakMin, tmp.Open);
					breakMin		= Math.Min(breakMin, tmp.Close);
				}

				bars.LastPrice = close;

				if (upTrend)
					if (endOfBar)
					{
						bool adding = false;
						if (bars.Instrument.MasterInstrument.Compare(bar.Close, anchorPrice) > 0)
						{
							anchorPrice = bar.Close;
							switchPrice = bar.Open;
							tmpVolume = volume;
							adding = true;
						}
						else
							if (bars.Instrument.MasterInstrument.Compare(breakMin, bar.Close) > 0)
							{
								anchorPrice = bar.Close;
								switchPrice = bar.Open;
								tmpVolume = volume;
								upTrend = false;
								adding = true;
							}

						if (adding)
						{
							double tmpOpen = upTrend ? Math.Min(Math.Max(switchPrice, close), anchorPrice) : Math.Max(Math.Min(switchPrice, close), anchorPrice);
							AddBar(bars, tmpOpen, close, close, close, tmpTime, volume, isRealtime);
						}
						else
						{
							bars.RemoveLastBar(isRealtime);
							double tmpOpen = Math.Min(Math.Max(switchPrice, close), anchorPrice);
							AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume, isRealtime);
						}
					}
					else
					{
						bars.RemoveLastBar(isRealtime);
						double tmpOpen = Math.Min(Math.Max(switchPrice, close), anchorPrice);
						AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume, isRealtime);
					}
				else
					if (endOfBar)
					{
						bool adding = false;
						if (bars.Instrument.MasterInstrument.Compare(bar.Close, anchorPrice) < 0)
						{
							anchorPrice		= bar.Close;
							switchPrice		= bar.Open;
							tmpVolume		= volume;
							adding			= true;
						}
						else
							if (bars.Instrument.MasterInstrument.Compare(breakMax, bar.Close) < 0)
							{
								anchorPrice		= bar.Close;
								switchPrice		= bar.Open;
								tmpVolume		= volume;
								upTrend			= true;
								adding			= true;
							}

						if (adding)
						{
							double tmpOpen = upTrend ? Math.Min(Math.Max(switchPrice, close), anchorPrice) : Math.Max(Math.Min(switchPrice, close), anchorPrice);
							AddBar(bars, tmpOpen, close, close, close, tmpTime, volume, isRealtime);
						}
						else
						{
							bars.RemoveLastBar(isRealtime);
							double tmpOpen = Math.Max(Math.Min(switchPrice, close), anchorPrice);
							AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume, isRealtime);
						}
					}
					else
					{
						bars.RemoveLastBar(isRealtime);
						double tmpOpen = Math.Max(Math.Min(switchPrice, close), anchorPrice);
						AddBar(bars, tmpOpen, close, close, close, tmpTime, tmpVolume, isRealtime);
					}
			}

			if (endOfBar)
				tmpTime = Cbi.Globals.MinDate;

			tmpCount = bars.Count;
		}
Пример #50
0
 public override double Calculate(TradeType tradeType, OrderType orderType, double orderPrice, double shares, Bars bars)
 {
     return F * shares + (M / 100) * (shares * orderPrice);
 }
Пример #51
0
        void ExportBars(StreamWriter writer, DataFeedStorage storage)
        {
            writer.WriteLine("Time,Open,High,Low,Close,Volume");
            var bars = new Bars(storage.Offline, m_symbol, PriceType.Bid, m_period, m_from, m_to);

            foreach (var element in bars)
            {
                if (!continueMonitoring)
                {
                    break;
                }
                var dateTime = element.From.ToString("yyyy.MM.dd HH:mm:ss.fff");
                var stOpen = element.Open.ToString(CultureInfo.InvariantCulture);
                var stHigh = element.High.ToString(CultureInfo.InvariantCulture);
                var stLow = element.Low.ToString(CultureInfo.InvariantCulture);
                var stClose = element.Close.ToString(CultureInfo.InvariantCulture);
                var stVolume = element.Volume.ToString(CultureInfo.InvariantCulture);
                writer.WriteLine("{0},{1},{2},{3},{4},{5}", dateTime, stOpen, stHigh, stLow, stClose, stVolume);
                this.RaiseProgress(element.From);
            }
        }
Пример #52
0
 protected override void StartCalc()
 {
     m_brkoutfactor = 1 + brkoutpct * 0.01;
     Volume         = Bars.TrueVolume();
 }
Пример #53
0
        public override void OnRender(ChartControl chartControl, ChartScale chartScale, ChartBars chartBars)
        {
            Bars       bars     = chartBars.Bars;
            float      barWidth = GetBarPaintWidth(BarWidthUI);
            Vector2    point0   = new Vector2();
            Vector2    point1   = new Vector2();
            RectangleF rect     = new RectangleF();

            for (int idx = chartBars.FromIndex; idx <= chartBars.ToIndex; idx++)
            {
                //Brush		overriddenBarBrush		= chartControl.GetBarOverrideBrush(chartBars, idx);
                Brush  overriddenOutlineBrush = chartControl.GetCandleOutlineOverrideBrush(chartBars, idx);
                double closeValue             = bars.GetClose(idx);
                int    close     = chartScale.GetYByValue(closeValue);
                int    high      = chartScale.GetYByValue(bars.GetHigh(idx));
                int    low       = chartScale.GetYByValue(bars.GetLow(idx));
                double openValue = bars.GetOpen(idx);
                int    open      = chartScale.GetYByValue(openValue);
                int    x         = chartControl.GetXByBarIndex(chartBars, idx);
                Brush  brush     = overriddenOutlineBrush ?? (closeValue > openValue ? UpBrushDX : closeValue < openValue ? DownBrushDX : DojiBrushDX);
                //Brush br = overriddenOutlineBrush ?? Stroke2.BrushDX;

                if (Math.Abs(open - close) < 0.0000001)
                {
                    // Line
                    point0.X = x - barWidth * 0.5f;
                    point0.Y = close;
                    point1.X = x + barWidth * 0.5f;
                    point1.Y = close;
                    if (!(brush is SolidColorBrush))
                    {
                        TransformBrush(overriddenOutlineBrush ?? DojiBrushDX, new RectangleF(point0.X, point0.Y - LineWidth, barWidth, LineWidth));
                    }
                    RenderTarget.DrawLine(point0, point1, brush, LineWidth);
                }
                else
                {
                    // Candle
                    rect.X      = x - barWidth * 0.5f + 0.5f;
                    rect.Y      = Math.Min(close, open);
                    rect.Width  = barWidth - 1;
                    rect.Height = Math.Max(open, close) - Math.Min(close, open);
                    if (!(brush is SolidColorBrush))
                    {
                        TransformBrush(brush, rect);
                    }
                    RenderTarget.DrawRectangle(rect, brush, LineWidth);
                    if (chartBars.IsInHitTest)
                    {
                        RenderTarget.FillRectangle(rect, chartControl.SelectionBrush);
                    }
                }

                // High wick
                if (high < Math.Min(open, close))
                {
                    point0.X = x;
                    point0.Y = high;
                    point1.X = x;
                    point1.Y = Math.Min(open, close);
                    if (!(brush is SolidColorBrush))
                    {
                        TransformBrush(brush, new RectangleF(point0.X - Stroke2.Width, point0.Y, LineWidth, point1.Y - point0.Y));
                    }
                    RenderTarget.DrawLine(point0, point1, brush, LineWidth);
                }

                // Low wick
                if (low > Math.Max(open, close))
                {
                    point0.X = x;
                    point0.Y = low;
                    point1.X = x;
                    point1.Y = Math.Max(open, close);
                    if (!(brush is SolidColorBrush))
                    {
                        TransformBrush(brush, new RectangleF(point1.X - Stroke2.Width, point1.Y, LineWidth, point0.Y - point1.Y));
                    }
                    RenderTarget.DrawLine(point0, point1, brush, LineWidth);
                }
            }
        }
Пример #54
0
    void Start()
    {
        cDate = iDate.ToString();

        crimes = new Dictionary <string, Dictionary <string, Dictionary <string, float> > >();

        states = new Dictionary <string, Bars>();
        reader = new CSVReader("Assets/Crime_Rate.csv");

        foreach (Bars child in GetComponentsInChildren <Bars>())
        {
            // If we initialize there are no errors
            child.initialize();
            states.Add(child.name, child);
        }

        // Create the outer two levels year and state
        foreach (string y in reader.data["Year"])
        {
            if (!crimes.ContainsKey(y))
            {
                int tmp = int.Parse(y);
                smallestDate = Math.Min(smallestDate, tmp);
                largestDate  = Math.Max(largestDate, tmp);

                crimes.Add(y, new Dictionary <string, Dictionary <string, float> >());
                foreach (string s in states.Keys)
                {
                    crimes[y].Add(s, new Dictionary <string, float>());
                }
            }
        }

        // Populate the data
        for (int i = 0; i < reader.data["Year"].Count; i++)
        {
            foreach (string s in interests)
            {
                crimes[reader.data["Year"][i]][reader.data["State Name"][i]].Add(s, float.Parse(reader.data[s][i]));
            }
        }

        Dictionary <string, float> scales = new Dictionary <string, float>();

        // Get the scale of the data and use it to normalize
        foreach (string s in interests)
        {
            float mVal = 0.000000000000000001f;

            Dictionary <string, Dictionary <string, float> > st = crimes[cDate];
            foreach (string sV in st.Keys)
            {
                mVal = Math.Max(mVal, st[sV][s]);
            }

            scales.Add(s, mVal);
        }

        // Set the values for each of the states
        foreach (String state in states.Keys)
        {
            Bars bars = states[state];
            foreach (string s in interests)
            {
                string title = s;
                float  value = crimes[cDate][bars.name][s];
                bars.addBar(title, (value / scales[s]) * maxHeight, title + System.Environment.NewLine + "[" + value.ToString("0.###") + "]" + System.Environment.NewLine + state);
            }
        }
    }
Пример #55
0
        void BackwardBarsEnumeration(ConnectionStringBuilder builder)
        {
            var connectionString = builder.ToString();
            this.dataFeed = new DataFeed(connectionString);
            this.dataFeed.Logon += this.OnLogon;
            this.dataFeed.Start();

            var status = this.logonEvent.WaitOne(LogonWaitingTimeout);
            Assert.IsTrue(status, "Timeout of logon event");

            var startTime = new DateTime(2015, 10, 10, 12, 0, 0, 0, DateTimeKind.Utc);
            var endTime = new DateTime(2015, 10, 10, 12, 1, 0, 0, DateTimeKind.Utc);

            var data = new List<Bar>();
            var bars = new Bars(this.dataFeed, "EURUSD", PriceType.Bid, BarPeriod.S1, endTime, startTime);

            foreach (var element in bars)
            {
                Assert.IsTrue(startTime <= element.From, "startTime <= element.From");
                Assert.IsTrue(element.To <= endTime, "element.To <= endTime");
                Assert.IsTrue(element.From < element.To, "Invalid a bar timestamp");
                data.Add(element);
            }

            this.dataFeed.Logon -= this.OnLogon;
            this.dataFeed.Stop();

            for (var index = 1; index < data.Count; ++index)
            {
                var first = data[index];
                var second = data[index - 1];
                Assert.IsTrue(first.To <= second.From, "Invalid bars sequence order.");
            }
        }
Пример #56
0
        protected override void OnBarUpdate()
        {
            // Get time of first bar on chart
            if (isFirstChartBar)
            {
                isFirstChartBar = false;
                chartStartTime  = Time[0];
            }

            // Not Enough History to calc rel vol
            if (Time[0].Date.AddDays(LookBackDays * -1) < chartStartTime.Date)
            {
                return;
            }

            // Only gather vol history on first tick
            // of bar since history does not change for
            // a given bar
            if (IsFirstTickOfBar)
            {
                int skipDays = 0;
                totalHistPeriodVol = 0;
                histPeriodVol      = new List <double>(LookBackDays);

                // Loop until all same timeperiod lookback days
                // are found or lookback exceeds history
                while (histPeriodVol.Count < LookBackDays)
                {
                    // Bar target time
                    DateTime tt = Time[0].AddDays((histPeriodVol.Count + 1 + skipDays) * -1);

                    // Bail if target day is before first chart, not enough history
                    if (tt.Date < Time[CurrentBar].Date)
                    {
                        return;
                    }

                    // No weekends
                    if ((tt.DayOfWeek == DayOfWeek.Saturday) || (tt.DayOfWeek == DayOfWeek.Sunday))
                    {
                        skipDays++;
                        continue;
                    }

                    // Skip over early close days and Holidays
                    if (TradingHours.PartialHolidays.ContainsKey(tt.Date) ||
                        TradingHours.Holidays.ContainsKey(tt.Date))
                    {
                        skipDays++;
                        continue;
                    }

                    // Get Prev day's same time bar
                    int relPrevBar = ChartBars.GetBarIdxByTime(ChartControl, tt);

                    // If the returned bar is not the expected date, a bar with the
                    // timetarget is not on the chart.  Dont know why GetBarIdxByTime
                    // does not return something more normal(like a -1) for a GetBarIdxXXX()
                    // miss.  Instead it just returns the incorrect bar.
                    // At this point a missing bar is unexpected
                    if (tt != Bars.GetTime(relPrevBar))
                    {
                        throw new Exception("Missing data error - Target Time: " + tt + " Found Time: " + Bars.GetTime(relPrevBar));
                    }

                    totalHistPeriodVol += Bars.GetVolume(relPrevBar);
                    histPeriodVol.Add(Bars.GetVolume(relPrevBar));
                }
                histPeriodVolStd = this.getStandardDeviation(histPeriodVol);
                avgHistPeriodVol = totalHistPeriodVol / LookBackDays;
            }

            // Get historical average at time volume from last x days
            Values[3][0] = avgHistPeriodVol;

            // Difference between avg period vol and current bars vol
            double rel_vol_diff = Volume[0] - avgHistPeriodVol;

            // Std Hi-Low Hash marks
            Values[1][0] = Math.Max(0.0, avgHistPeriodVol - histPeriodVolStd);
            Values[2][0] = avgHistPeriodVol + histPeriodVolStd;

            // Raw period volume bars, color code based on
            // volume above, below or within 1 std band
            Values[0][0] = Volume[0];
            if (ShowVolumeBars)
            {
                // Greater than one std
                if (Volume[0] > Values[2][0])
                {
                    PlotBrushes[0][0] = VolAboveStdBrush;
                }
                // Within one std
                else if (Values[0][0] > Values[1][0])
                {
                    PlotBrushes[0][0] = VolWithinStdBrush;
                }
                // Less than 1 std
                else
                {
                    PlotBrushes[0][0] = VolBelowStdBrush;
                }
            }
            else
            {
                PlotBrushes[0][0] = Brushes.Transparent;
            }
        }
Пример #57
0
        public Bars GetBars(string symbol, PeriodType period, ref int count, int offset)
        {
            string rc = Command(string.Format("BR {0} {1} {2} {3}", symbol, (int) period, offset, count));
            if (!ResponseOK(rc) || rc.Length < 3)
                return null;

            string[] reply = rc.Substring(3).Split(new[] {' '});
            if (reply.Length < 5 || reply[0] != symbol)
                return null;

            int rperiod, rbars, roffset, rcount;
            try
            {
                rperiod = int.Parse(reply[1]);
                rbars = int.Parse(reply[2]);
                roffset = int.Parse(reply[3]);
                rcount = int.Parse(reply[4]);
            }
            catch (FormatException)
            {
                return null;
            }
            if (rperiod != (int) period || roffset != offset || rcount*6 != reply.Length - 5)
                return null;

            count = rbars;
            var bars = new Bars(symbol, period);
            for (int i = 5; i < reply.Length; i += 6)
            {
                try
                {
                    DateTime time = FromTimestamp(int.Parse(reply[i]));
                    double open = StringToDouble(reply[i + 1]);
                    double high = StringToDouble(reply[i + 2]);
                    double low = StringToDouble(reply[i + 3]);
                    double close = StringToDouble(reply[i + 4]);
                    int volume = int.Parse(reply[i + 5]);

                    bars.Insert(time, open, high, low, close, volume);
                }
                catch (FormatException)
                {
                    return null;
                }
            }
            return bars;
        }
Пример #58
0
 public override double GetPercentComplete(Bars bars, DateTime now)
 {
     return(bars.Count == 0 ? 0 : (double)bars.GetVolume(bars.Count - 1) / bars.BarsPeriod.Value);
 }
        private void _drawLevelFromCustomBar()
        {
            // --> Prelevo le candele scelte
            Bars BarsCustom = MarketData.GetBars(PivotTimeFrame);

            int index = BarsCustom.Count - 1;

            // --> Potrei non avere un numero sufficiente di candele
            if (index < 1 || (BarsCustom[index].Close == BarsCustom[index].Open))
            {
                return;
            }



            try
            {
                // --> TimeSpan DiffTime = BarsCustom[index - i].OpenTime.Subtract(BarsCustom[(index - i) - 1].OpenTime); // <-- Strategia da valutare

                DateTime thisCandle = BarsCustom[index].OpenTime;
                DateTime nextCandle = thisCandle.AddMinutes(_getTimeFrameCandleInMinutes(PivotTimeFrame));

                double high  = BarsCustom[index - 1].High;
                double low   = BarsCustom[index - 1].Low;
                double close = BarsCustom[index - 1].Close;

                double pivot = (high + low + close) / 3;

                double r1 = pivot + (Fibo1 * (high - low));
                double s1 = pivot - (Fibo1 * (high - low));

                double r2 = pivot + (Fibo2 * (high - low));
                double s2 = pivot - (Fibo2 * (high - low));

                double r3 = pivot + (Fibo3 * (high - low));
                double s3 = pivot - (Fibo3 * (high - low));

                Chart.DrawTrendLine("pivot ", thisCandle, pivot, nextCandle, pivot, Color.FromName(PivotColor.ToString("G")), 1, LineStyle.DotsVeryRare);
                Chart.DrawTrendLine("r1 ", thisCandle, r1, nextCandle, r1, Color.FromName(ResistanceColor.ToString("G")), 1, LineStyle.DotsRare);
                Chart.DrawTrendLine("r2 ", thisCandle, r2, nextCandle, r2, Color.FromName(ResistanceColor.ToString("G")), 1, LineStyle.Lines);
                Chart.DrawTrendLine("r3 ", thisCandle, r3, nextCandle, r3, Color.FromName(ResistanceColor.ToString("G")), 1, LineStyle.Solid);
                Chart.DrawTrendLine("s1 ", thisCandle, s1, nextCandle, s1, Color.FromName(SupportColor.ToString("G")), 1, LineStyle.DotsRare);
                Chart.DrawTrendLine("s2 ", thisCandle, s2, nextCandle, s2, Color.FromName(SupportColor.ToString("G")), 1, LineStyle.Lines);
                Chart.DrawTrendLine("s3 ", thisCandle, s3, nextCandle, s3, Color.FromName(SupportColor.ToString("G")), 1, LineStyle.Solid);

                if (!ShowLabels)
                {
                    return;
                }

                Chart.DrawText("Lpivot ", "P", nextCandle, pivot, Color.FromName(PivotColor.ToString("G"))).VerticalAlignment = VerticalAlignment.Center;
                Chart.DrawText("Lr1 ", "R1", nextCandle, r1, Color.FromName(ResistanceColor.ToString("G"))).VerticalAlignment = VerticalAlignment.Center;
                Chart.DrawText("Lr2 ", "R2", nextCandle, r2, Color.FromName(ResistanceColor.ToString("G"))).VerticalAlignment = VerticalAlignment.Center;
                Chart.DrawText("Lr3 ", "R3", nextCandle, r3, Color.FromName(ResistanceColor.ToString("G"))).VerticalAlignment = VerticalAlignment.Center;
                Chart.DrawText("Ls1 ", "S1", nextCandle, s1, Color.FromName(SupportColor.ToString("G"))).VerticalAlignment    = VerticalAlignment.Center;
                Chart.DrawText("Ls2 ", "S2", nextCandle, s2, Color.FromName(SupportColor.ToString("G"))).VerticalAlignment    = VerticalAlignment.Center;
                Chart.DrawText("Ls3 ", "S3", nextCandle, s3, Color.FromName(SupportColor.ToString("G"))).VerticalAlignment    = VerticalAlignment.Center;
            }
            catch
            {
            }
        }
Пример #60
0
 public BarsLow(Bars bars)
     : base(bars)
 {
 }