Exemplo n.º 1
0
 private void GraphicTimer_Tick(object sender, EventArgs e)
 {
     lock (this)
     {
         Visualize.Refresh();
     }
 }
Exemplo n.º 2
0
        public ViewsNavigation()
        {
            VisualizeControl = new Visualize();
            DevicesControl   = new Devices();

            ConfigureNavigation();
        }
        private void VisualizeDeployment()
        {
            using (var bmp = Screenshot.Capture())
            {
                using (var g = Graphics.FromImage(bmp))
                {
                    // find the radius of 5 tiles
                    var p1       = new PointFT(0f, 0f).ToScreenAbsolute();
                    var p2       = new PointFT(0f, 5f).ToScreenAbsolute();
                    var distance = Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

                    Visualize.RectangleT(bmp, _border, new Pen(Color.FromArgb(128, Color.Red)));

                    g.DrawLine(new Pen(Color.FromArgb(192, Color.Red)), _attackLine.Item1.ToScreenAbsolute(), _attackLine.Item2.ToScreenAbsolute());

                    //foreach (PointFT point in _tankPoints)
                    //    Visualize.RectangleT(bmp, new RectangleT((int)point.X, (int)point.Y, 1, 1), new Pen(Color.Orange));

                    Visualize.RectangleT(bmp, new RectangleT((int)_qwPoint.X, (int)_qwPoint.Y, 1, 1), new Pen(Color.Blue));

                    Visualize.RectangleT(bmp, new RectangleT((int)_core.X, (int)_core.Y, 1, 1), new Pen(Color.Purple));

                    g.FillEllipse(new SolidBrush(Color.FromArgb(128, Color.Gold)),
                                  _healPoint.ToScreenAbsolute().ToRectangle((int)distance, (int)distance));

                    g.FillEllipse(new SolidBrush(Color.FromArgb(128, Color.Magenta)),
                                  _ragePoint.ToScreenAbsolute().ToRectangle((int)distance, (int)distance));

                    g.FillEllipse(new SolidBrush(Color.FromArgb(128, Color.Magenta)),
                                  _queenRagePoint.ToScreenAbsolute().ToRectangle((int)distance, (int)distance));
                }
                var d = DateTime.UtcNow;
                Screenshot.Save(bmp, $"Breakthrough Deploy {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
            }
        }
Exemplo n.º 4
0
        public static void decision(int menuPosition)
        {
            switch (menuPosition)
            {
            case 0:
            {
                Visualize.Creature();
            }
            break;

            case 1:
            {
                Console.WriteLine("Типо справка, а так идите нахер я вас не звал");
                while (true)
                {
                    if (Console.ReadKey().Key == ConsoleKey.Escape)
                    {
                        return;
                    }
                }
            }

            case 2: return;

            default: return;
            }
        }
        /// <summary>
        /// Tests to see whether or not we can easily reach the town hall to snipe it or not.
        /// </summary>
        /// <param name="townHall"></param>
        /// <returns></returns>
        public static bool CanSnipe(this TownHall townHall)
        {
            if (townHall != null)
            {
                Target target = townHall.GetTownHallPoints();

                Log.Debug($"[Berts Agorithms] Town Hall Center Location: X:{target.Center.X} Y:{target.Center.Y}");
                Log.Debug($"[Berts Agorithms] Town Hall Outer Edge Location: X:{target.Edge.X} Y:{target.Edge.Y}");
                Log.Debug($"[Berts Agorithms] DistanceSq from Town Hall to closest outer red point: {target.EdgeToRedline.ToString("F1")}");

#if DEBUG
                //Get a screen Capture...
                using (Bitmap canvas = Screenshot.Capture())
                {
                    //Draw some stuff on it.
                    Visualize.Target(canvas, Origin, 40, Color.White);
                    Visualize.Target(canvas, target.Center, 40, Color.Orange);
                    Visualize.Target(canvas, target.Edge, 40, Color.Red);

                    //Save the Image to the Debug Folder...
                    var d = DateTime.UtcNow;
                    Screenshot.Save(canvas, $"CanSnipe TownHall {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
                }
                Log.Debug("[Berts Algorithms] Snipe Townhall Debug Image Saved!");
#endif

                if (target.EdgeToRedline < _townHallToRedZoneMinDistance)  // means there is no wall or building between us and the OUTSIDE of the Town Hall
                {
                    return(true);
                }
            }

            return(false);
        }
        private void VisualizeDeployPoints()
        {
            var clockwisePoints = GameGrid.RedPoints.OrderBy(point => Math.Atan2(point.X, point.Y)).ToList();
            var inflatedPoints  =
                clockwisePoints.Select(
                    point =>
                    new PointFT((float)(point.X + (point.X / Math.Sqrt(point.DistanceSq(new PointFT(0, 0)))) * 4),
                                (float)(point.Y + (point.Y / Math.Sqrt(point.DistanceSq(new PointFT(0, 0)))) * 4)))
                .ToList();

            using (Bitmap bmp = Screenshot.Capture())
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    foreach (PointFT redPoint in clockwisePoints)
                    {
                        Visualize.RectangleT(bmp, new RectangleT((int)redPoint.X, (int)redPoint.Y, 1, 1), new Pen(Color.FromArgb(128, Color.DarkRed)));
                    }

                    foreach (PointFT redPoint in inflatedPoints)
                    {
                        Visualize.RectangleT(bmp, new RectangleT((int)redPoint.X, (int)redPoint.Y, 1, 1), new Pen(Color.FromArgb(128, Color.DarkBlue)));
                    }
                }
                var d = DateTime.UtcNow;
                Screenshot.Save(bmp,
                                $"RedLineDeploy {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
            }
        }
Exemplo n.º 7
0
        private bool LoadStlFile(string filename)
        {
            this.stl_file = filename;

            if (!File.Exists(filename))
            {
                pictureBox1.Image = null;
                return(false);
            }

            int w    = 2400;
            int h    = 1600;
            int xdiv = 12;
            int ydiv = 8;

            //slice
            Stopwatch sw   = Stopwatch.StartNew();
            Mesh      mesh = new Mesh(filename);

            Console.WriteLine("load stl: {0} ms", sw.ElapsedMilliseconds); sw.Restart();
            mesh.ShiftCenter();
            mesh.Scale(appset.stl_scale);
            Console.WriteLine("shift/scale stl: {0} ms", sw.ElapsedMilliseconds); sw.Restart();
            //float zstep = (mesh.zmax - mesh.zmin) / (xdiv * ydiv);
            float zstep = appset.zstep;

            slices = new Slices(mesh, zstep, appset.slice_tol, appset.z_angle * (float)Math.PI / 180f);
            Console.WriteLine("total slicing: {0} ms", sw.ElapsedMilliseconds); sw.Restart();

            //visualize
            Visualize vis = new Visualize(w, h);

            pictureBox1.Image = vis.show_Slices(slices, xdiv, ydiv);
            Console.WriteLine("visualize: {0} ms", sw.ElapsedMilliseconds); sw.Restart();

            //gcode
            gcode                  = new Gcode();
            gcode.ZStep            = appset.zstep;
            gcode.header           = appset.gcode_header;
            gcode.footer           = appset.gcode_footer;
            gcode.WallThickness    = appset.WallThickness;
            gcode.FilamentDiameter = appset.FilamentDiameter;
            gcode.PrintSpeed       = appset.PrintSpeed;
            gcode.PrintPerimeter   = appset.PrintPerimeter;
            gcode.Append(slices);
            Console.WriteLine("gcode: {0} ms", sw.ElapsedMilliseconds); sw.Restart();

            //show info
            txtInfo.Text =
                gcode.info().Replace(";", "").Replace("\n", "\r\n") +
                mesh.ToString() + "\r\n" +
                string.Format("Mesh Facets    {0:0.}\r\n", mesh.Facets.Length) +
                string.Format("Layers         {0:0.}\r\n", slices.slices.Count) +
                string.Format("Line Segments  {0:0.}\r\n", slices.LineSegmentCount());

            //clear settings isdirty flag
            appset.IsDirtyClearFlag();
            return(true);
        }
Exemplo n.º 8
0
        public override IEnumerable <int> AttackRoutine()
        {
            // Bottom right side
            var rightBottom = new PointFT((float)GameGrid.MaxX - 2, (float)GameGrid.DeployExtents.MinY);
            var bottomRight = new PointFT((float)GameGrid.MinX + 8, (float)GameGrid.DeployExtents.MinY);

            var center = new PointFT(bottomRight.X + 0.5f * (rightBottom.X - bottomRight.X),
                                     bottomRight.Y + 0.5f * (rightBottom.Y - bottomRight.Y));

            // Screenshot for 3 points for the deployment line
            using (var bmp = Screenshot.Capture())
            {
                using (var g = Graphics.FromImage(bmp))
                {
                    Visualize.RectangleT(bmp, new RectangleT((int)rightBottom.X, (int)rightBottom.Y, 1, 1), new Pen(Color.Blue));
                    Visualize.RectangleT(bmp, new RectangleT((int)bottomRight.X, (int)bottomRight.Y, 1, 1), new Pen(Color.Blue));

                    Visualize.RectangleT(bmp, new RectangleT((int)center.X, (int)center.Y, 1, 1), new Pen(Color.White));
                }
                var d = DateTime.UtcNow;
                Screenshot.Save(bmp, "Bottom Right {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
            }

            // Deploy troops
            var units = Deploy.GetTroops();

            units.OrderForDeploy();
            for (var i = 3; i >= 1; i--)
            {
                switch (i)
                {
                case 3:
                    point = rightBottom;
                    break;

                case 2:
                    point = bottomRight;
                    break;

                case 1:
                    point = center;
                    break;
                }

                foreach (var unit in units)
                {
                    if (unit?.Count > 0)
                    {
                        foreach (var t in Deploy.AtPoint(unit, point, unit.Count / i))
                        {
                            yield return(t);
                        }
                    }
                }
            }
        }
        private static void VisualizeTownhall()
        {
            var th = TownHall.Find();

            using (var bmp = Screenshot.Capture())
            {
                Visualize.Grid(bmp);
                Visualize.Axes(bmp);
                Visualize.RectangleT(bmp, th.Location);
                Screenshot.Show(bmp);
            }
        }
Exemplo n.º 10
0
        public void FinishAndProcess()
        {
            try
            {
                var priceData = new DenseMatrix(symbols.Length, numTicks);

                for (int j = 0; j < symbols.Length; j++)
                {
                    SortedList <DateTime, Tick> d = mktData[j].data.Data;
                    for (int k = 0; k < d.Count; k++)
                    {
                        priceData[j, k] = d.Values[k].BidClose;
                    }
                }

                for (int i = 0; i < symbols.Length; i++)
                {
                    for (int j = 0; j < symbols.Length; j++)
                    {
                        double[] pDatai = priceData.Row(i).ToArray();
                        double[] pDataj = priceData.Row(j).ToArray();

                        switch (cType)
                        {
                        case CovarianceType.LogReturn:
                        {
                            pDatai = priceData.Row(i).ToArray().LogRateOfReturn();
                            pDataj = priceData.Row(j).ToArray().LogRateOfReturn();
                            break;
                        }

                        case CovarianceType.RawReturn:
                        {
                            pDatai = priceData.Row(i).ToArray().RawRateOfReturn();
                            pDataj = priceData.Row(j).ToArray().RawRateOfReturn();
                            break;
                        }
                        }
                        correlation[i, j] = StatisticsExtension.Correlation(pDatai, pDataj);
                        covariance[i, j]  = StatisticsExtension.Covariance((DenseVector)priceData.Row(i),
                                                                           (DenseVector)priceData.Row(j));
                    }
                }

                Visualize.GenerateHeatMatrix(symbols, correlation, "C:\\Users\\Ethan\\Work\\QuantSysdata.html");
                Console.WriteLine("Finished Generating Correlation Matrix.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 11
0
        private void Visualize_Load(object sender, EventArgs e)
        {
            //Compute object position and dimension
            Dimension_Xp = (float)Visualize_Size.X / 2;
            Dimension_Yp = (float)Visualize_Size.Y / 2;
            Dimension_Zp = (float)Visualize_Size.Z / 2;
            Dimension_Xn = (float)-Visualize_Size.X / 2;
            Dimension_Yn = (float)-Visualize_Size.Y / 2;
            Dimension_Zn = (float)-Visualize_Size.Z / 2;

            //init transformation matrix
            Matrix = new float[] { 1.0f, 0.0f, 0.0f, 0.0f,
                                   0.0f, 1.0f, 0.0f, 0.0f,
                                   0.0f, 0.0f, 1.0f, 0.0f,
                                   0.0f, 0.0f, 0.0f, 1.0f };

            //File path
            string[] imageFiles = new string[] {
                "image/Xplus.png",
                "image/Xminus.png",
                "image/Yplus.png",
                "image/Yminus.png",
                "image/Zplus.png",
                "image/Zminus.png"
            };

            //Config Gl control
            Visualize.InitializeContexts();
            Visualize.SwapBuffers();
            Visualize_SizeChanged(sender, e);
            Gl.glShadeModel(Gl.GL_SMOOTH);
            Gl.glEnable(Gl.GL_LINE_SMOOTH);
            Gl.glEnable(Gl.GL_TEXTURE_2D);                                                  // Enable Texture Mapping
            Gl.glEnable(Gl.GL_NORMALIZE);
            Gl.glEnable(Gl.GL_COLOR_MATERIAL);
            Gl.glEnable(Gl.GL_DEPTH_TEST);                                                  // Enables Depth Testing
            Gl.glEnable(Gl.GL_BLEND);
            Gl.glEnable(Gl.GL_LIGHTING);
            Gl.glEnable(Gl.GL_LIGHT0);
            Gl.glHint(Gl.GL_POLYGON_SMOOTH_HINT, Gl.GL_NICEST);     // Really Nice Point Smoothing
            Gl.glClearColor(0.6f, 0.7f, 0.9f, 0.2f);
            //Load file
            textures = LoadTexture(imageFiles);

            //Setup timer
            Timer          = new Timer();
            Timer.Interval = 20;
            Timer.Tick    += new EventHandler(GraphicTimer_Tick);
            Timer.Start();
        }
Exemplo n.º 12
0
    // upon editor visualization: //
    private void OnDrawGizmos()
    {
        if (!raycastingController && UnityIs.inEditorEditMode)
        {
            raycastingController = Controller.left;
        }

        if (raycastingController)
        {
            Visualize.localLineFrom(raycastingController, localDirection, distance,
                                    visualizeLine,
                                    visualizationColor);
        }
    }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            var baseNum       = BaseConstants.Octal;
            var decimalNumber = 1002652783;

            var converter  = new ConvertNumber();
            var visualizer = new Visualize();

            var convertedNumber = converter.ConvertFromDecimalToBase_Complex((ulong)decimalNumber, baseNum);

            visualizer.ViewElaboredTable(convertedNumber);

            Console.ReadKey();
        }
Exemplo n.º 14
0
    void OnValidate()
    {
        switch (visualizationStyle)
        {
        case VisualizationStyle.None:
            visualize = NoAction;
            break;

        case VisualizationStyle.Bars:
            visualize = VisualizeBars;
            break;

        case VisualizationStyle.Lines:
            visualize = VisualizeLines;
            break;
        }
    }
Exemplo n.º 15
0
        public void FinishAndProcess()
        {
            for (int i = 0; i < symbols.Length; i++)
            {
                SortedList <DateTime, Tick> d = mktData[i].data.Data;

                for (int j = 0; j < numTicks; j++)
                {
                    graphData[i, j] = indicator.HandleNextTick(d.Values[j]);
                }
            }

            Visualize.GenerateMultiSymbolGraph(symbols, graphData, mktData[0].data.Data.Values[0].Time,
                                               DateTimeUtils.TimeFrameToTimeSpan(timeframe), "C:\\Users\\Ethan\\Work\\QuantSysdata.html");

            Console.WriteLine("Done Processing symbol set.");
        }
Exemplo n.º 16
0
 public static void DebugBottomRightSidePoints()
 {
     using (var bmp = Screenshot.Capture())
     {
         using (var g = Graphics.FromImage(bmp))
         {
             var y = GameGrid.DeployExtents.MinY;
             var x = 18;
             while (x >= -15)
             {
                 Visualize.RectangleT(bmp, new RectangleT(x, y, 1, 1), new Pen(Color.Blue));
                 x--;
             }
         }
         var d = DateTime.UtcNow;
         Screenshot.Save(bmp, $"BottomRightPoints {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
     }
 }
Exemplo n.º 17
0
    void Start()
    {
        aud     = GetComponent <AudioSource>();
        samples = new float[sampleCount];
        switch (visualizationStyle)
        {
        case VisualizationStyle.None:
            visualize = NoAction;
            break;

        case VisualizationStyle.Bars:
            visualize = VisualizeBars;
            break;

        case VisualizationStyle.Lines:
            visualize = VisualizeLines;
            break;
        }
        InitializeBars();
    }
Exemplo n.º 18
0
        public static void DebugSpells()
        {
            using (var bmp = Screenshot.Capture())
            {
                using (var g = Graphics.FromImage(bmp))
                {
                    g.DrawLine(new Pen(Color.FromArgb(192, Color.Orange)), AllInOnePushDeploy.FirstHasteLine.Item1.ToScreenAbsolute(), AllInOnePushDeploy.FirstHasteLine.Item2.ToScreenAbsolute());
                    g.DrawLine(new Pen(Color.FromArgb(192, Color.Orange)), AllInOnePushDeploy.FirstRageLine.Item1.ToScreenAbsolute(), AllInOnePushDeploy.FirstRageLine.Item2.ToScreenAbsolute());
                    g.DrawLine(new Pen(Color.FromArgb(192, Color.Orange)), AllInOnePushDeploy.SecondHasteLine.Item1.ToScreenAbsolute(), AllInOnePushDeploy.SecondHasteLine.Item2.ToScreenAbsolute());


                    Visualize.CircleT(bmp, AllInOnePushDeploy.FirstRagePoint, 5, Color.Magenta, 64, 0);
                    Visualize.CircleT(bmp, AllInOnePushDeploy.SecondRagePoint, 5, Color.Magenta, 64, 0);
                    Visualize.CircleT(bmp, AllInOnePushDeploy.FirstHealPoint, 5, Color.Yellow, 64, 0);
                    Visualize.CircleT(bmp, AllInOnePushDeploy.FirstHastePoint, 5, Color.OrangeRed, 64, 0);
                }
                var d = DateTime.UtcNow;
                Screenshot.Save(bmp, $"{AllInOnePushDeploy.AttackName} Spells {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
            }
        }
Exemplo n.º 19
0
        public void Predict()
        {
            double error = 0;
            int    c     = 0;

            var d     = new DenseMatrix(2, _normalizedPredictionData.Length - WindowSize);
            int count = 0;

            for (int i = WindowSize; i < _normalizedPredictionData.Length; i++)
            {
                // calculate based on actual data
                IMLData input = new BasicMLData(WindowSize);
                for (int j = 0; j < input.Count; j++)
                {
                    input.Data[j] = _normalizedPredictionData[(i - WindowSize) + j];
                }

                IMLData output     = network.Compute(input);
                double  prediction = output.Data[0];


                error += Math.Pow((normalizeArray.Stats.DeNormalize(prediction) - predictionData[i]) / predictionData[i],
                                  2);
                c++;
                d[0, count] = predictionData[i];
                d[1, count] = normalizeArray.Stats.DeNormalize(prediction);
                count++;
            }

            error /= c;
            error  = Math.Pow(error, .5);
            Console.WriteLine(error);

            OutputData = d.Row(1).ToArray();

            string[] symbols = { "actual", "predicted" };
            Visualize.GeneratePredictionGraph(symbols, d, new DateTime(), new TimeSpan(24, 0, 0),
                                              QSConstants.DEFAULT_DATA_FILEPATH + write + ".html");
        }
Exemplo n.º 20
0
        public void Predict()
        {
            double error = 0;
            int    c     = 0;

            var d     = new DenseMatrix(2, _normalizedPredictionData.Length);
            int count = 0;

            for (int i = 0; i < _normalizedPredictionData.Length; i++)
            {
                // calculate based on actual data
                IMLData input = new BasicMLData(inputs);
                for (int j = 0; j < input.Count; j++)
                {
                    input.Data[j] = _normalizedTrainingData[j, i];
                }

                IMLData output     = network.Compute(input);
                double  prediction = output.Data[0];


                error +=
                    Math.Pow(
                        (normalizeArrayOutput.Stats.DeNormalize(prediction) - predictionData[i]) / predictionData[i], 2);
                c++;
                d[0, count] = predictionData[i];
                d[1, count] = normalizeArrayOutput.Stats.DeNormalize(prediction);
                count++;
            }

            error /= c;
            error  = Math.Pow(error, .5);
            Console.WriteLine(error);

            string[] symbols = { "actual", "predicted" };
            Visualize.GeneratePredictionGraph(symbols, d, new DateTime(), new TimeSpan(24, 0, 0),
                                              "C:\\Sangar\\resultfinal.html");
        }
Exemplo n.º 21
0
        public static void DebugEQpells()
        {
            using (var bmp = Screenshot.Capture())
            {
                using (var g = Graphics.FromImage(bmp))
                {
                    Visualize.RectangleT(bmp, new RectangleT((int)AllInOnePushDeploy.FirstFunnellingPoint.X, (int)AllInOnePushDeploy.FirstFunnellingPoint.Y, 1, 1), new Pen(Color.Blue));
                    Visualize.RectangleT(bmp, new RectangleT((int)AllInOnePushDeploy.SecondFunnellingPoint.X, (int)AllInOnePushDeploy.SecondFunnellingPoint.Y, 1, 1), new Pen(Color.Blue));

                    Visualize.RectangleT(bmp, new RectangleT((int)AllInOnePushDeploy.Origin.X, (int)AllInOnePushDeploy.Origin.Y, 1, 1), new Pen(Color.Red));


                    //draw rectangle around the target
                    Visualize.RectangleT(bmp, new RectangleT((int)AllInOnePushDeploy.Target.X, (int)AllInOnePushDeploy.Target.Y, 3, 3), new Pen(Color.Blue));

                    Visualize.CircleT(bmp, AllInOnePushDeploy.FirstJumpPoint, 3.5f, Color.DarkGreen, 100, 0);


                    Visualize.CircleT(bmp, AllInOnePushDeploy.EqPoint, 4, Color.SandyBrown, 100, 0);
                }
                var d = DateTime.UtcNow;
                Screenshot.Save(bmp, $"{AllInOnePushDeploy.AttackName} EQ Spells {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
            }
        }
        public override IEnumerable <int> AttackRoutine()
        {
            Log.Debug("[Snipe Deploy] Getting the best townhall deploy point.");
            var snipePoint = new Container <PointFT> {
                Item = GetTownHallDeployPoint()
            };

            Log.Debug($"[Snipe Deploy] Deploy point is ({snipePoint.Item})");

            var troops = Deploy.GetTroops();

            var hero = troops.GetQueen() ?? troops.GetKing() ?? troops.GetWarden();

            if (hero != null)
            {
                Log.Info("[Snipe Deploy] Deploying the " + hero.PrettyName + " to snipe.");
                foreach (var t in Deploy.AtPoint(hero, snipePoint))
                {
                    yield return(t);
                }

                hero.Recount();

                if (hero.Count > 0)
                {
                    var th = TownHall.Find();

                    using (var bmp = Screenshot.Capture(true))
                    {
                        Visualize.RectangleT(bmp, th.Location);
                        Visualize.RectangleT(bmp, new RectangleT((int)snipePoint.Item.X, (int)snipePoint.Item.Y, 1, 1));
                        var d = DateTime.UtcNow;
                        Screenshot.Save(bmp, $"Snipe Deploy_{d.Year}-{d.Month}-{d.Day}_{d.Hour}-{d.Minute}-{d.Second}");
                    }
                }

                yield return(5000);

                Deploy.WatchHeroes(new List <DeployElement> {
                    hero
                });

                var countdown = new Countdown(15.0);

                if (hero.Count < 1)
                {
                    while (countdown.IsRunning)
                    {
                        if (Attack.SurrenderIfWeHaveAStar())
                        {
                            yield break;
                        }
                        else
                        {
                            yield return(200);
                        }
                    }
                }
                else
                {
                    Log.Info("[Snipe Deploy] Hero failed to deploy; trying to use troops");
                }
            }

            var snipeTroops =
                troops.GetByAttackType(AttackType.Damage)
                .GetByType(DeployElementType.NormalUnit)
                .Where(u => u.UnitData?.TargetType == TargetType.Loot || u.UnitData?.TargetType == TargetType.None)
                .ToArray();

            if (snipeTroops.Length > 0)
            {
                Log.Info("[Snipe Deploy] Deploying troops to snipe.");

                var countdown = new Countdown(15.0, true);
                var pt        = new Container <PointFT> {
                    Item = GetTownHallDeployPoint()
                };
                while (true)
                {
                    if (countdown.IsFinished)
                    {
                        foreach (var t in Deploy.AtPoint(snipeTroops, snipePoint))
                        {
                            yield return(t);
                        }

                        snipeTroops.Recount();

                        if (snipeTroops.All(u => u.Count < 1))
                        {
                            yield break;
                        }

                        countdown.Restart();
                    }

                    if (Attack.SurrenderIfWeHaveAStar())
                    {
                        yield break;
                    }
                }
            }
        }
        /// <summary>
        /// Check to see how many collector and mine near to the redline by user defined distance
        /// </summary>
        /// <param name="userDistance">Minimum distance for exposed colloctors and mines</param>
        /// <param name="minCollectors">minimum exposed collectors</param>
        /// <param name="minMines">minimum exposed mines</param>
        /// <param name="AttackName">Attack name for logs and debugging</param>
        /// <param name="debug">debug mode in advanced settings</param>
        /// <returns>true if matches user defined min collectores and mines</returns>
        public static bool IsBaseMinCollectorsAndMinesOutside(int userDistance, int minCollectors, int minMines, string AttackName, int debug)
        {
            var distance = userDistance * userDistance;

            var redPoints = GameGrid.RedPoints.Where(
                point =>
                !(point.X > 18 && point.Y > 18 || point.X > 18 && point.Y < -18 || point.X < -18 && point.Y > 18 ||
                  point.X < -18 && point.Y < -18));

            collectors = ElixirCollector.Find().Where(c => c.Location.GetCenter()
                                                      .DistanceSq(redPoints.OrderBy(p => p.DistanceSq(c.Location.GetCenter()))
                                                                  .FirstOrDefault()) <= distance);

            mines = GoldMine.Find().Where(c => c.Location.GetCenter()
                                          .DistanceSq(redPoints.OrderBy(p => p.DistanceSq(c.Location.GetCenter()))
                                                      .FirstOrDefault()) <= distance);

            drills = DarkElixirDrill.Find().Where(c => c.Location.GetCenter()
                                                  .DistanceSq(redPoints.OrderBy(p => p.DistanceSq(c.Location.GetCenter()))
                                                              .FirstOrDefault()) <= distance);

            int collectorsCount = collectors != null?collectors.Count() : 0;

            int minesCount = mines != null?mines.Count() : 0;

            int drillsCount = drills != null?drills.Count() : 0;

            // Set total count of targets
            SmartFourFingersDeploy.TotalTargetsCount = collectorsCount + minesCount + drillsCount;

            // four corners
            var top    = new PointFT((float)GameGrid.DeployExtents.MaxX + 1, GameGrid.DeployExtents.MaxY + 4);
            var right  = new PointFT((float)GameGrid.DeployExtents.MaxX + 1, GameGrid.DeployExtents.MinY - 4);
            var bottom = new PointFT((float)GameGrid.DeployExtents.MinX - 1, GameGrid.DeployExtents.MinY - 4);
            var left   = new PointFT((float)GameGrid.DeployExtents.MinX - 1, GameGrid.DeployExtents.MaxY + 4);

            SetCore();

            var corners = new List <Tuple <PointFT, PointFT> >
            {
                new Tuple <PointFT, PointFT>(top, right),
                new Tuple <PointFT, PointFT>(bottom, right),
                new Tuple <PointFT, PointFT>(bottom, left),
                new Tuple <PointFT, PointFT>(top, left)
            };

            // loop throw the 4 sides and count targets on each side
            var targetsAtLine = new List <int>();

            foreach (var l in corners)
            {
                var colCount = collectors.Where(t => t.Location.GetCenter().
                                                IsInTri(SmartFourFingersDeploy.Core, l.Item1, l.Item2))?.Count() ?? 0;
                var minCount = mines.Where(t => t.Location.GetCenter().
                                           IsInTri(SmartFourFingersDeploy.Core, l.Item1, l.Item2))?.Count() ?? 0;
                var drillCount = drills.Where(t => t.Location.GetCenter().
                                              IsInTri(SmartFourFingersDeploy.Core, l.Item1, l.Item2))?.Count() ?? 0;
                var total = colCount + minCount + drillCount;

                targetsAtLine.Add(total);
            }

            SmartFourFingersDeploy.TargetsAtLine = targetsAtLine;

            var op = new Opponent(0);

            //if (!op.IsForcedAttack )
            {
                Log.Info($"{AttackName} NO. of Colloctors & mines near from red line:");
                Log.Info($"elixir colloctors is {collectorsCount}");
                Log.Info($"gold mines is {minesCount}");
                Log.Info($"----------------------------");
                Log.Info($"sum of all is {collectorsCount + minesCount}");

                if (debug == 1)
                {
                    using (Bitmap bmp = Screenshot.Capture())
                    {
                        using (Graphics g = Graphics.FromImage(bmp))
                        {
                            foreach (var c in collectors)
                            {
                                var point = c.Location.GetCenter();
                                Visualize.Target(bmp, point, 30, Color.Purple);
                            }

                            foreach (var c in mines)
                            {
                                var point = c.Location.GetCenter();
                                Visualize.Target(bmp, point, 30, Color.Gold);
                            }

                            foreach (var c in drills)
                            {
                                var point = c.Location.GetCenter();
                                Visualize.Target(bmp, point, 30, Color.Black);
                            }
                            DrawLine(bmp, Color.Red, SmartFourFingersDeploy.Core, top);
                            DrawLine(bmp, Color.Red, SmartFourFingersDeploy.Core, right);
                            DrawLine(bmp, Color.Red, SmartFourFingersDeploy.Core, bottom);
                            DrawLine(bmp, Color.Red, SmartFourFingersDeploy.Core, left);
                        }
                        var d = DateTime.UtcNow;
                        Screenshot.Save(bmp, "Collectors and Mines {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
                    }
                }
            }
            if (collectorsCount >= minCollectors && minesCount >= minMines)
            {
                return(true);
            }
            else
            {
                Log.Warning($"{AttackName} this base doesn't meets Collocetors & Mines requirements");
                return(false);
            }
        }
Exemplo n.º 24
0
        private static void Main()
        {
            //TestLiveCointegration.Run();

            /*
             * IndicatorMatrix im = new IndicatorMatrix("EUR/USD");
             * im.LoadData();
             * im.Execute();
             */

            //TestIndicator.TestMA(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD15M.xml", 14000, new QSPolyMA(40), new ZLEMA(40));
            //TestIndicator.TestChannelLive(new QSPolyChannel(), "EUR/USD", "m5", 5000 );
            //TestIndicator.TestChannel(new KirshenbaumBands(20), QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD15M.xml", 10000);
            //TestIndicator.TestMA(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", 15000,  new SMA(25), new DWT(25, 5));
            //TestIndicator.TestGraph(new ReversalGenesis(50),  QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", 15000);
            //TestIndicator.TestGraph(new HurstIndicator(256), QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", 15000);
            //TestIndicator.TestGraphLive(new Genesis(30), "m30", "EUR/USD", 10000);
            //TestIndicator.TestGraphLive(new PercentileRank(250, new SMA(200)), "H1", "EUR/USD", 1000);
            //TestIndicator.TestGraphLive(new PercentileRank(250, new SMA(200,new HistoricalVol(50))), "H1", "EUR/USD", 100000);
            //TestIndicator.TestGraphLive(new WilliamsR(), "H1", "EUR/USD", 100000);
            //TestIndicator.TestGraph(new PercentileRank(252, new SMA(251)), QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", 10000);
            Quantum        q1 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", "EUR/USD");
            Quantum        q2 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD1H.xml", "GBP/USD");
            Quantum        q3 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", "AUD/USD");
            List <Quantum> lq = new List <Quantum>();

            lq.Add(q1);
            lq.Add(q2);
            lq.Add(q3);
            MultiQuantum        mq   = MultiQuantum.OrganizeMultiQuantum(lq);
            List <List <Tick> > list = mq.RevertToList();

            double[] dat1 = list[0].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();
            double[] dat2 = list[1].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();
            double[] dat3 = list[2].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();

            DenseVector d11 = new DenseVector(dat1);
            DenseVector d12 = new DenseVector(dat2);
            DenseVector d13 = new DenseVector(dat3);

            DenseVector fe = ((.48 * d11) + (-0.22 * d12) + (-.46 * d13));

            Visualize.GenerateSimpleGraph(fe, "result.html");


            Console.Read();

            Func <Chromosome, double> fitnessFunc = new Func <Chromosome, double>(
                chromosome =>
            {
                double weight1 = ((RealCodedGene)chromosome[0]).GeneValue;
                double weight2 = ((RealCodedGene)chromosome[1]).GeneValue;
                double weight3 = ((RealCodedGene)chromosome[2]).GeneValue;

                double w1mod = weight1 / (weight1 + weight2 + weight3);
                double w2mod = weight2 / (weight1 + weight2 + weight3);
                double w3mod = weight3 / (weight1 + weight2 + weight3);

                DenseVector d1 = new DenseVector(dat1);
                DenseVector d2 = new DenseVector(dat2);
                DenseVector d3 = new DenseVector(dat3);

                double stdev = ((w1mod * d1) + (w2mod * d2) + (w3mod * d3)).StandardDeviation();

                return((stdev > 0) ? (1 / stdev) : 0.000001);
            }
                );

            Random r  = new Random();
            Gene   g1 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x <1.0 && (double)x> -1.0))
            {
                HI = 1.0, LOW = -1.0
            });
            Gene g2 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x <1.0 && (double)x> -1.0))
            {
                HI = 1.0, LOW = -1.0
            });
            Gene g3 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x <1.0 && (double)x> -1.0))
            {
                HI = 1.0, LOW = -1.0
            });
            List <Gene> cfootprint = new List <Gene>();

            cfootprint.Add(g1);
            cfootprint.Add(g2);
            cfootprint.Add(g3);

            GeneticAlgorithm ga = new GeneticAlgorithm(
                fitnessFunc, cfootprint, 30, 200, 10
                );

            ga.Run();

            Console.Read();


            var ba1 = new BacktestEngine(0, 3010, true);

            ba1.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", "EUR/USD");
            ba1.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD1H.xml", "GBP/USD");
            //ba.LoadDataLive("EUR/USD", "m5", 200000);
            //ba.LoadDataLive("GBP/USD", "m5", 20000);
            ba1.OrganizeData();
            ba1.LoadStrategy(new Cointegration());
            ba1.Execute();



            Console.Read();


            object[,] denseMatrix;
            ExcelUtil.Open(QSConstants.DEFAULT_DATA_FILEPATH + @"GBPUSD1H.xml", out denseMatrix);

            var mData = new List <double>();

            var predictor = new AC(60);

            for (int i = denseMatrix.GetLength(0); i > 1; i--)
            {
                DateTime dateTime = (DateTime)denseMatrix[i, 1];
                var      t        = new Tick(
                    0,
                    (double)denseMatrix[i, 6],
                    (double)denseMatrix[i, 7],
                    (double)denseMatrix[i, 8],
                    (double)denseMatrix[i, 9],
                    0,
                    (double)denseMatrix[i, 2],
                    (double)denseMatrix[i, 3],
                    (double)denseMatrix[i, 4],
                    (double)denseMatrix[i, 5],
                    (double)denseMatrix[i, 10],
                    dateTime
                    );

                double d = predictor.HandleNextTick(t);
                if (!d.Equals(double.NaN))
                {
                    mData.Add(d);
                }
            }

            int windowSize     = 5;
            int iterations     = 10000;
            int trainLength    = 5000;
            int validateLength = 1000;

            double[] trainData    = mData.ToArray().Take(trainLength).ToArray();
            double[] validateData = mData.ToArray().Skip(trainLength).ToArray().Take(validateLength).ToArray();

            Stage1NeuralNetwork nn = new Stage1NeuralNetwork(windowSize, iterations, trainData, validateData);

            nn.Execute(1);

            NeuralNetworkStrategy nns = new NeuralNetworkStrategy(windowSize)
            {
                NeuralNetwork = nn
            };

            var ba = new BacktestEngine(5000, 9200, true);

            //ba.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD15M.xml", "EUR/USD");
            ba.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "NZDUSD1H.xml", "GBP/USD");
            //ba.LoadDataLive("EUR/USD", "m5", 200000);
            //ba.LoadDataLive("GBP/USD", "m5", 20000);
            ba.OrganizeData();
            ba.LoadStrategy(nns);
            ba.Execute();


            Console.Read();

            /*
             * Func<Chromosome, double> function = (chromosome =>
             * {
             *  double fitness = 0.001;
             *
             *  ba.ResetAccount();
             *  ba.ResetStrategies();
             *  ba.LoadStrategy(new CustomStrategy(
             *         (int)(double)chromosome[0].GeneValue,
             *         (int)(double)chromosome[1].GeneValue,
             *         (int)(double)chromosome[2].GeneValue,
             *         (int)(double)chromosome[3].GeneValue,
             *         (int)(double)chromosome[4].GeneValue,
             *         (int)(double)chromosome[5].GeneValue,
             *         (int)(double)chromosome[6].GeneValue,
             *         (int)(double)chromosome[7].GeneValue,
             *         (int)(double)chromosome[8].GeneValue
             *      ));
             *  ba.Execute();
             *
             *
             *  fitness += ba.ret;
             *
             *  return (fitness > 0) ? fitness : 0.001;
             * }
             *  );
             *
             * var GA = new GeneticAlgorithm(function,
             *  new List<Gene>
             *  {
             *      new Gene(50, new Gene.Constraint(5,200)),
             *      new Gene(50, new Gene.Constraint(5,200)),
             *      new Gene(50, new Gene.Constraint(5,200)),
             *      new Gene(50, new Gene.Constraint(5,500)),
             *      new Gene(50, new Gene.Constraint(1,100)),
             *      new Gene(50, new Gene.Constraint(1,100)),
             *      new Gene(50, new Gene.Constraint(5,500)),
             *      new Gene(50, new Gene.Constraint(5,500)),
             *      new Gene(50, new Gene.Constraint(1,100))
             *  }) { Generations = 1000, Trials = 10 }
             *  ;
             *
             * GA.InitializePopulation();
             * GA.Run();
             *
             * Console.Read();
             */



            /*
             * object[,] denseMatrix;
             * ExcelUtil.Open(Constants.DEFAULT_DATA_FILEPATH + @"EURUSD1H.xml", out denseMatrix);
             *
             * var mData = new List<double>();
             *
             * var predictor = new RSI(40);
             *
             * for (int i = denseMatrix.GetLength(0); i > 1; i--)
             * {
             *  DateTime dateTime = (DateTime) denseMatrix[i, 1];
             *  var t = new Tick(
             *          0,
             *          (double) denseMatrix[i, 6],
             *          (double) denseMatrix[i, 7],
             *          (double) denseMatrix[i, 8],
             *          (double) denseMatrix[i, 9],
             *          0,
             *          (double) denseMatrix[i, 2],
             *          (double) denseMatrix[i, 3],
             *          (double) denseMatrix[i, 4],
             *          (double) denseMatrix[i, 5],
             *          (double) denseMatrix[i, 10],
             *          dateTime
             *          );
             *
             *  double d = predictor.HandleNextTick(t);
             *  if (!d.Equals(double.NaN))
             *      mData.Add(d);
             * }
             *
             * int windowSize = 5;
             * int iterations = 5000;
             * int trainLength = 5000;
             * int validateLength = 1000;
             * double[] trainData = mData.ToArray().Take(trainLength).ToArray();
             * double[] validateData = mData.ToArray().Skip(trainLength).ToArray().Take(validateLength).ToArray();
             *
             * Stage1NeuralNetwork nn = new Stage1NeuralNetwork(windowSize, iterations, trainData, validateData);
             * nn.Execute(1);
             *
             * NeuralNetworkStrategy nns = new NeuralNetworkStrategy(windowSize){NeuralNetwork = nn};
             */

            /*
             * bool seao = true;
             * if (seao)
             * {
             *
             *  var ba = new BacktestEngine(0, 50000, true);
             *  ba.LoadDataLive("EUR/USD", "m30", 80000);
             *
             *  //ba.LoadStrategy(nns);
             *  ba.LoadStrategy(new RSIEntry(50){LongEntry = 60, ShortEntry = 40});
             *  ba.LoadStrategy(new RSIExit(50){ LongExit = 70, ShortExit = 30 });
             *
             *  //ba.LoadStrategy(new Pyramid(.1, .05, .001));
             *  ba.Execute();
             *
             *  Console.Read();
             * }
             *
             * BacktestEngine[] barray = new BacktestEngine[2];
             *
             * Func<Chromosome, double> function = (chromosome =>
             * {
             *  double fitness = 0.001;
             *  foreach (BacktestEngine bx in barray)
             *  {
             *      bx.ResetAccount();
             *      bx.ResetStrategies();
             *      bx.LoadStrategy(new CustomStrategy());
             *      bx.LoadStrategy(new Pyramid((double) chromosome[0].GeneValue,
             *          (double) chromosome[1].GeneValue,
             *          (double) chromosome[2].GeneValue));
             *      bx.Execute();
             *
             *      if (bx.ret > 100)
             *          fitness += 100;
             *      else
             *          fitness += bx.ret;
             *  }
             *
             *  return (fitness > 0) ? fitness/5 : 0.001;
             * }
             *  );
             *
             * var GA = new GeneticAlgorithm(function,
             *  new List<Gene>
             *  {
             *      new Gene(5, new Gene.Constraint(0,1.0)),
             *      new Gene(5, new Gene.Constraint(0,1.0)),
             *      new Gene(5, new Gene.Constraint(0,1.0/100.0))
             *  }) {Generations = 1000, Trials = 1}
             *  ;
             *
             * GA.InitializePopulation();
             * GA.Run();
             *
             * Console.Read();
             *
             * /*
             * b.Output = true;
             * b.ResetAccount();
             * b.ResetStrategies();
             * b.LoadStrategy(new RSIEntry()
             * {
             *  EntryTarget1 = (double)GA.maxC[0].GeneValue,
             *  EntryTarget2 = (double)GA.maxC[1].GeneValue
             * });
             * b.LoadStrategy(new RSIExit()
             * {
             *  ExitTarget1 = (double)GA.maxC[2].GeneValue,
             *  ExitTarget2 = (double)GA.maxC[3].GeneValue
             * });
             *
             *
             * b.Execute();
             */
            //Console.Read();


            //object[,] data;

            /*
             * ExcelUtil.Open("C:\\Users\\EL65628\\Work\\QuantSys\\data\\UCUM.xls", out data);
             * DenseMatrix d = ExcelUtil.ToMatrix(data, 2, 1283, 1, 2, true);
             *
             * DenseVector normchf = Statistics.NormalizeZScore(d.Column(0).ToArray());
             * DenseVector normmxn = Statistics.NormalizeZScore(d.Column(1).ToArray());
             *
             * DenseVector kurtmxn = new DenseVector(Statistics.AggregateWindow(d.Column(1).ToArray(),
             *  Statistics.Kurtosis, 50, false, false));
             *
             * DenseVector corre = new DenseVector((Statistics.AggregateWindow(
             *  Statistics.RawRateOfReturn(d.Column(0).ToArray()),
             *  Statistics.RawRateOfReturn(d.Column(1).ToArray()),
             *  Statistics.Correlation,
             *  80, false, true)));
             *
             * //DenseMatrix dNew = new DenseMatrix(3, 1282);
             * //dNew.SetRow(0, (DenseVector)d.Column(0).Normalize(100));
             * //dNew.SetRow(1, (DenseVector)d.Column(1).Normalize(100));
             * //dNew.SetRow(2, corre);
             *
             * Visualize.GenerateGraph(corre, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\correlation.html");
             * Visualize.GenerateGraph(kurtmxn, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\kurtosis.html");
             * //Visualize.GenerateGraph(normmxn, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff2.html");
             * Visualize.GenerateGraph((DenseVector)(Statistics.NormalizeZScore((-1.5 * normmxn + .9 * normchf).ToArray())), "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff3.html");
             *
             * string[] symbols = { "usd/chf", "usd/mxn" ,"correlation"};
             * //Visualize.GenerateMultiSymbolGraph(symbols, dNew, new DateTime(), new TimeSpan(1, 0, 0), "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff.html");
             *
             *
             * int[] vectors = { 5, 3, 2, 4, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 };
             *
             * string vecstring = "1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 1 1 0 0 0 1 0 0 0 0 1 1 1 1 0 0 0 1 1 0";
             *
             *
             * string[] vectemp = vecstring.Split(' ');
             * List<int> vec = new List<int>();
             *
             * for (int i = 0; i < vectors.Length; i++)
             * {
             *  if (vectemp[i]=="1") vec.Add(vectors[i]);
             * }
             *
             * //int[] vect = {13, 19, 25, 27 };
             * int[] vect = { 17, 18, 22, 27, 40, 49};
             *
             * ExcelUtil.Open("C:\\Users\\EL65628\\Work\\QuantSys\\data\\EURUSD1D.xml", out data);
             * TwoStageNN twoStageNn = new TwoStageNN(50, 200, data, vect);
             * twoStageNn.Execute();
             *
             *
             * //GeneticAlgorithm g = new GeneticAlgorithm();
             * //g.Run();
             *
             * Console.ReadLine();
             *
             * PortfolioOptimizer.Run();
             */

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            string[] currencies =
            {
                "EUR/USD",
                "GBP/USD",
                "USD/CAD",
                "USD/CHF",
                "AUD/USD",
                "NZD/USD",
                "USD/JPY",
                "USD/MXN",
                "USD/ZAR",
                "USD/PLN",
                "USD/TRY",
                "USD/DKK",
                "USD/SEK",
                "USD/NOK"
            };

            var currencypairs = new List <string[]>();


            for (int i = 0; i < currencies.Length; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    if (currencies[i] != currencies[j])
                    {
                        string[] temp = { currencies[i], currencies[j] };
                        currencypairs.Add(temp);
                        Console.WriteLine(currencies[i] + " " + currencies[j]);
                    }
                }
            }


            /////////////////////////////////////////////////////////

            /*
             * FXSession fxsession1 = new FXSession();
             *
             * string[] tempgroup = { "AUD/USD", "NZD/USD" };
             *
             * Thread oThread1 = new Thread(new ThreadStart(fxsession1.InitializeSession));
             * oThread1.Start();
             *
             * while (fxsession1.LoginStatus.Equals(FXSession.LOGIN_STATUS.NOT_LOGGED_IN))
             * {
             *  Thread.Sleep(1000);
             *  Console.Write(".");
             * }
             *
             * if (fxsession1.LoginStatus.Equals(FXSession.LOGIN_STATUS.LOGGED_IN))
             * {
             *  //Job_SymbolSet job = new Job_SymbolSet(ex, "H1", 150, new EMA(14));
             *  //Job_CorrelationMatrix job = new Job_CorrelationMatrix(currencies, "D1", 300, Job_CorrelationMatrix.CovarianceType.RawReturn);
             *
             *  Job_Cointegration job = new Job_Cointegration(tempgroup, "m30", 300);
             *      fxsession1.PlaceJob(job);
             *      job.RunJob(fxsession1);
             *      Thread.Sleep(1000);
             * }
             *
             * Console.ReadLine();
             *
             */
            //////////////////////////////////////////////////////////////////

            while (true)
            {
                try
                {
                    var fxsession = new FXSession();


                    var oThread = new Thread(fxsession.InitializeSession);
                    oThread.Start();

                    while (!fxsession.LoggedIn)
                    {
                        Thread.Sleep(1000);
                        Console.Write(".");
                    }

                    if (fxsession.LoggedIn)
                    {
                        //Job_SymbolSet job = new Job_SymbolSet(ex, "H1", 150, new EMA(14));
                        //Job_CorrelationMatrix job = new Job_CorrelationMatrix(currencies, "D1", 300, Job_CorrelationMatrix.CovarianceType.RawReturn);

                        //Job_Cointegration.Process(fxsession, "USD/DKK", "USD/CHF", "m30", 3000);
                        //Console.Read();

                        foreach (var group in currencypairs)
                        {
                            if ((!group[0].Substring(0, 3).Equals("USD") && !group[1].Substring(0, 3).Equals("USD")) ||
                                (group[0].Substring(0, 3).Equals("USD") && group[1].Substring(0, 3).Equals("USD")))
                            {
                                try
                                {
                                    Job_Cointegration.Process(fxsession, group[0], group[1], "m30", 3000);
                                    Thread.Sleep(1000);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                        }
                    }

                    fxsession.EndSession();
                    oThread.Abort();
                }

                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                Console.WriteLine(DateTime.Now.ToString());

                Thread.Sleep(1000 * 60 * 30);
            }

            Console.ReadLine();
        }
        /// <summary>
        /// Check to see how many collector and mine near to the redline by user defined distance
        /// </summary>
        /// <param name="userDistance">Minimum distance for exposed colloctors and mines</param>
        /// <param name="minCollectors">minimum exposed collectors</param>
        /// <param name="minMines">minimum exposed mines</param>
        /// <param name="AttackName">Attack name for logs and debugging</param>
        /// <param name="debug">debug mode in advanced settings</param>
        /// <returns>true if matches user defined min collectores and mines</returns>
        public static bool IsBaseMinCollectorsAndMinesOutside(int userDistance, int minCollectors, int minMines, string AttackName, int debug)
        {
            var distance = userDistance * userDistance;

            var redPoints = GameGrid.RedPoints.Where(
                point =>
                !(point.X > 18 && point.Y > 18 || point.X > 18 && point.Y < -18 || point.X < -18 && point.Y > 18 ||
                  point.X < -18 && point.Y < -18));

            var collectors = ElixirCollector.Find().Where(c => c.Location.GetCenter()
                                                          .DistanceSq(redPoints.OrderBy(p => p.DistanceSq(c.Location.GetCenter()))
                                                                      .FirstOrDefault()) <= distance);

            var mines = GoldMine.Find().Where(c => c.Location.GetCenter()
                                              .DistanceSq(redPoints.OrderBy(p => p.DistanceSq(c.Location.GetCenter()))
                                                          .FirstOrDefault()) <= distance);

            int collectorsCount = collectors != null?collectors.Count() : 0;

            int minesCount = mines != null?mines.Count() : 0;

            Log.Info($"{AttackName} NO. of Colloctors & mines near from red line:");
            Log.Info($"elixir colloctors is {collectorsCount}");
            Log.Info($"gold mines is {minesCount}");
            Log.Info($"----------------------------");
            Log.Info($"sum of all is {collectorsCount + minesCount}");

            if (debug == 1)
            {
                using (Bitmap bmp = Screenshot.Capture())
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        foreach (var c in collectors)
                        {
                            var point = c.Location.GetCenter();
                            Visualize.RectangleT(bmp, new RectangleT((int)point.X, (int)point.Y, 2, 2), new Pen(Color.Blue));
                        }


                        foreach (var c in mines)
                        {
                            var point = c.Location.GetCenter();
                            Visualize.RectangleT(bmp, new RectangleT((int)point.X, (int)point.Y, 2, 2), new Pen(Color.White));
                        }
                    }
                    var d = DateTime.UtcNow;
                    Screenshot.Save(bmp, "Collectors and Mines {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}");
                }
            }

            if (collectorsCount >= minCollectors && minesCount >= minMines)
            {
                return(true);
            }
            else
            {
                Log.Warning($"{AttackName} this base doesn't meets Collocetors & Mines requirements");
                return(false);
            }
        }
