예제 #1
0
        //[TestMethod]
        public void test_deals()
        {
            FinancialInstrument instr    = controller.get_instrument("SPFB_LKOH_140101_140331.txt");
            TradingStrategy     strategy = controller.get_strategy("Test5").Originator;

            ForecastingModule forecastingModule = new ForecastingModule(strategy, instr);
            ForecastResult    result            = forecastingModule.run();

            int      numDeal = 5;
            TypeDeal expType = TypeDeal.Sell;
            DateTime expDateOpen = new DateTime(14, 2, 12, 12, 35, 0);
            DateTime expDateClose = new DateTime(14, 2, 12, 12, 36, 0);
            double   expOpenPrice = 20430, expClosePrice = 20438;

            TradeDeal tradeDeal = result.get_deal(numDeal);

            double actOpenPrice  = tradeDeal.OpeningPrice;
            double actClosePrice = tradeDeal.ClosingPrice;

            Assert.AreEqual(
                true,
                tradeDeal.Opening == false &&
                tradeDeal.Type == expType &&
                actOpenPrice == expOpenPrice
                //&& tradeDeal.DateTimeOpen.Equals(expDateOpen)
                //&& tradeDeal.DateTimeClose == expDateClose
                && actClosePrice == expClosePrice
                );
        }
예제 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHangfireDashboard("/mydashboard");

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });

            var myTradingService = new TradingStrategy(new AlphaVantage(), new PortfolioOperations(new TradingdbContext(), new AlphaVantage()));

            RecurringJob.AddOrUpdate(
                () => myTradingService.Execute(),
                Cron.HourInterval(4));
        }
예제 #3
0
 public CexApi(string apiKey, string apiSecret, string apiUsername, string slackWebhook, ILogger logger,
               TradingStrategy tradingStrategy)
 {
     _apiKey         = apiKey;
     _apiSecret      = apiSecret;
     _apiUsername    = apiUsername;
     SlackWebhook    = slackWebhook;
     Logger          = logger;
     TradingStrategy = tradingStrategy ?? new TradingStrategy
     {
         MinutesOfAccountHistoryOrderForPurchaseDecision     = 60,
         MinutesOfAccountHistoryOrderForSellDecision         = 60,
         MinutesOfPublicHistoryOrderForPurchaseDecision      = 30,
         MinutesOfPublicHistoryOrderForSellDecision          = 30,
         MinimumReservePercentageAfterInitInTargetCurrency   = 0.1m,
         MinimumReservePercentageAfterInitInExchangeCurrency = 0.1m,
         OrderCapPercentageAfterInit     = 0.6m,
         OrderCapPercentageOnInit        = 0.25m,
         AutoDecisionExecution           = true,
         MarketChangeSensitivityRatio    = 0.01m,
         PriceCorrectionFrequencyInHours = 24,
         TradingValueBleedRatio          = 0.1m
     };
     Rest = new Rest("https://cex.io/api/",
                     new RestConfig
     {
         OperationMode = RestMode.HTTPRestClient,
         UseRestConvertForCollectionSerialization = false
     },
                     logger);
 }
