Inheritance: Next
Exemplo n.º 1
0
        public void Serialization_NewCross_SerializedAndDeserializedCrossEqualsUnlessJsonIgnoredProperties()
        {
            ///Arrange

            var targetColor       = new Color(250, 250, 250);
            var targetStrokeColor = new Color(120, 120, 120);
            var targetStartPoint  = new Point(0.0, 0.0);
            var targetEndPoint    = new Point(10.0, 10.0);

            var targetCross = new Cross(targetStartPoint, targetEndPoint, LineStyle.Dashed)
            {
                FillColor    = targetColor,
                IsChanged    = true,
                LineWidth    = 1,
                Selected     = false,
                StrokeColor  = targetStrokeColor,
                Style        = LineStyle.Dashed,
                IgnoreEvents = false
            };

            ///Act

            var deserializedTargetCross = Utils.SerializeDeserialize(targetCross);

            ///Assert

            Utils.AssertDeserializedStorablePropertyEquality <Cross> (targetCross, deserializedTargetCross);
        }
Exemplo n.º 2
0
        public void GetSelection_NewCross_GetAllSelectionPositionsOk()
        {
            ///Arrange

            var targetColor      = new Color(250, 250, 250);
            var targetStartPoint = new Point(0.0, 0.0);
            var targetEndPoint   = new Point(10.0, 10.0);

            var targetCross = new Cross(targetStartPoint, targetEndPoint, LineStyle.Dashed)
            {
                FillColor = targetColor,
            };

            var topLeftPoint     = targetCross.Area.TopLeft;
            var bottomLeftPoint  = targetCross.Area.BottomLeft;
            var topRightPoint    = targetCross.Area.TopRight;
            var bottomRightPoint = targetCross.Area.BottomRight;

            ///Act

            var topLeftSelection     = targetCross.GetSelection(topLeftPoint);
            var bottomLeftSelection  = targetCross.GetSelection(bottomLeftPoint);
            var topRightSelection    = targetCross.GetSelection(topRightPoint);
            var bottomRightSelection = targetCross.GetSelection(bottomRightPoint);

            ///Assert

            Assert.AreEqual(SelectionPosition.TopLeft, topLeftSelection.Position);
            Assert.AreEqual(SelectionPosition.BottomLeft, bottomLeftSelection.Position);
            Assert.AreEqual(SelectionPosition.TopRight, topRightSelection.Position);
            Assert.AreEqual(SelectionPosition.BottomRight, bottomRightSelection.Position);
        }
Exemplo n.º 3
0
        public void Move_NewCross_CrossMoved()
        {
            ///Arrange

            var targetColor      = new Color(250, 250, 250);
            var targetStartPoint = new Point(0.0, 0.0);
            var targetEndPoint   = new Point(10.0, 10.0);

            var targetCross = new Cross(targetStartPoint, targetEndPoint, LineStyle.Dashed)
            {
                FillColor = targetColor,
            };

            ///Act

            var selection = new Selection(targetCross, SelectionPosition.All);

            targetCross.Move(selection, targetEndPoint, targetCross.Start.Copy());

            ///Assert

            Assert.AreEqual(10.0, targetCross.Start.X);
            Assert.AreEqual(10.0, targetCross.Start.Y);
            Assert.AreEqual(20.0, targetCross.Stop.X);
            Assert.AreEqual(20.0, targetCross.Stop.Y);
        }