Exemplo n.º 26
0
        public static void Process(FXSession session, string symbol1, string symbol2, string timeframe, int length)
        {
            HistoricPriceEngine h1 = new HistoricPriceEngine(session);

            h1.GetLongHistoricPrices(symbol1, timeframe, length);

            while (!h1.Complete)
            {
                Thread.Sleep(100);
            }

            HistoricPriceEngine h2 = new HistoricPriceEngine(session);

            h2.GetLongHistoricPrices(symbol2, timeframe, length);

            while (!h2.Complete)
            {
                Thread.Sleep(100);
            }
            //-----------------------

            var dateTimeList = new SortedList <DateTime, int>();

            Quantum q1 = h1.Data;
            Quantum q2 = h2.Data;


            var priceData = new DenseMatrix(2, q1.Data.Count);

            for (int j = 0; j < ((q1.Data.Count <= q2.Data.Count)?q1.Data.Count:q2.Data.Count); j++)
            {
                dateTimeList.Add(q1.Data.Values[j].Time, 1);
                priceData[0, j] = q1.Data.Values[j].BidClose;
                priceData[1, j] = q2.Data.Values[j].BidClose;
            }

            Vector <double> price1 = priceData.Row(0);
            Vector <double> price2 = priceData.Row(1);
            //Statistics.ApplyFunction((DenseVector)price1, Math.Log);
            //Statistics.ApplyFunction((DenseVector)price2, Math.Log);

            DenseVector norm1 = price1.ToArray().NormalizeZScore();
            DenseVector norm2 = price2.ToArray().NormalizeZScore();

            var newsym = new string[] { symbol1, symbol2, "spread" };

            var m = new DenseMatrix(6, norm1.Count);

            m.SetRow(0, norm1);
            m.SetRow(1, norm2);
            m.SetRow(2, (norm1 - norm2).ToArray().NormalizeZScore());

            string filename = symbol1.Replace('/', '_') + "-" + symbol2.Replace('/', '_') + ".html";


            Visualize.GenerateMultiPaneGraph(newsym, dateTimeList.Keys.ToArray(), m, QSConstants.DEFAULT_DATA_FILEPATH + filename,
                                             new ChartOption[] { new ChartOption(), new ChartOption()
                                                                 {
                                                                     Layover = true, YPosition = 0
                                                                 }, new ChartOption()
                                                                 {
                                                                     YPosition = 1
                                                                 } }, null, filename + ".json");

            FileUpload.UploadFileToFTP(QSConstants.DEFAULT_DATA_FILEPATH + filename, filename);
            FileUpload.UploadFileToFTP(QSConstants.DEFAULT_DATA_FILEPATH + filename + ".json", filename + ".json");

            double Spread = m[2, m.ColumnCount - 1];

            if (Spread > 2.0 && m[2, m.ColumnCount - 2] <= 2.0)
            {
                Emailer.SendEmail(symbol1 + "-" + symbol2 + " Spread Above 2.0", "Test");
            }

            if (Spread < -2.0 && m[2, m.ColumnCount - 2] >= -2.0)
            {
                Emailer.SendEmail(symbol1 + "-" + symbol2 + " Spread Below -2.0", "Test");
            }
        }