예제 #4
0
        public void TestMethod1()
        {
            //Входные данные
            //Создать 2 условия
            int index1 = 0, index2 = 0;
            int curIndex                 = 60;
            ParameterCondition par1      = ParameterCondition.PriceClose;
            ParameterCondition par2      = ParameterCondition.PriceOpen;
            Predicate          predicate = Predicate.Less;

            Condition cond = new Condition(index1, index2, par1, par2, null, null, 0.0, 0.0, predicate);

            int index1_ = 1, index2_ = 1;
            ParameterCondition par1_      = ParameterCondition.Indicator;
            ParameterCondition par2_      = ParameterCondition.Indicator;
            Predicate          predicate_ = Predicate.MoreEqual;
            Indicator          ind1       = new SMA(14);
            Indicator          ind2       = new SMA(28);

            Condition cond2 = new Condition(index1_, index2_, par1_, par2_, ind1, ind2, 0.0, 0.0, predicate_);


            //Накопить данные для индикаторов
            for (int i = 0; i < curIndex; i++)
            {
                ind1.update_value(i, instrument);
                ind2.update_value(i, instrument);
            }


            //Создать правило
            TradingRule rule = new TradingRule();

            rule.add_condition(cond);
            rule.add_condition(cond2);

            string          name     = "TestStrategy1";
            DateTime        dateTime = DateTime.Now;
            TradingStrategy strat    = new TradingStrategy(name);

            strat.add_rule(rule);
            strat.save_to_xml();

            controller.add_strategy(new CaretakerStrategy(strat));

            TradingStrategy strat1 = controller.get_strategy(name).Originator;

            File.Delete("Strategies\\TestStrategy1.xml");

            Assert.AreEqual(strat.Loaded &&
                            strat.Name == name &&
                            strat.DateOfChange == dateTime &&
                            strat.DateOfCreation == dateTime, true);
        }
예제 #5
0
 public BackTest(IRequest request) : base(request)
 {
     technicalAnalysis = new TechnicalAnalysis(BinanceClient, _request);
     tradingStrategy   = new TradingStrategy(BinanceClient, _request);
     LastPrices        = new Dictionary <string, decimal>();
     CandleSticks      = new Queue <Dictionary <string, Candlestick> >();
     IsLastCandleStick = false;
     foreach (var item in _request.TradingPairs)
     {
         LastPrices.Add(item, 0m);
     }
 }