Exemplo n.º 4
0
        protected override void OnBar(Instrument instrument, Bar bar)
        {
            // Add bar to bar series.
            Bars.Add(bar);

            Log(bar, barsGroup);

            if (fastSMA.Count > 0)
            {
                Log(fastSMA.Last, fastSmaGroup);
            }

            if (slowSMA.Count > 0)
            {
                Log(slowSMA.Last, slowSmaGroup);
            }

            // Calculate performance.
            Portfolio.Performance.Update();

            Log(Portfolio.Value, equityGroup);

            if (!SuspendTrading)
            {
                // Check strategy logic.
                if (fastSMA.Count > 0 && slowSMA.Count > 0)
                {
                    Cross cross = fastSMA.Crosses(slowSMA, bar.DateTime);

                    if (!HasPosition(instrument))
                    {
                        // Enter long/short.
                        if (cross == Cross.Above)
                        {
                            Order enterOrder = BuyOrder(Instrument, Qty, "Enter Long");
                            Send(enterOrder);
                        }
                        else if (cross == Cross.Below)
                        {
                            Order enterOrder = SellOrder(Instrument, Qty, "Enter Short");
                            Send(enterOrder);
                        }
                    }
                    else
                    {
                        // Reverse to long/short.
                        if (Position.Side == PositionSide.Long && cross == Cross.Below)
                        {
                            Order reverseOrder = SellOrder(Instrument, Math.Abs(Position.Amount) + Qty, "Reverse to Short");
                            Send(reverseOrder);
                        }
                        else if (Position.Side == PositionSide.Short && cross == Cross.Above)
                        {
                            Order reverseOrder = BuyOrder(Instrument, Math.Abs(Position.Amount) + Qty, "Reverse to Long");
                            Send(reverseOrder);
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
    int Click = 0;  //记录当前棋子
    //当放置棋子的时候判断状态和能否放置
    public void OnClick(Cross cross)
    {
        if (_state != State.BlackGo)
        {
            return;
        }

        // 如果该位置可以放置
        if (CanPlace(cross.GridX, cross.GridY))
        {
            Click++;
            _lastPlayerX = cross.GridX;
            _lastPlayerY = cross.GridY;
            if (PlaceChess(cross, true))
            {
                // 已经胜利
                _state = State.Over;
                ShowResult(ChessType.Black);
                return;
            }
            else
            {
                //判断当前棋局是否满棋,玩家先走,287次正确走步时为满棋
                if (Click >= 287 && mWhoStart == 1)
                {
                    mMaxTimer = 0;
                    return;
                }
                // 换电脑走
                _state           = State.WhiteGo;
                mTimerLabel.text = "0:00";
                mMaxTimer        = 15;
            }
        }
    }
Exemplo n.º 6
0
        void CrossToBigs(TAlternativeParserGrpCrossItem ACrossItem, TAlternativeParserItemBig ABig)
        {
            TAlternativeParserGrpItemBase     Base;
            TAlternativeParserGrpCrossItemOut Cross;
            TAlternativeParserItemBig         mHeadBig = new TAlternativeParserItemBig();

            mHeadBig.OwnerBig = ABig;
            ABig.MainList.Append(mHeadBig);

            TAlternativeParserItemBig mBig = new TAlternativeParserItemBig();

            for (int i = 0; i <= ACrossItem.CountBasis - 1; i++)
            {
                FillItemGrp(ACrossItem.GetItemsBasis(i), ref mBig);
            }
            mBig.Check    = true;
            mBig.OwnerBig = mHeadBig;
            mBig.NumAlt   = 0;
            mBig.Cross    = true;
            mHeadBig.AddBig(mBig);
            for (int i = 0; i <= ACrossItem.CountOut - 1; i++)
            {
                mBig       = new TAlternativeParserItemBig();
                Cross      = ACrossItem.GetItemsOut(i);
                mBig.Check = true;
                mBig.Cross = true;
                for (int j = 0; j <= Cross.Count - 1; j++)
                {
                    FillItemGrp(Cross.GetItems(j), ref mBig);
                }
                mBig.NumAlt   = i + 1;
                mBig.OwnerBig = mHeadBig;
                mHeadBig.AddBig(mBig);
            }
        }
Exemplo n.º 7
0
        public void TestLoadSave()
        {
            var tmpFolder = "Users.0000";
            var tmpName   = "Test1";
            var exts      = new[] { "banzai", "editor", "solve" };
            var cross     = new Cross(10, 10);

            cross.SetCell(0, 0, Cross.CellState.Fill);

            CrossIO.ExportEditor(tmpName, cross);
            var cross0 = CrossIO.Import(tmpFolder, tmpName);

            if (cross0.GetCell(0, 0) != Cross.CellState.Unknown)
            {
                throw new Exception();
            }
            CrossIO.Export(tmpFolder, tmpName, cross);
            var cross1 = CrossIO.Import(tmpFolder, tmpName);

            if (cross1.GetCell(0, 0) != Cross.CellState.Fill)
            {
                throw new Exception();
            }

            var dir =
                $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\{Application.CompanyName}\{
                    Application.ProductName}\{tmpFolder}\";

            Array.ForEach(exts, e => File.Delete(dir + tmpName + '.' + e));
            if (!Directory.EnumerateFiles(dir).Any())
            {
                Directory.Delete(dir);
            }
        }
Exemplo n.º 8
0
        public override void CreateShape()
        {
            //base.CreateShape();
            Cross cross = new Cross(this.X, this.Y);

            this.GraphicsPath = cross.GetPath();
        }
Exemplo n.º 9
0
        private void TestCheckLineVal(string sample, string len, string state)
        {
            var results = new Dictionary <Cross.SectionState, char>
            {
                { Cross.SectionState.Right, '+' },
                { Cross.SectionState.Wrong, '-' },
                { Cross.SectionState.InProgress, '?' }
            };
            var source = new Dictionary <char, Cross.CellState>
            {
                { '#', Cross.CellState.Fill },
                { '.', Cross.CellState.Dot },
                { ' ', Cross.CellState.Unknown }
            };
            var cross = new Cross(sample.Length, 1);

            for (int i = 0; i < sample.Length; i++)
            {
                cross.SetCell(i, 0, source[sample[i]]);
            }
            cross.Left[0] = new Cross.Line(len.Split().Select(int.Parse));
            cross.CheckLines();

            var res =
                new string(
                    cross.Left[0]
                    .Sections
                    .Select(s => results[s.State])
                    .ToArray());

            if (res != state)
            {
                throw new Exception($"[{sample}] [{len}] [{state}]{Environment.NewLine}==> Wrong [{res}]");
            }
        }
Exemplo n.º 10
0
        // distance to outlet, position of outlet
        public IEnumerable <Cross> GetCrosses(int n, int row, int col)
        {
            // len: 2(N+1)+1
            //var len = (1 << (N + 1)) + 1;
            var end = 1 << (n + 1);

            if (row == 0 || col == 0 || row == end || col == end)
            {
                yield break;
            }

            var cross = new Cross
            {
                Dir           = Direction.Down,
                CenterRow     = 1 << n,
                    CenterCol = 1 << n
            };

            yield return(cross);

            while (!cross.Covers(row, col))
            {
                cross = cross.GetNext(--n, row, col);
                yield return(cross);
            }
        }
Exemplo n.º 11
0
 public void addLayer(LayerType layerType, int countNeurons, List <float> weights = null)
 {
     if (layerType == LayerType.Input)
     {
         Input i = new Input();
         i.model = this;
         i.addNeurons(countNeurons);
         layers.Add(i);
         i.connectNeurons();
     }
     else if (layerType == LayerType.Serial)
     {
         Serial s = new Serial();
         s.model = this;
         s.addNeurons(countNeurons);
         layers.Add(s);
         s.connectNeurons(weights);
     }
     else if (layerType == LayerType.Cross)
     {
         Cross c = new Cross();
         c.model = this;
         c.addNeurons(countNeurons);
         layers.Add(c);
         c.connectNeurons(weights);
     }
 }
Exemplo n.º 12
0
        public void InitSnap(Canvas canvas, IEnumerable <Point> snapPointsOfFigure, IEnumerable <Figure> blackList)
        {
            _startSnapPoints = new List <Point>();
            _ghostSnapPoints = new List <Point>();

            foreach (var point in snapPointsOfFigure)
            {
                //We need the the fixed snap-points,
                //because we are oprating with dxSum and dySum,
                //which make only sense with the original starting positions.
                _startSnapPoints.Add(point.Clone());

                //We move ghost snap points around to the new position.
                _ghostSnapPoints.Add(point.Clone());
            }

            _snapPointCross = new Cross(0, 0, 10, 10)
            {
                IsSelectable    = false,
                IsDragable      = false,
                IsVisible       = false,
                CanBeSnapTarget = false,
                StrokeColor     = Colors.Red,
            };

            canvas.AddFigure(_snapPointCross);
        }
Exemplo n.º 13
0
    //此处判断当前走棋后是否胜出
    bool PlaceChess(Cross cross, bool isblack)
    {
        if (cross == null)
        {
            return(false);
        }

        // 创建棋子
        var newChess = GameObject.Instantiate <GameObject>(isblack ? BlackPrefab : WhitePrefab);

        newChess.transform.SetParent(cross.gameObject.transform, false);

        var ctype = isblack ? ChessType.Black : ChessType.White;

        // 设置数据
        _model.Set(cross.GridX, cross.GridY, ctype);

        //每次需要判断是否是满棋局
        if (Click >= 288 && isblack)
        {
            mMaxTimer = 0;
            return(true);
        }

        var linkCount = _model.CheckLink(cross.GridX, cross.GridY, ctype);

        return(linkCount >= BoardModel.WinChessCount);
    }
Exemplo n.º 14
0
        private void OnBar_Symbol0(Bar bar)
        {
            do
            {
                Cross cross = fastSMA.Crosses(slowSMA, bar);
                if (Cross.Above == cross)
                {
                    base.TargetPosition = 1;
                    TextParameter.Text  = "金叉";
                }
                else if (Cross.Below == cross)
                {
                    base.TargetPosition = -1;
                    TextParameter.Text  = "死叉";
                }
                else
                {
                    // 保持上次的状态
                }

                // 合成合约没有持仓等基本信息,如何进行止损呢?
                FixedStop(bar.Close, 300, StopMode.Absolute, "");
                TakeProfit(bar.Close, 400, StopMode.Absolute, "");
            } while (false);
        }
Exemplo n.º 15
0
 private void DecombinePreview(bool _isStart)
 {
     if (_isStart && m_previewStreet.GetStartConnection().m_OtherConnection != null)
     {
         Connection oldConnection = m_previewStreet.GetStartConnection().m_OtherConnection;
         Connection.DeCombine(m_previewStreet.GetStartConnection(), m_previewStreet.GetStartConnection().m_OtherConnection);
         if (oldConnection.m_Owner is Street)
         {
             StreetComponentManager.CreateDeadEnd((Street)oldConnection.m_Owner, oldConnection.m_OwnerStart);
         }
         else if (oldConnection.m_Owner is Cross)
         {
             Cross c = (Cross)oldConnection.m_Owner;
             StreetComponentManager.CreateDeadEnd((Cross)oldConnection.m_Owner, c.GetIndexByConnection(oldConnection));
         }
     }
     else if (m_previewStreet.m_EndConnection.m_OtherConnection != null)
     {
         Connection oldConnection = m_previewStreet.m_EndConnection.m_OtherConnection;
         Connection.DeCombine(m_previewStreet.m_EndConnection, m_previewStreet.m_EndConnection.m_OtherConnection);
         if (oldConnection.m_Owner is Street)
         {
             StreetComponentManager.CreateDeadEnd((Street)oldConnection.m_Owner, oldConnection.m_OwnerStart);
         }
         else if (oldConnection.m_Owner is Cross)
         {
             Cross c = (Cross)oldConnection.m_Owner;
             StreetComponentManager.CreateDeadEnd((Cross)oldConnection.m_Owner, c.GetIndexByConnection(oldConnection));
         }
     }
 }
Exemplo n.º 16
0
 public void UploadFile(string subPath,
                        string fileName,
                        string realFileName,
                        Cross crossWith,
                        string crossId)
 {
 }
Exemplo n.º 17
0
        /// <summary>
        /// Перерисовать только активные части
        /// </summary>
        /// <param name="comParams">Пересичтать параметры</param>
        public void RedrawActual()
        {
            if (Candels.AllDataPaintedCandle.Count == 0)
            {
                return;
            }
            FocusCandle = null;

            //Рисуем активную свечу справа
            PaintActual(Candels.AllDataPaintedCandle[0]);
            //Ищем активную(наведенную свечу)
            FocusCandle = Candels.AllDataPaintedCandle.FirstOrDefault(dCan => dCan.Body.X <= CrossPoint.X && dCan.Body.X + dCan.Body.Width >= CrossPoint.X);
            if (FocusCandle.NotIsNull())
            {
                Cross.PaintCrossLines(CrossPoint, FocusCandle);
                if (FocusCandle.TailCoord.High.Y <= CrossPoint.Y && FocusCandle.TailCoord.Low.Y >= CrossPoint.Y)
                {
                    //Событие передвижения по свечке
                    if (OnCandleMove.NotIsNull())
                    {
                        OnCandleMove(CrossPoint, FocusCandle);
                    }
                }
            }
            else
            {
                Cross.PaintCrossLines(CrossPoint, null);
            }
        }
Exemplo n.º 18
0
    public void OnClick(Cross cross)
    {
        if (_state != State.BlackGo)
        {
            return;
        }

        // 不能在已经放置过的棋子上放置
        if (CanPlace(cross.GridX, cross.GridY))
        {
            _lastPlayerX = cross.GridX;
            _lastPlayerY = cross.GridY;

            if (PlaceChess(cross, true))
            {
                // 已经胜利
                _state = State.Over;
                ShowResult(ChessType.Black);
            }
            else
            {
                // 换电脑走
                _state = State.WhiteGo;
            }
        }
    }
Exemplo n.º 19
0
    // Update is called once per frame
    void Update()
    {
        if (roomNumber == giovannicontrol.roomNumber)
        {
            if (!atacar.isPlaying && !morir.isPlaying)
            {
                fly.Play();
                fly.loop = true;
            }
            else
            {
                fly.Stop();
            }

            timetochange++;

            if (aLife <= 0)
            {
                Death();
            }


            if (timetochange > 50)
            {
                move_x       = Random.Range(-0.5f, 0.5f);
                move_y       = Random.Range(-0.5f, 0.5f);
                timetochange = 0;
            }

            transform.position = new Vector2(
                move_x * aSpeed + transform.position.x,
                move_y * aSpeed + transform.position.y
                );

            if (cross)
            {
                crossStats = GameObject.FindObjectOfType <Cross>();
                Physics2D.IgnoreCollision(crossStats.GetComponent <Collider2D>(), GetComponent <Collider2D>(), true);

                if (crossContact())
                {
                    isAttacked();
                }
            }

            attack();
        }


        if (target.position.x < transform.position.x && facingRight)
        {
            Flip();
        }

        if (target.position.x > transform.position.x && !facingRight)
        {
            Flip();
        }
    }
Exemplo n.º 20
0
        public void IsLeftSide_ShouldReturnCorrectResult(int x, int y, bool result)
        {
            IPoint lineStartPoint = new BoundaryPoint(14.3429, 17.5163);
            IPoint lineEndPoint   = new BoundaryPoint(29.9575, 32.0665);
            ICross point          = new Cross(x, y);

            Assert.AreEqual(result, GeometryHelper.IsLeftSide(lineStartPoint, lineEndPoint, point));
        }
Exemplo n.º 21
0
        protected void HandleCross(Cross item, PdfPageWriter writer, Context context)
        {
            var physicalBox = ToPhysicalBox(item, context);
            var go          = (PdfGraphicsOptions)GetReferenceObject(item.GraphicsOptionsRef ?? context.GraphicsOptionsRef) ?? new PdfGraphicsOptions();

            writer.DrawLine(physicalBox[0], physicalBox[1], physicalBox[2], physicalBox[3], go);
            writer.DrawLine(physicalBox[2], physicalBox[1], physicalBox[0], physicalBox[3], go);
        }
Exemplo n.º 22
0
 public static Cross ClampMin(Cross c, float f)
 {
     for (int i = 0; i < 5; i++)
     {
         c.vals[i] = Mathf.Min(f, c.vals[i]);
     }
     return(c);
 }
Exemplo n.º 23
0
        public void AddInGroup(T n, string ls)
        {
            Cross c = new Cross(n);

            c.Dat      = Last;
            c.listSign = ls;
            Last       = c;
        }
 private static void OnCenterPointUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
 {
     Cross cross = d as Cross;
     cross.NotifyPropertyChanged("X1");
     cross.NotifyPropertyChanged("X2");
     cross.NotifyPropertyChanged("Y1");
     cross.NotifyPropertyChanged("Y2");
 }
Exemplo n.º 25
0
 public void HideTipForce()
 {
     LeanTween.cancel(gameObject);
     transform.GetComponent <UnityEngine.EventSystems.EventTrigger>().enabled = false;
     gameObject.GetComponent <CanvasGroup>().alpha = 0;
     //gameObject.SetActive(false);
     _isOver = false;
     Cross.SetActive(false);
 }
Exemplo n.º 26
0
        public Cross GetCrossProjectNodeKPIs()
        {
            CrossProjectNodeKPIsHelper ch = new CrossProjectNodeKPIsHelper();
            Cross result = ch.GetRow();
            CrossProjectNodeKPIsCellHelper cch = new CrossProjectNodeKPIsCellHelper();

            result.Rows = cch.GetRows();
            return(result);
        }
Exemplo n.º 27
0
        public Cross GetCrossGuides(QueryByCrossGuidesCellRequest request)
        {
            CrossGuidesHelper     ch     = new CrossGuidesHelper();
            Cross                 result = ch.GetRow();
            CrossGuidesCellHelper cch    = new CrossGuidesCellHelper();

            result.Rows = cch.GetRows(request);
            return(result);
        }
Exemplo n.º 28
0
        public Cross GetCross()
        {
            CrossHelper     ch     = new CrossHelper();
            Cross           result = ch.GetRow();
            CrossCellHelper cch    = new CrossCellHelper();

            result.Rows = cch.GetRows();
            return(result);
        }
Exemplo n.º 29
0
    public override void OnBar(Bar bar)
    {
        // does the fast average cross over the slow average?
        // if so, time to buy long
        Cross cross = sma1.Crosses(sma2, bar);

        // we only allow one active position at a time
        if (entryEnabled)
        {
            // if price trend is moving upward, open a long
            // position using a market order, and send it in
            if (cross == Cross.Above)
            {
                marketOrder = MarketOrder(OrderSide.Buy, Qty, "Entry");
                marketOrder.Send();
                // if one cancels all exit method is desired, we
                // also issue a limit (profit target) order, and
                // a stop loss order in case the breakout fails.
                // The OCA exit method uses a real stop loss order.
                // The Stop exit method uses a stop indicator.
                // Use either the OCA or Stop method, not both at once.
                if (OCAExitEnabled)
                {
                    // create and send a profit limit order
                    double profitTarget = LimitOCALevel * bar.Close;
                    limitOrder          = SellLimitOrder(Qty, profitTarget, "Limit OCA " + OCACount);
                    limitOrder.OCAGroup = "OCA " + Instrument.Symbol + " "
                                          + OCACount;
                    limitOrder.Send();
                    // create and send a stop loss order
                    double lossTarget = StopOCALevel * bar.Close;
                    stopOrder          = SellStopOrder(Qty, lossTarget, "Stop OCA " + OCACount);
                    stopOrder.OCAGroup = "OCA " + Instrument.Symbol + " "
                                         + OCACount;
                    stopOrder.Send();
                    // bump the OCA count to make OCA group strings unique
                    OCACount++;
                }
                entryEnabled = false;
            }
        }
        // else if entry is disabled on this bar, we have an open position
        else
        {
            // if we are using the crossover exit, and if the fast
            // average just crossed below the slow average, issue a
            // market order to close the existing position
            if (CrossoverExitEnabled)
            {
                if (cross == Cross.Below)
                {
                    marketOrder = MarketOrder(OrderSide.Sell, Qty, "Crossover Exit");
                    marketOrder.Send();
                }
            }
        }
    }
Exemplo n.º 30
0
        public Cross GetCrossProjectNodeFilesKMExtend(QueryByCrossProjectNodeFilesKMExtendRequest request)
        {
            CrossProjectNodeFilesHelper ch = new CrossProjectNodeFilesHelper();
            Cross result = ch.GetRow();
            CrossProjectNodeFilesCellKMExtendHelper cch = new CrossProjectNodeFilesCellKMExtendHelper();

            result.Rows = cch.GetRows(request);
            return(result);
        }
Exemplo n.º 31
0
        public Engine(Graphics g)
        {
            g_Handle = g;

            Paint_Area = new Rectangle(0, 0, 1600, 1200);

            //Balls = new List<Ball>();
            //Queued_Balls = new Queue<Ball>();

            ArrowStart = new Point();
            ArrowEnd = new Point();
            ShowArrow = false;

            //Lines = new List<Obstacle>();
            //Lines.Add(new Obstacle(new Point(700, 700), new Point(900, 700)));
            //Lines.Add(new Obstacle(new Point(700, 700), new Point(700, 900)));

            TestStart = new Point();
            TestEnd = new Point();
            TestCut = new Point();
            Actual = new Cross();
            The = new Line();
        }
Exemplo n.º 32
0
		internal static ECross Convert(Cross cross)
		{
			switch (cross)
			{
			case Cross.Above:
				return ECross.Above;
			case Cross.Below:
				return ECross.Below;
			case Cross.None:
				return ECross.None;
			default:
				throw new NotImplementedException("Cross type is not supported : " + cross);
			}
		}
Exemplo n.º 33
0
		internal static ECross Convert(Cross cross)
		{
			switch (cross)
			{
				case Cross.Above:
					return ECross.Above;
				case Cross.Below:
					return ECross.Below;
				case Cross.None:
					return ECross.None;
				default:
					throw new ArgumentException(string.Format("Unsupported Cross - {0}", cross));
			}
		}
Exemplo n.º 34
0
Arquivo: code.cs Projeto: heber/FreeOQ
	public override void OnBar(Bar bar)
	{
		if (sma.Count == 0)
			return;

		// if we are using a trend-following exit and have an open
		// positiong that we should close
		if (TrendFollowingExitEnabled && HasPosition && Bars.Count > TrendFollowingExitLength + 1)
		{
			// check if we are long and today's close is lower than 
			// lowest low of the last "trendFollowingExitLength" bars.
			// If so, then exit on the next bar open
			if (Position.Side == PositionSide.Long)
			{
				double prevLow = Bars.LowestLow(Bars.Count - TrendFollowingExitLength - 1, Bars.Count - 2);

				if (bar.Close < prevLow)
					exitOnBarOpen = true;
			}

			// check if we are short and today's close is higher than 
			// highest high of the last "trendFollowingExitLength" bars
			// If so, exit on the next bar open
			if (Position.Side == PositionSide.Short)
			{
				double prevHigh = Bars.HighestHigh(Bars.Count - TrendFollowingExitLength - 1, Bars.Count - 2);

				if (bar.Close > prevHigh)
					exitOnBarOpen = true;
			}
		}

		// look for N consecutive closes after a crossover
		Cross cross = Bars.Crosses(sma, bar);
		// if any cross occurred, reset the consecutive close count,
		// and copy the cross value so we can reset our copy of it
		// without wiping out the original indicator.
		if (cross != Cross.None)
		{
			smaCross = cross;
			ccCount = 0;
		}

		// if a cross occurred, increment the cc count, because the 
		// first bar counts as the first consecutive close
		if (smaCross != Cross.None)
			ccCount++;

		// if we have enough consecutive closes, it's time to trade
		if (ccCount == ConsClosesCount)
		{
			// if we have no position open, or if we have a position
			// that is opposite the cross direction (ie, we need to 
			// close the position)
			if (!HasPosition ||
				(Position.Side == PositionSide.Long && smaCross == Cross.Below) ||
				(Position.Side == PositionSide.Short && smaCross == Cross.Above))
			{
				switch (FilterType)
				{
					// enter a trade if no filters are being used
					case FilterType.None:
					{
						entryEnabled = true;
						break;
					}
					// enter a trade if the RAVI filter says ok
					case FilterType.RAVI:
					{
						entryEnabled = FilterRAVI();
						break;
					}
					// enable a trade if the ADX filter says ok
					case FilterType.ADX:
					{
						entryEnabled = FilterADX();
						break;
					}
				}

				// if an entry was enabled, open a position on next bar open
				if (entryEnabled)
					exitOnBarOpen = false;
				// and reset our copy of the cross status to none
				smaCross = Cross.None;
			}
			// reset the consecutive close count too
			ccCount = 0;
		}
	}
Exemplo n.º 35
0
        /// <summary>
        /// Draw a frame around the buffer from (0,0) to (width, height)
        /// </summary>
        void DrawFrame(PixelsBuffer buffer, Cross.Drawing.Color color)
        {
            int idx = 0; //pixel index

            //draw left, right lines
            for (int y = 0; y < buffer.Height; y++)
            {
                //left
                idx = buffer.StartOffset + buffer.Stride * y;// buffer.GetPixelIndex(0, y);
                buffer.Data[idx] = color.Data;

                //right
                idx = buffer.StartOffset + buffer.Stride * y + buffer.Width - 1;// buffer.GetPixelIndex(buffer.Width - 1, y);
                buffer.Data[idx] = color.Data;
            }

            //draw top, bottom lines
            for (int x = 0; x < buffer.Width; x++)
            {
                //top
                idx = buffer.StartOffset + x;// buffer.GetPixelIndex(x, 0);
                buffer.Data[idx] = color.Data;

                //bottom
                idx = buffer.StartOffset + (buffer.Height - 1) * buffer.Stride + x;// buffer.GetPixelIndex(x, buffer.Height - 1);
                buffer.Data[idx] = color.Data;
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Draw a diagonal line with the specified color from (0,0) to (width, height)
        /// </summary>
        void DrawLine(PixelsBuffer buffer, Cross.Drawing.Color color)
        {
            int idx = 0; //pixel index

            for (int i = 0; i < buffer.Height; i++)
            {
                idx = buffer.StartOffset + i * buffer.Stride + i; // buffer.GetPixelIndex(i, i);
                buffer.Data[idx] = color.Data;
            }
        }
Exemplo n.º 37
0
        private void RenderEngine(object obj)
        {
            SolidBrush Background = new SolidBrush(Color.White);

            int Ticks_1000ms = Environment.TickCount;
            int Ticks_50ms = Environment.TickCount;
            Point Acceleration = new Point(0, 1); // 10 px down
            Point No_Acceleration = new Point(-Acceleration.X * 2, -Acceleration.Y * 2);
            Pen Arrow = new Pen(new SolidBrush(Color.Green), 2f);
            Pen TestPoints = new Pen(new SolidBrush(Color.Red), 1f);
            Pen TestCutts = new Pen(new SolidBrush(Color.Lime), 1f);
            Font fps_font = new Font("Arial", 12);
            SolidBrush fps_brush = new SolidBrush(Color.Black);

            Bitmap RenderedFrame = new Bitmap(Paint_Area.Width, Paint_Area.Height);
            Graphics f_Handle = Graphics.FromImage(RenderedFrame);
            //Obstacle Obs = new Obstacle(new Point())

            //TestCut = new Point(Paint_Area.Width / 2, Paint_Area.Height / 2);

            Cross Test = new Cross(new Point(Paint_Area.Width / 2, Paint_Area.Height / 2)); // centered test point
            Test.Color = Color.Green;

            Line Mirror = new Line();
            Mirror.Start = new Point(Paint_Area.Width / 2 - 100, Paint_Area.Height / 2 - 100);
            Mirror.End = new Point(Paint_Area.Width / 2 + 100, Paint_Area.Height / 2 + 100);
            Mirror.Color = Color.Gray;

            Line Exit = new Line();
            Exit.Color = Color.Red;
            Exit.Start = Test.Position;

            int fps = 0;
            int frames_rendered = 0;
            string info = "";
            double Angle = 45;
            double Length = 300;

            while(true)
            {
                // draw background
                f_Handle.FillRectangle(Background, Paint_Area);

                /*
                // draw balls
                foreach(Ball ball in Balls)
                {
                    ball.Draw(f_Handle);
                }

                // draw lines
                foreach(Obstacle obs in Lines)
                {
                    obs.Draw(f_Handle);
                }

                // draw arrow
                if (ShowArrow)
                {
                    f_Handle.DrawLine(Arrow, ArrowStart, ArrowEnd);

                    // calculate angle and arrow
                }*/

                f_Handle.DrawString(fps.ToString() + "fps", fps_font, fps_brush, 0, 0);

                // draw crosses
                Test.Draw(f_Handle, Paint_Area.Height);
                Actual.Draw(f_Handle, Paint_Area.Height);

                The.Start = Actual.Position;
                The.End = Test.Position;
                The.Draw(f_Handle, Paint_Area.Height);
                Mirror.Draw(f_Handle, Paint_Area.Height);

                // calculate end
                double beta = Mirror.Angle - The.Angle;
                double c = The.Lenght * Math.Cos(beta / 360 * 2 * Math.PI);

                Exit.End = new Point((int)(2 * c * Math.Cos(Mirror.Angle / 360 * 2 * Math.PI) + The.Start.X), (int)(2 * c * Math.Sin(Mirror.Angle / 360 * 2 * Math.PI) + The.Start.Y));
                Exit.Draw(f_Handle, Paint_Area.Height);

                // draw info
                info = "beta: " + beta.ToString() + "\n";
                info += "c: " + c.ToString();

                f_Handle.DrawString(info, fps_font, fps_brush, 0, 50);

                // draw line

                /*
                // testpoints
                f_Handle.DrawLine(TestPoints, TestStart.X - 10, TestStart.Y, TestStart.X + 10, TestStart.Y);
                f_Handle.DrawLine(TestPoints, TestStart.X, TestStart.Y - 10, TestStart.X, TestStart.Y + 10);
                f_Handle.DrawLine(TestPoints, TestEnd.X - 10, TestEnd.Y, TestEnd.X + 10, TestEnd.Y);
                f_Handle.DrawLine(TestPoints, TestEnd.X, TestEnd.Y - 10, TestEnd.X, TestEnd.Y + 10);
                f_Handle.DrawLine(TestCutts, TestCut.X - 10, TestCut.Y, TestCut.X + 10, TestCut.Y);
                f_Handle.DrawLine(TestCutts, TestCut.X, TestCut.Y - 10, TestCut.X, TestCut.Y + 10);*/

                // draw on screen
                g_Handle.DrawImage(RenderedFrame, 0, 0,800,600);

                // check for change
                if(Environment.TickCount > (Ticks_50ms + 50))
                {
                    // refresh ticks
                    Ticks_50ms = Environment.TickCount;

                    // every 50 ms
                    Mirror.Start.X = (int)(-(Length / 2) * Math.Sin(Angle / 360 * 2 * Math.PI) + The.End.X);
                    Mirror.Start.Y = (int)(-(Length / 2) * Math.Cos(Angle / 360 * 2 * Math.PI) + The.End.Y);
                    Mirror.End.X = (int)((Length / 2) * Math.Sin(Angle / 360 * 2 * Math.PI) + The.End.X);
                    Mirror.End.Y = (int)((Length / 2) * Math.Cos(Angle / 360 * 2 * Math.PI) + The.End.Y);

                    // inkrement angle
                    //Angle += 1;
                }

                // calculate fps
                if (Environment.TickCount > (Ticks_1000ms + 1000))
                {
                    // refresh ticks
                    Ticks_1000ms = Environment.TickCount;

                    fps = frames_rendered;
                    frames_rendered = 0;
                }
                frames_rendered++;

                /*
                // move balls every 500 ms
                if(Environment.TickCount > (Ticks + 10))
                {
                    // refresh ticks
                    Ticks = Environment.TickCount;

                    // move balls
                    foreach(Ball ball in Balls)
                    {
                        // move ball
                        ball.Move(Acceleration);

                        // check for exit down
                        if(ball.Position.Y > Paint_Area.Height)
                        {
                            // change direction
                            ball.Movement = new Point(ball.Movement.X, -ball.Movement.Y * 70 / 100);
                            ball.Move(No_Acceleration);
                        }

                        // exit right
                        if ((ball.Position.X > Paint_Area.Width) || (ball.Position.X < 0))
                        {
                            // change direction
                            ball.Movement = new Point(-ball.Movement.X * 70 / 100, ball.Movement.Y);
                            ball.Move(No_Acceleration);
                        }

                        // check for collision
                        foreach(Obstacle obs in Lines)
                        {
                            obs.calculateCollision(ball);
                        }
                    }

                    // check for finish
                    Balls.RemoveAll(x => (x.Position.X > Paint_Area.Width) || (x.Position.X < 0) || (x.Position.Y > Paint_Area.Height) || (x.Position.Y < 0));
                }

                // check for new balls
                while(Queued_Balls.Count > 0)
                {
                    Balls.Add(Queued_Balls.Dequeue());
                }
                 */
            }
        }