Exemplo n.º 27
0
        public void FinishAndProcess()
        {
            try
            {
                var priceData = new DenseMatrix(symbols.Length, numTicks);

                for (int j = 0; j < symbols.Length; j++)
                {
                    SortedList <DateTime, Tick> d = mktData[j].data.Data;
                    for (int k = 0; k < d.Count; k++)
                    {
                        //if (!symbols[j].Substring(0, 3).Equals("USD")) priceData[j, k] = 1/d.Values[k].BidClose;
                        priceData[j, k] = d.Values[k].BidOpen;
                    }
                }

                Vector <double> price1 = priceData.Row(0);
                Vector <double> price2 = priceData.Row(1);
                //Statistics.ApplyFunction((DenseVector)price1, Math.Log);
                //Statistics.ApplyFunction((DenseVector)price2, Math.Log);

                DenseVector norm1 = price1.ToArray().NormalizeZScore();
                DenseVector norm2 = price2.ToArray().NormalizeZScore();

                var newsym = new string[symbols.Length + 4];
                for (int i = 0; i < symbols.Length; i++)
                {
                    newsym[i] = symbols[i];
                }

                newsym[2] = "spread";
                newsym[3] = "EMA5";
                newsym[4] = "EMA15";
                newsym[5] = "EMA30";


                var m = new DenseMatrix(6, norm1.Count);
                m.SetRow(0, norm1);
                m.SetRow(1, norm2);
                m.SetRow(2, (norm1 - norm2).ToArray().NormalizeZScore());
                m.SetRow(3, EMA.CalcEMA(m.Row(2).ToArray(), 5));
                m.SetRow(4, EMA.CalcEMA(m.Row(2).ToArray(), 15));
                m.SetRow(5, EMA.CalcEMA(m.Row(2).ToArray(), 30));

                string filename = symbols[0].Replace('/', '_') + "-" + symbols[1].Replace('/', '_') + ".html";


                ((DenseVector)m.Row(0)).GenerateSimpleGraph("C:\\Sangar\\result.html");

                Visualize.GenerateMultiSymbolGraph(newsym, m, DateTime.Now.AddSeconds(-60 * 5 * 300), new TimeSpan(0, 5, 0),
                                                   "C:\\Sangar\\" + filename);

                FileUpload.UploadFileToFTP("C:\\Sangar\\" + filename, filename);

                Spread = m[2, m.ColumnCount - 1];

                if (Spread > 2.0 && m[2, m.ColumnCount - 2] <= 2.0)
                {
                    Emailer.SendEmail(symbols[0] + "-" + symbols[1] + " Spread Above 2.0", "Test");
                }

                if (Spread < -2.0 && m[2, m.ColumnCount - 2] >= -2.0)
                {
                    Emailer.SendEmail(symbols[0] + "-" + symbols[1] + " Spread Below -2.0", "Test");
                }

                //if (m[2, m.ColumnCount - 1] < 0.5 && m[2, m.ColumnCount - 2] >= 0.5)
                //    Emailer.SendEmail(symbols[0] + "-" + symbols[1] + " Spread Below 0.5", "Test");

                //if (m[2, m.ColumnCount - 1] > -0.5 && m[2, m.ColumnCount - 2] <= -0.5)
                //    Emailer.SendEmail(symbols[0] + "-" + symbols[1] + " Spread Above -0.5", "Test");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        void CreateDebugImages()
        {
            List <InfernoTower>  infernos       = InfernoTower.Find(CacheBehavior.Default).ToList();
            List <WizardTower>   wizTowers      = WizardTower.Find(CacheBehavior.Default).ToList();
            List <ArcherTower>   archerTowers   = ArcherTower.Find(CacheBehavior.Default).ToList();
            List <ElixirStorage> elixirStorages = ElixirStorage.Find(CacheBehavior.Default).ToList();
            EagleArtillery       eagle          = EagleArtillery.Find(CacheBehavior.Default);

            var d             = DateTime.UtcNow;
            var debugFileName = $"Dragon Deploy {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}";

            using (Bitmap canvas = Screenshot.Capture())
            {
                Screenshot.Save(canvas, $"{debugFileName}_1");

                //Draw some stuff on it.
                Visualize.Axes(canvas);
                Visualize.Grid(canvas, redZone: true);
                Visualize.Target(canvas, mainTarget.Center, 40, Color.Red);
                Visualize.Target(canvas, deFunnelPoints[0], 40, Color.White);
                Visualize.Target(canvas, deFunnelPoints[1], 40, Color.White);
                Visualize.Target(canvas, balloonFunnelPoints[0], 40, Color.Pink);
                Visualize.Target(canvas, balloonFunnelPoints[1], 40, Color.Pink);

                for (int i = 0; i < infernos.Count(); i++)
                {
                    Visualize.Target(canvas, infernos.ElementAt(i).Location.GetCenter(), 30, Color.Orange);
                }

                for (int i = 0; i < airDefenses.Count(); i++)
                {
                    Visualize.Target(canvas, airDefenses.ElementAt(i).Location.GetCenter(), 30, Color.Cyan);
                }

                for (int i = 0; i < wizTowers.Count(); i++)
                {
                    Visualize.Target(canvas, wizTowers.ElementAt(i).Location.GetCenter(), 30, Color.Purple);
                }

                for (int i = 0; i < archerTowers.Count(); i++)
                {
                    Visualize.Target(canvas, archerTowers.ElementAt(i).Location.GetCenter(), 30, Color.RosyBrown);
                }

                if (eagle != null)
                {
                    Visualize.Target(canvas, eagle.Location.GetCenter(), 30, Color.YellowGreen);
                }

                Visualize.Target(canvas, mainTarget.DeployGrunts, 40, Color.Beige);

                Screenshot.Save(canvas, $"{debugFileName}_2");
            }

            //Write a text file that goes with all images that shows what is in the image.
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < airDefenses.Count(); i++)
            {
                sb.AppendLine($"Air Defense {i + 1} - Level:{airDefenses.ElementAt(i).Level}");
            }

            for (int i = 0; i < infernos.Count(); i++)
            {
                sb.AppendLine($"Inferno Tower {i + 1} - Level:{infernos.ElementAt(i).Level}");
            }

            for (int i = 0; i < wizTowers.Count(); i++)
            {
                sb.AppendLine($"Wizard Tower {i + 1} - Level:{wizTowers.ElementAt(i).Level}");
            }

            for (int i = 0; i < archerTowers.Count(); i++)
            {
                sb.AppendLine($"Archer Tower {i + 1} - Level:{archerTowers.ElementAt(i).Level}");
            }

            if (eagle != null)
            {
                sb.AppendLine($"Eagle Artillery 1 - Level:{eagle.Level}");
            }

            //System.IO.File.WriteAllText($@"C:\RaccoonBot\Debug Screenshots\{debugFileName}_3.txt", sb.ToString());

            Log.Info($"{Tag} Deploy Debug Image Saved!");
        }
Exemplo n.º 29
0
        private static void OutputDebugImage(string algorithmName, List <Building> buildings, List <Target> targetList, string AttackId)
        {
            var d             = DateTime.UtcNow;
            var debugFileName = $"{algorithmName} {d.Year}-{d.Month}-{d.Day} {d.Hour}-{d.Minute}-{d.Second}-{d.Millisecond}[{AttackId}]".GetSafeFilename();

            //Get a screen Capture of all targets we found...
            using (Bitmap canvas = Screenshot.Capture())
            {
                Screenshot.Save(canvas, $"{debugFileName}_1");

                Visualize.Axes(canvas);
                Visualize.Grid(canvas, redZone: true);

                //Draw the Max Outside Boundry For Deployment...
                for (int i = -35; i <= 35; i++)
                {
                    var color = Color.Magenta;
                    if (i % 2 == 0)
                    {
                        color = Color.LightPink;
                    }

                    float max = 30f;
                    DrawLine(canvas, color, SafePoint(max, i), SafePoint(max, i + 1));   //Top Left Side
                    DrawLine(canvas, color, SafePoint(i, max), SafePoint(i + 1, max));   //Top Right Side
                    DrawLine(canvas, color, SafePoint(i + 1, -max), SafePoint(i, -max)); //Bottom Left Side
                    DrawLine(canvas, color, SafePoint(-max, i + 1), SafePoint(-max, i)); //Bottom Right Side
                }

                //Temporary Draw all the Redpoints.
                foreach (var point in GameGrid.RedPoints)
                {
                    DrawPoint(canvas, Color.Red, point);
                }

                //Temporary Draw all the Greenpoints.
                foreach (var point in GreenPoints)
                {
                    DrawPoint(canvas, Color.Green, point);
                }

                foreach (var building in buildings)
                {
                    var color = Color.White;
                    if (building.GetType() == typeof(ElixirCollector) || building.GetType() == typeof(ElixirStorage))
                    {
                        color = Color.Violet;
                    }
                    if (building.GetType() == typeof(GoldMine) || building.GetType() == typeof(GoldStorage))
                    {
                        color = Color.Gold;
                    }
                    if (building.GetType() == typeof(DarkElixirDrill) || building.GetType() == typeof(DarkElixirStorage))
                    {
                        color = Color.Brown;
                    }

                    //Draw a target on each building.
                    Visualize.Target(canvas, building.Location.GetCenter(), 40, color);
                }
                //Save the Image to the Debug Folder...
                Screenshot.Save(canvas, $"{debugFileName}_2");
            }

            //Get a screen Capture of all targets we found...
            using (Bitmap canvas = Screenshot.Capture())
            {
                foreach (var target in targetList)
                {
                    var color = Color.White;
                    if (target.TargetBuilding.GetType() == typeof(ElixirCollector) || target.TargetBuilding.GetType() == typeof(ElixirStorage))
                    {
                        color = Color.Violet;
                    }
                    if (target.TargetBuilding.GetType() == typeof(GoldMine) || target.TargetBuilding.GetType() == typeof(GoldStorage))
                    {
                        color = Color.Gold;
                    }
                    if (target.TargetBuilding.GetType() == typeof(DarkElixirDrill) || target.TargetBuilding.GetType() == typeof(DarkElixirStorage))
                    {
                        color = Color.Brown;
                    }

                    //Draw a target on each building.
                    Visualize.Target(canvas, target.TargetBuilding.Location.GetCenter(), 40, color);
                    Visualize.Target(canvas, target.DeployGrunts, 20, color);
                    Visualize.Target(canvas, target.DeployRanged, 20, color);
                }
                //Save the Image to the Debug Folder...
                Screenshot.Save(canvas, $"{debugFileName}_3");
            }

            Log.Debug("[Berts Algorithms] Collector/Storage & Target Debug Images Saved!");
        }
Exemplo n.º 30
0
        public void CalculatePerformance()
        {
            double[] performance = performanceMatrix.Row(4).ToArray();
            double   sharpeRatio = performance.ToArray().SharpeRatio();
            double   averageRet  = performance.ToArray().AverageRawReturn();

            ret = 100 * (performance[performance.Length - 1] - performance[0]) / performance[0];

            if (Output)
            {
                List <string> symbols = new List <string>();
                symbols.Add("Performance");
                symbols.Add("Balance");
                symbols.Add("Equity");

                List <ChartOption> options = new List <ChartOption>();
                options.Add(new ChartOption()
                {
                    ChartType = "spline", Height = 300, YPosition = 0
                });
                options.Add(new ChartOption()
                {
                    ChartType = "spline", Height = 200, YPosition = 1
                });
                options.Add(new ChartOption()
                {
                    ChartType = "spline", Height = 0, YPosition = 1, Layover = true
                });

                int yPos = 3;
                foreach (var indicator in _strategies[0].indicatorList.Values)
                {
                    options.Add(new ChartOption()
                    {
                        ChartType = "spline", Height = 200, YPosition = yPos
                    });
                    symbols.Add(indicator.ToString());
                    yPos++;
                }


                Visualize.GenerateMultiPaneGraph(
                    symbols.ToArray(),
                    _multiQuantum.Keys.ToArray(),
                    performanceMatrix,
                    QSConstants.DEFAULT_DATA_FILEPATH + "result.html",
                    options.ToArray(),
                    _accountManager.Flags.ToArray()
                    );

                Console.WriteLine("Total return: " +
                                  100 * (performance[performance.Length - 1] - performance[0]) / performance[0] + "%");
                Console.WriteLine("Maximum drawdown: " + 100 * performance.ToArray().MaximumDrawdown(true) + "%");
                Console.WriteLine("Average return " + 100 * averageRet + "%");
                Console.WriteLine("Sharpe ratio " + sharpeRatio);

                double trades      = _accountManager.Trades.Count;
                double totalProfit = _accountManager.Trades.Sum(d1 => d1 > 0 ? d1 : 0);
                double totalLoss   = _accountManager.Trades.Sum(d1 => d1 < 0 ? d1 : 0);
                double ProfitCount = _accountManager.Trades.Count(d1 => d1 > 0);
                double LossCount   = _accountManager.Trades.Count(d1 => d1 < 0);

                Console.WriteLine("Number of trades closed: " + trades);
                Console.WriteLine("% Profit trades: " + ProfitCount / trades);
                Console.WriteLine("% Loss trades: " + LossCount / trades);
                Console.WriteLine("Average Profit/trade: " + totalProfit / ProfitCount);
                Console.WriteLine("Average Loss/trade: " + totalLoss / LossCount);
            }
        }