Esempio n. 1
0
        static void Main(string[] args)
        {
            //args = new[] { "autosignals" };

            //var g = new SignalGenerator { Symbol = "ACARIX" };
            //g.GenerateSignals();

            //Console.ReadLine();

            //return;

            var autoSignals = false;

            if (args.Length > 0 && args[0].ToLowerInvariant() == "autosignals")
            {
                autoSignals = true;
            }

            var infoPath = @"Dropbox\info.json";

            var jsonPath = Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), infoPath);

            if (!File.Exists(jsonPath))
            {
                jsonPath = Path.Combine(Environment.GetEnvironmentVariable("AppData"), infoPath);
            }

            if (!File.Exists(jsonPath))
            {
                throw new Exception("Dropbox could not be found!");
            }

            var dropboxPath = File.ReadAllText(jsonPath).Split('\"')[5].Replace(@"\\", @"\");

            var dataFilePath = Path.Combine(dropboxPath, "Data");

            if (!Directory.Exists(dataFilePath))
            {
                Directory.CreateDirectory(dataFilePath);
            }


            var signalsPath = Path.Combine(dataFilePath, $"Invesim");

            if (!Directory.Exists(signalsPath))
            {
                Directory.CreateDirectory(signalsPath);
            }
            var templatePath      = Path.Combine(signalsPath, "SignalChart.xlsx");
            var symbolsPath       = Path.Combine(signalsPath, "Symbols.txt");
            var currentlyOpenPath = Path.Combine(signalsPath, "CurrentlyOpen.json");

            signalsPath = Path.Combine(signalsPath, $"Signals");
            if (!Directory.Exists(signalsPath))
            {
                Directory.CreateDirectory(signalsPath);
            }
            signalsPath = Path.Combine(signalsPath, $"{DateTime.Today:yyyy-MM-dd}.txt");

            dataFilePath = Path.Combine(dataFilePath, "InveSim.v2.json");

            var sim = new Simulator.Simulator();

            sim.OnNeedData += Sim_OnNeedData;
            sim.OnLog      += Sim_OnLog;

            //var data = System.IO.File.Exists("data.xml") ? System.IO.File.ReadAllText("data.xml") : null;
            //sim.LoadData(data);

            var data = System.IO.File.Exists(dataFilePath) ? System.IO.File.ReadAllText(dataFilePath) : null;

            System.IO.File.WriteAllText("data.backup.json", data);
            sim.LoadJsonData(data);

            while (true)
            {
                Console.WriteLine("InveSim");
                Console.WriteLine();

                var choice = -1;

                if (autoSignals)
                {
                    choice = 5;
                }

                while (choice < 0)
                {
                    Console.WriteLine("1 - Simulate v");
                    Console.WriteLine("2 - Simulate s");
                    Console.WriteLine("3 - Simulate s, ohv");
                    Console.WriteLine("4 - Update values");
                    Console.WriteLine("5 - Generate signals");
                    Console.WriteLine("6 - Get signal data");
                    Console.WriteLine("0 - Exit");
                    var s = Console.ReadLine();
                    choice = int.TryParse(s, out var x) ? x : -1;
                }

                if (choice == 0)
                {
                    return;
                }

                sim.Setup(choice == 4);

                sim.Holdings.Clear();

                sim.Data.Signals.Signals.Clear();

                var vecko  = choice == 1 || choice == 4;
                var signal = choice == 2 || choice == 3 || choice == 4;

                var sig = sim.Data.Signals;

                if (choice == 6)
                {
                    Console.Write("Symbol: ");
                    var symbol = Console.ReadLine();

                    var oldFile       = System.IO.File.ReadAllText(currentlyOpenPath);
                    var currentlyOpen = JsonDeserialize <List <(DateTime, string)> >(oldFile);
                    var gen           = new SignalGenerator {
                        Symbol = symbol
                    };
                    var sym = currentlyOpen.Where(i => i.Item2 == symbol).Select(i => (DateTime?)i.Item1).FirstOrDefault();
                    if (sym.HasValue)
                    {
                        var dte = sim.Data.DateHandler.GetPreviousDate(sym.Value);
                        gen.ForceBuy = dte;
                    }
                    var x = gen.GenerateSignals();

                    Console.WriteLine("Date;Open;High;Low;Close;BuyLine;SellLine;StopLoss;In");
                    var pb = gen.Days[0].In;

                    foreach (var day in gen.Days)
                    {
                        var sl  = day.StopLoss <= 0 ? "" : day.StopLoss.ToString("###0.00");
                        var inn = day.In == pb ? "" : (day.In ? "1" : "0");

                        pb = day.In;

                        Console.WriteLine($"{day.Date:yyyy-MM-dd};{day.Open:###0.00};{day.High:###0.00};{day.Low:###0.00};{day.Close:###0.00};{day.BuyLine:###0.00};{day.SellLine:###0.00};{sl};{inn}");
                    }

                    while (true)
                    {
                        Console.WriteLine();
                        Console.Write("Create chart (Y/N): ");

                        if (Console.ReadLine().ToLowerInvariant() == "y")
                        {
                            DateTime?startDate = null;
                            var      def       = DateTime.Today.AddMonths(-3).ToString("yyyyMMdd");
                            while (!startDate.HasValue)
                            {
                                Console.Write($"Enter start date (yyyyMMdd) [{def}]: ");
                                var inp = Console.ReadLine();
                                if (inp == "")
                                {
                                    inp = def;
                                }
                                if (DateTime.TryParseExact(inp, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var v))
                                {
                                    startDate = v;
                                }
                            }

                            DateTime?endDate = null;
                            def = DateTime.Today.ToString("yyyyMMdd");
                            if (DateTime.Now.Hour < 17)
                            {
                                def = DateTime.Today.AddDays(-1).ToString("yyyyMMdd");
                            }
                            while (!endDate.HasValue)
                            {
                                Console.Write($"Enter end date (yyyyMMdd) [{def}]: ");
                                var inp = Console.ReadLine();
                                if (inp == "")
                                {
                                    inp = def;
                                }
                                if (DateTime.TryParseExact(inp, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var v))
                                {
                                    endDate = v;
                                }
                            }

                            var activeRange = gen.Days.Where(d => d.Date >= startDate && d.Date <= endDate).ToList();

                            CreateChart(activeRange, symbol, templatePath);
                        }
                        else
                        {
                            break;
                        }
                    }

                    continue;
                }
                if (choice == 5)
                {
                    try
                    {
                        sig.Signals.Clear();

                        var symbolList = System.IO.File.ReadAllText(symbolsPath).Replace("\n", "").Split('\r').Where(s => !string.IsNullOrEmpty(s)).ToList();

                        var oldFile       = System.IO.File.ReadAllText(currentlyOpenPath);
                        var currentlyOpen = JsonDeserialize <List <(DateTime, string)> >(oldFile);

                        var TargetSl = new List <(string, double, double)>();

                        foreach (var s in symbolList)
                        {
                            Console.WriteLine(s);

                            var gen = new SignalGenerator {
                                Symbol = s
                            };
                            var sym = currentlyOpen.Where(i => i.Item2 == s).Select(i => (DateTime?)i.Item1).FirstOrDefault();
                            if (sym.HasValue)
                            {
                                var dte = sim.Data.DateHandler.GetPreviousDate(sym.Value);
                                gen.ForceBuy = dte;
                            }
                            var x = gen.GenerateSignals();
                            foreach (var d in x.Item1)
                            {
                                sig.AddSignal(d, s, true, false);
                            }
                            foreach (var d in x.Item2)
                            {
                                sig.AddSignal(d, s, false, true);
                            }
                            TargetSl.Add((s, gen.Target, gen.StopLoss));
                        }

                        foreach (var s in sig.Signals)
                        {
                            s.Date = sim.Data.DateHandler.GetNextDate(s.Date);
                        }

                        var active = new List <(DateTime, string)>();

                        foreach (var symbol in sig.Signals.Select(s => s.Symbol).Distinct())
                        {
                            var sym = sig.Signals.Where(s => s.Symbol == symbol).OrderByDescending(s => s.Date).First();
                            if (sym.Buy)
                            {
                                active.Add((sym.Date, sym.Symbol));
                            }
                        }

                        var dt = sig.Signals.Max(s => s.Date);

                        var dates = new List <DateTime>();

                        while (dates.Count < 5)
                        {
                            dates.Add(dt);
                            dt = sig.Signals.Where(s => s.Date < dt).Max(s => s.Date);
                        }

                        //if(!autoSignals) Console.ReadLine();

                        var sb = new System.Text.StringBuilder();

                        foreach (var d in dates.OrderBy(d => d))
                        {
                            sb.AppendLine($"Signals for {d:yyyy-MM-dd}");
                            Console.WriteLine($"Signals for {d:yyyy-MM-dd}");

                            foreach (var s in sig.Signals.Where(x => x.Date.Equals(d)))
                            {
                                sb.AppendLine($"{s.Symbol}, {(s.Buy ? "buy" : "sell")}");
                                Console.WriteLine($"{s.Symbol}, {(s.Buy ? "buy" : "sell")}");
                            }

                            sb.AppendLine();
                        }

                        sb.AppendLine($"Open");
                        Console.WriteLine($"Open");

                        var fileContent = JsonSerialize(active);
                        if (autoSignals)
                        {
                            System.IO.File.WriteAllText(currentlyOpenPath, fileContent);
                        }

                        foreach (var(date, sym) in active.OrderBy(s => s.Item1))
                        {
                            var TS = TargetSl.Where(t => t.Item1 == sym).First();
                            sb.AppendLine($"{date:yyyy-MM-dd} {sym} Target: {TS.Item2:####0.00} StopLoss: {TS.Item3:####0.00}");
                            Console.WriteLine($"{date:yyyy-MM-dd} {sym} Target: {TS.Item2:####0.00} StopLoss: {TS.Item3:####0.00}");
                        }

                        if (autoSignals)
                        {
                            System.IO.File.WriteAllText(signalsPath, sb.ToString());
                        }

                        if (autoSignals)
                        {
                            return;
                        }

                        Console.ReadLine();

                        continue;
                    }catch (Exception ex)
                    {
                        if (!autoSignals)
                        {
                            throw;
                        }

                        System.IO.File.WriteAllText(signalsPath + ".error.txt", ex.ToString());

                        return;
                    }
                }

                if (vecko)
                {
                    AddSignals(sig);
                }

                if (signal)
                {
                    var onlyHighVolume = choice == 3;

                    if (!onlyHighVolume)
                    {
                        sig.Add("HIFA B  ", "20200515", "20200522");
                        sig.Add("CTT     ", "20200519", "20200520");
                        sig.Add("SJR B   ", "20200525", "20200612");
                        sig.Add("CAT B   ", "20200526", "20200610");
                        sig.Add("CTT     ", "20200527", "20200528");
                        sig.Add("ACTI    ", "20200528", "20200602");
                        sig.Add("CTT     ", "20200529", "20200612");
                        sig.Add("HIFA B  ", "20200608", "20200612");
                        sig.Add("ACTI    ", "20200611", "20200622");
                        sig.Add("CAT B   ", "20200611", "20200612");
                        sig.Add("SJR B   ", "20200617", "20200711");
                        sig.Add("CTT     ", "20200618", "20200701");
                        sig.Add("HIFA B  ", "20200626", "20200707");
                        sig.Add("CAT B   ", "20200702", "20200720");
                        sig.Add("CTT     ", "20200703", null);
                        sig.Add("ACTI    ", "20200708", "20200714");
                        sig.Add("SJR B   ", "20200720", null);
                        sig.Add("ACTI    ", "20200721", null);
                        sig.Add("CAT B   ", "20200721", null);
                    }

                    sig.Add("NETI B  ", "20200518", "20200610");
                    sig.Add("ATRLJ B ", "20200519", "20200612");
                    sig.Add("FING B  ", "20200519", "20200610");
                    sig.Add("EOLU B  ", "20200520", "20200612");
                    sig.Add("WIHL    ", "20200520", "20200612");
                    sig.Add("AAK     ", "20200522", "20200609");
                    sig.Add("NEWA B  ", "20200527", "20200612");
                    sig.Add("GCOR    ", "20200601", "20200612");
                    sig.Add("AAK     ", "20200611", "20200612");
                    sig.Add("NETI B  ", "20200611", "20200702");
                    sig.Add("WIHL    ", "20200617", "20200624");
                    sig.Add("ATRLJ B ", "20200618", "20200623");
                    sig.Add("AZA     ", "20200629", "20200701");
                    sig.Add("FING B  ", "20200629", "20200630");
                    sig.Add("EOLU B  ", "20200701", "20200715");
                    sig.Add("AZA     ", "20200702", null);
                    sig.Add("GCOR    ", "20200703", "20200714");
                    sig.Add("WIHL    ", "20200703", "20200708");
                    sig.Add("ATRLJ B ", "20200707", "20200708");
                    sig.Add("ATRLJ B ", "20200709", "20200713");
                    sig.Add("ATRLJ B ", "20200714", "20200720");
                    sig.Add("FING B  ", "20200714", null);
                    sig.Add("AAK     ", "20200716", "20200720");
                    sig.Add("EOLU B  ", "20200721", null);
                }

                sim.Data.DateHandler.Holidays.Clear();
                sim.Data.DateHandler.Holidays.Add(new DateTime(2019, 4, 19));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2019, 5, 30));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2019, 6, 6));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2019, 6, 10));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2019, 12, 24));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2019, 12, 25));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2019, 12, 26));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2019, 12, 31));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 1, 1));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 1, 6));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 4, 10));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 4, 13));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 5, 1));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 5, 21));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 6, 19));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 12, 24));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 12, 25));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2020, 12, 31));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2021, 1, 1));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2021, 1, 6));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2021, 4, 6));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2021, 5, 13));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2021, 6, 25));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2021, 12, 24));
                sim.Data.DateHandler.Holidays.Add(new DateTime(2021, 12, 31));

                Console.WriteLine(sim.Details());

                var until = DateTime.Today;

                var timeCheck = choice == 4 ? 1730 : 1745;

                if (int.Parse(DateTime.Now.ToString("HHmm")) < timeCheck)
                {
                    until = sim.Data.DateHandler.GetPreviousDate(until);
                }

                until = sim.Data.DateHandler.GetPreviousDate(until.AddDays(1));

                var log = new List <(DateTime date, decimal cash, decimal total)>();

                //sim.Data.Symbols.Clear();

                var lastData = "";

                while (sim.CurrentDate < until)
                {
                    sim.NextDay();
                    log.Add((sim.CurrentDate, sim.Cash, sim.TotalValue));
                    //data = sim.GetData();
                    //System.IO.File.WriteAllText("data.xml", data);
                    data = sim.GetJsonData();
                    if (data != lastData)
                    {
                        for (var i = 0; i < 10; i++)
                        {
                            try
                            {
                                System.IO.File.WriteAllText(dataFilePath, data);
                                break;
                            }
                            catch (System.IO.IOException) when(i < 9)
                            {
                                Console.WriteLine("IO Error, retrying...");
                                System.Threading.Thread.Sleep(1000);
                            }
                        }
                    }
                    lastData = data;
                    Console.WriteLine();
                    Console.WriteLine(sim.Details());
                    //Console.WriteLine("Press enter...");
                    //Console.ReadLine();
                }

                Console.WriteLine();
                Console.ReadLine();

                foreach ((var date, decimal cash, decimal total) in log)
                {
                    Console.WriteLine($"{date:yyyy-MM-dd};{cash};{total - cash}");
                }

                Console.ReadLine();

                if (autoSignals)
                {
                    break;
                }
            }
        }