예제 #6
0
        public void test_run()
        {
            FinancialInstrument instr    = controller.get_instrument("SPFB.Si_090101_091231.txt");
            TradingStrategy     strategy = controller.get_strategy("Test5").Originator;

            strategy.subscribe_analyzer(new AnalyzerDirection());

            ForecastingModule forecastingModule = new ForecastingModule(strategy, instr);
            ForecastResult    result            = forecastingModule.run();

            //result.print();
            double profitExepted = -3419;

            int      numDeal = 5;
            TypeDeal expType = TypeDeal.Buy;
            DateTime expDateOpen = new DateTime(2009, 5, 13, 10, 49, 0);
            DateTime expDateClose = new DateTime(2009, 5, 13, 10, 53, 0);
            double   expOpenPrice = 32110, expClosePrice = 32094;

            TradeDeal tradeDeal = result.get_deal(numDeal);

            double   actOpenPrice     = tradeDeal.OpeningPrice;
            double   actClosePrice    = tradeDeal.ClosingPrice;
            DateTime actDateTimeOpen  = tradeDeal.DateTimeOpen;
            DateTime actDateTimeClose = tradeDeal.DateTimeClose;


            Assert.AreEqual(true,
                            profitExepted == result.CurProfit &&
                            tradeDeal.Opening == false &&
                            tradeDeal.Type == expType &&
                            actOpenPrice == expOpenPrice &&
                            actClosePrice == expClosePrice &&
                            actDateTimeOpen == expDateOpen &&
                            actDateTimeClose == expDateClose);
        }
        static void Main(string[] args)
        {
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddConsole();
            Console.WriteLine("======================");
            var tradingEngines = new List <ITradingEngine>();

            var useExchange = SupportedExchanges.Unknown;

            while (useExchange == SupportedExchanges.Unknown)
            {
                Console.WriteLine("Type 1 for CEX.IO, Type 2 for GDAX, Type 3 for Bitstamp:");
                useExchange =
                    NumericUtils.GetIntegerValueFromObject(Console.ReadLine()).ParseEnum <SupportedExchanges>();
            }


            Console.Write($"{useExchange.ToString()} API Secret:");
            var secret = Console.ReadLine();

            switch (useExchange)
            {
            case SupportedExchanges.Cex:
                Console.Write("\n CEX Username:"******"\n GDAX Pass phrase:");
                break;

            case SupportedExchanges.Bitstamp:
                Console.Write("\n Bitstamp Client Id:");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var username = Console.ReadLine();


            Console.Write($"\n{useExchange.ToString()} API Key:");
            var apiKey = Console.ReadLine();

            Console.Write("\nSlack Notification Webhook Url:");
            var slackWebhook = Console.ReadLine();


            var exchangeCurrency = string.Empty;

            while (exchangeCurrency.IsNullOrEmpty())
            {
                Console.Write($"\n{useExchange.ToString()} Exhcange Base currency name: (default BTC)");
                exchangeCurrency = Console.ReadLine();
                if (Currencies.SupportedCurrencies.Count(i => i == exchangeCurrency) > 0)
                {
                    continue;
                }

                if (exchangeCurrency.IsNullOrEmpty())
                {
                    Console.WriteLine("Default cryptocurrency BTC selected.");
                    exchangeCurrency = Currencies.BTC;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.BackgroundColor = ConsoleColor.White;
                    Console.WriteLine("Invalid currency name. Please try again.");
                    Console.ResetColor();
                    exchangeCurrency = null;
                }
            }

            var targetCurrency = string.Empty;

            while (targetCurrency.IsNullOrEmpty())
            {
                Console.Write($"\n{useExchange.ToString()} Exhcange Target currency name: (default USD)");
                targetCurrency = Console.ReadLine();
                if (Currencies.SupportedCurrencies.Count(i => i == targetCurrency) > 0)
                {
                    continue;
                }

                if (targetCurrency.IsNullOrEmpty())
                {
                    Console.WriteLine("Default target currency USD selected.");
                    targetCurrency = Currencies.USD;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.BackgroundColor = ConsoleColor.White;
                    Console.WriteLine("Invalid currency name. Please try again.");
                    Console.ResetColor();
                    targetCurrency = null;
                }
            }


            var stopLine = 0m;

            while (stopLine <= 0)
            {
                Console.Write("\nSpecify the bottom line value where execution should STOP:");
                stopLine = NumericUtils.GetDecimalValueFromObject(Console.ReadLine());
                if (stopLine > 0)
                {
                    continue;
                }

                Console.ForegroundColor = ConsoleColor.Red;
                Console.BackgroundColor = ConsoleColor.White;
                Console.WriteLine(
                    "Bottom line value must be positive number representing your target currency value. (e.g. 5000 )");
                Console.ResetColor();
            }

            Console.WriteLine(
                $"Minutes of historical orders on {useExchange.ToString()} for buying considerations: (default 3)");
            var publicOrderHistoryForBuyingDecision = NumericUtils.GetIntegerValueFromObject(Console.ReadLine());

            if (publicOrderHistoryForBuyingDecision <= 0)
            {
                publicOrderHistoryForBuyingDecision = 3;
            }

            Console.WriteLine(
                $"Minutes of historical orders on {useExchange.ToString()} for selling considerations: (default 3)");
            var publicOrderHistoryForSellingDecision = NumericUtils.GetIntegerValueFromObject(Console.ReadLine());

            if (publicOrderHistoryForSellingDecision <= 0)
            {
                publicOrderHistoryForSellingDecision = 3;
            }

            Console.WriteLine("Minutes of historical account orders for buying considerations: (default 5)");
            var accountOrderHistoryForBuyingDecision = NumericUtils.GetIntegerValueFromObject(Console.ReadLine());

            if (accountOrderHistoryForBuyingDecision <= 0)
            {
                accountOrderHistoryForBuyingDecision = 5;
            }

            Console.WriteLine("Minutes of historical account orders for selling considerations: (default 5)");
            var accountOrderHistoryForSellingDecision = NumericUtils.GetIntegerValueFromObject(Console.ReadLine());

            if (accountOrderHistoryForSellingDecision <= 0)
            {
                accountOrderHistoryForSellingDecision = 5;
            }

            Console.WriteLine("Minutes change sensitivity ratio in decimal: (default 0.005)");
            var sensitivityRatio = NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (sensitivityRatio <= 0)
            {
                sensitivityRatio = 0.005m;
            }

            Console.WriteLine("Minimum Reserve In Target Currency: (default 0.2)");
            var minimumReservePercentageAfterInitInTargetCurrency =
                NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (minimumReservePercentageAfterInitInTargetCurrency <= 0)
            {
                minimumReservePercentageAfterInitInTargetCurrency = 0.2m;
            }

            Console.WriteLine("Minimum Reserve In Exchange Currency: (default 0.2)");
            var minimumReservePercentageAfterInitInExchangeCurrency =
                NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (minimumReservePercentageAfterInitInExchangeCurrency <= 0)
            {
                minimumReservePercentageAfterInitInExchangeCurrency = 0.2m;
            }

            Console.WriteLine("Order Cap Percentage On Init: (default 0.25)");
            var orderCapPercentageOnInit =
                NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (orderCapPercentageOnInit <= 0)
            {
                orderCapPercentageOnInit = 0.25m;
            }

            Console.WriteLine("Order Cap Percentage After Init: (default 0.3)");
            var orderCapPercentageAfterInit =
                NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (orderCapPercentageAfterInit <= 0)
            {
                orderCapPercentageAfterInit = 0.3m;
            }


            bool autoExecution;

            Console.ForegroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("Automated order execution - Enter 'CONFIRM' to execute order automatically: ");
            Console.ResetColor();
            autoExecution = Console.ReadLine() == "CONFIRM";


            var tradingStrategy = new TradingStrategy
            {
                MinutesOfAccountHistoryOrderForPurchaseDecision     = accountOrderHistoryForBuyingDecision,
                MinutesOfAccountHistoryOrderForSellDecision         = accountOrderHistoryForSellingDecision,
                MinutesOfPublicHistoryOrderForPurchaseDecision      = publicOrderHistoryForBuyingDecision,
                MinutesOfPublicHistoryOrderForSellDecision          = publicOrderHistoryForSellingDecision,
                MinimumReservePercentageAfterInitInTargetCurrency   = minimumReservePercentageAfterInitInTargetCurrency,
                MinimumReservePercentageAfterInitInExchangeCurrency =
                    minimumReservePercentageAfterInitInExchangeCurrency,
                OrderCapPercentageAfterInit = orderCapPercentageAfterInit,
                OrderCapPercentageOnInit    = orderCapPercentageOnInit,
                AutoDecisionExecution       = autoExecution,
                StopLine = stopLine,
                MarketChangeSensitivityRatio    = sensitivityRatio,
                PriceCorrectionFrequencyInHours = 12,
                TradingValueBleedRatio          = 0.1m
            };

            IApi api;

            switch (useExchange)
            {
            case SupportedExchanges.Gdax:
                api = new GdaxApi(apiKey, secret, username, slackWebhook,
                                  loggerFactory.CreateLogger($"GDAX Trading Engine - {exchangeCurrency} - {targetCurrency}"),
                                  tradingStrategy);
                break;

            case SupportedExchanges.Cex:
                api = new CexApi(apiKey, secret, username, slackWebhook,
                                 loggerFactory.CreateLogger($"CEX.IO Trading Engine - {exchangeCurrency} - {targetCurrency}"),
                                 tradingStrategy);
                break;

            case SupportedExchanges.Bitstamp:
                api = new BitstampApi(apiKey, secret, username, slackWebhook,
                                      loggerFactory.CreateLogger($"Bitstamp Trading Engine - {exchangeCurrency} - {targetCurrency}"),
                                      tradingStrategy);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            tradingEngines.Add(new TradingEngine(api, exchangeCurrency, targetCurrency));

            var tasks = new List <Task>();

            foreach (var engine in tradingEngines)
            {
                tasks.Add(Task.Run(async() => await engine.StartAsync()));
            }

            Task.WaitAll(tasks.ToArray());
        }
 static void Main(string[] args)
 {
     TradingStrategy tradStrat = new TradingStrategy();
 }