public async Task <ActionResult> UpdateConnection(AlgoType algoType)
        {
            var model = await PoolReader.GetPoolConnection(algoType);

            if (model == null)
            {
                return(ViewMessageModal(new ViewMessageModel(ViewMessageType.Danger, "Error", $"Connection #{algoType} not found")));
            }

            var pools = await PoolReader.GetPools();

            return(View("UpdatePoolConnectionModal", new AdminUpdatePoolConnectionModel
            {
                AlgoType = model.AlgoType,
                Host = model.Host,
                Name = model.Name,
                Port = model.Port,
                DefaultDiff = model.DefaultDiff,
                DefaultPool = model.DefaultPool,
                FixedDiffSummary = model.FixedDiffSummary,
                VarDiffHighSummary = model.VarDiffHighSummary,
                VarDiffLowSummary = model.VarDiffLowSummary,
                VarDiffMediumSummary = model.VarDiffMediumSummary,
                Pools = pools.Where(x => x.AlgoType == algoType).OrderBy(x => x.Symbol).ToList()
            }));
        }
        public async Task <List <PoolWorkerModel> > GetWorkers(string userId, AlgoType algoType)
        {
            var currentUserId = new Guid(userId);

            using (var context = PoolDataContextFactory.CreateContext())
            {
                var query = context.Worker
                            .AsNoTracking()
                            .Where(x => x.AlgoType == algoType && x.UserId == currentUserId && x.IsEnabled)
                            .OrderBy(x => x.IsActive)
                            .ThenBy(x => x.Name)
                            .Select(worker => new PoolWorkerModel
                {
                    Id               = worker.Id,
                    Name             = worker.Name,
                    AlgoType         = worker.AlgoType,
                    Hashrate         = worker.Hashrate,
                    Difficulty       = worker.Difficulty,
                    TargetPool       = worker.TargetPool,
                    Password         = worker.Password,
                    TargetDifficulty = worker.TargetDifficulty,
                    IsAutoSwitch     = worker.IsAutoSwitch,
                    IsActive         = worker.IsActive
                });

                return(await query.ToListNoLockAsync().ConfigureAwait(false));
            }
        }
Esempio n. 3
0
        public static void AddFactory(AlgoType algoType)
        {
            if (Factories.ContainsKey(algoType))
            {
                return;
            }
            switch (algoType)
            {
            case AlgoType.Constant:
                Factories.Add(AlgoType.Constant, new ConstantAlgoFactory());
                break;

            case AlgoType.Increment:
                Factories.Add(AlgoType.Increment, new IncrementAlgoFactory());
                break;

            case AlgoType.Multiple:
                Factories.Add(AlgoType.Multiple, new MultipleAlgoFactory());
                break;

            case AlgoType.Exp:
                Factories.Add(AlgoType.Exp, new ExpAlgoFactory());
                break;

            case AlgoType.Fibonacci:
                Factories.Add(AlgoType.Fibonacci, new FibonacciAlgoFactory());
                break;

            case 0:
                throw new Exception("Invalid algo type");
            }
        }
Esempio n. 4
0
        public async Task <PoolConnectionModel> GetPoolConnection(AlgoType algoType)
        {
            var cacheResult = await CacheService.GetOrSetHybridAsync(CacheKey.PoolConnection(algoType), TimeSpan.FromSeconds(10), async() =>
            {
                var sanitizer = new HtmlSanitizer();
                using (var context = PoolDataContextFactory.CreateContext())
                {
                    var query = from connection in context.Connection
                                where connection.AlgoType == algoType && connection.IsEnabled
                                select new PoolConnectionModel
                    {
                        Id                   = connection.Id,
                        Name                 = connection.Name,
                        AlgoType             = connection.AlgoType,
                        Host                 = connection.Host,
                        Port                 = connection.Port,
                        DefaultDiff          = connection.DefaultDiff,
                        DefaultPool          = connection.DefaultPool,
                        FixedDiffSummary     = connection.FixedDiffSummary,
                        VarDiffLowSummary    = connection.VarDiffLowSummary,
                        VarDiffHighSummary   = connection.VarDiffHighSummary,
                        VarDiffMediumSummary = connection.VarDiffMediumSummary
                    };

                    var result = await query.FirstOrDefaultNoLockAsync().ConfigureAwait(false);
                    result.FixedDiffSummary     = sanitizer.Sanitize(result.FixedDiffSummary);
                    result.VarDiffLowSummary    = sanitizer.Sanitize(result.VarDiffLowSummary);
                    result.VarDiffHighSummary   = sanitizer.Sanitize(result.VarDiffHighSummary);
                    result.VarDiffMediumSummary = sanitizer.Sanitize(result.VarDiffMediumSummary);
                    return(result);
                }
            }).ConfigureAwait(false);

            return(cacheResult);
        }
        public static ConvertionResult Convert(string code, AlgoType algotype, Model.File[] includeFiles)
        {
            string calgoCode = null;
            IEnumerable <ParsingError> parsingErrors = new ParsingError[0];
            var compilerErrors = new CompilerError[0];

            var codeBase = CodeBase.Mq4;

            if (CSharpCodeDetector.IsCSharpCode(code))
            {
                codeBase = CodeBase.CSharp;
            }
            else if (MqCodeBaseDetector.IsMq5Code(code))
            {
                codeBase = CodeBase.Mq5;
            }
            else if (!MqCodeBaseDetector.IsValidMq4Code(code))
            {
                codeBase = CodeBase.Invalid;
            }
            else
            {
                var parser = new Mq4Parser();

                var indicatorParsingResult = parser.Parse(code, algotype, includeFiles);
                var algo = indicatorParsingResult.Algo;
                parsingErrors = indicatorParsingResult.ParsingErrors;
                if (parsingErrors.All(e => e.ErrorType < ErrorType.Error))
                {
                    var presenter = CreatePresenter(algotype);
                    calgoCode = presenter.GenerateCodeFrom(algo);

                    var compiler = new CSharpCompiler();
                    var fileName = Path.GetTempFileName();
                    try
                    {
                        var codeToCompile = calgoCode;
                        var indexToInsert = codeToCompile.IndexOf("//Custom Indicators Place Holder");
                        foreach (var customIndicatorName in algo.CustomIndicators)
                        {
                            codeToCompile = codeToCompile.Insert(indexToInsert,
                                                                 CustomIndicatorTemplate.Replace("CustomIndicatorName",
                                                                                                 customIndicatorName));
                        }
                        compilerErrors = compiler.Compile(codeToCompile, fileName);

                        codeBase = MqCodeBaseDetector.GetCodeBaseFromErrors(compilerErrors);
                    }
                    finally
                    {
                        File.Delete(fileName);
                    }
                }
            }

            return(new ConvertionResult(calgoCode, parsingErrors, compilerErrors, codeBase));
        }
Esempio n. 6
0
        public static ConvertionResult Convert(string code, AlgoType algotype, Model.File[] includeFiles)
        {
            string calgoCode = null;
            IEnumerable<ParsingError> parsingErrors = new ParsingError[0];
            var compilerErrors = new CompilerError[0];

            var codeBase = CodeBase.Mq4;
            if (CSharpCodeDetector.IsCSharpCode(code))
            {
                codeBase = CodeBase.CSharp;
            }
            else if (MqCodeBaseDetector.IsMq5Code(code))
            {
                codeBase = CodeBase.Mq5;
            }
            else if (!MqCodeBaseDetector.IsValidMq4Code(code))
            {
                codeBase = CodeBase.Invalid;
            }
            else
            {
                var parser = new Mq4Parser();

                var indicatorParsingResult = parser.Parse(code, algotype, includeFiles);
                var algo = indicatorParsingResult.Algo;
                parsingErrors = indicatorParsingResult.ParsingErrors;
                if (parsingErrors.All(e => e.ErrorType < ErrorType.Error))
                {
                    var presenter = CreatePresenter(algotype);
                    calgoCode = presenter.GenerateCodeFrom(algo);

                    var compiler = new CSharpCompiler();
                    var fileName = Path.GetTempFileName();
                    try
                    {
                        var codeToCompile = calgoCode;
                        var indexToInsert = codeToCompile.IndexOf("//Custom Indicators Place Holder");
                        foreach (var customIndicatorName in algo.CustomIndicators)
                        {
                            codeToCompile = codeToCompile.Insert(indexToInsert,
                                                                 CustomIndicatorTemplate.Replace("CustomIndicatorName",
                                                                                                 customIndicatorName));
                        }
                        compilerErrors = compiler.Compile(codeToCompile, fileName);

                        codeBase = MqCodeBaseDetector.GetCodeBaseFromErrors(compilerErrors);
                    }
                    finally
                    {
                        File.Delete(fileName);
                    }
                }
            }

            return new ConvertionResult(calgoCode, parsingErrors, compilerErrors, codeBase);
        }
        public static string GetSimplifiedName(string fullNameWithExtraCharacters, AlgoType algoType)
        {
            var regex = new Regex(@"[^\w0-9]");
            var simplifiedName = regex.Replace(fullNameWithExtraCharacters, string.Empty);
            
            if (char.IsDigit(simplifiedName[0]))
                simplifiedName = "_" + simplifiedName;

            return simplifiedName + "_" + algoType;
        }
        public async Task <ActionResult> UpdateWorkerPool(AlgoType algoType)
        {
            var pools = await PoolReader.GetPools();

            return(View("UpdateWorkerPoolModal", new AdminUpdateWorkerPoolModel
            {
                AlgoType = algoType,
                Pools = pools.Where(x => x.AlgoType == algoType).OrderBy(x => x.Symbol).ToList()
            }));
        }
        public static AlgoType? GetAlgoType(string code, AlgoType defaultValue)
        {
            if (!code.Contains("start"))
                return null;
            if (RobotKeyWords.Any(code.Contains))
                return AlgoType.Robot;
            if (defaultValue == AlgoType.Robot)
                return null;

            return defaultValue;
        }
Esempio n. 10
0
        private static string GetMq4Name(string mq4Code, AlgoType algoType)
        {
            var match = Mq4NameRegex.Match(mq4Code);

            if (!match.Success)
            {
                return("Converted" + algoType.ToString());
            }

            return(AlgoNameProvider.GetSimplifiedName(match.Groups["name"].Value, algoType));
        }
        public static string GetSimplifiedName(string fullNameWithExtraCharacters, AlgoType algoType)
        {
            var regex          = new Regex(@"[^\w0-9]");
            var simplifiedName = regex.Replace(fullNameWithExtraCharacters, string.Empty);

            if (char.IsDigit(simplifiedName[0]))
            {
                simplifiedName = "_" + simplifiedName;
            }

            return(simplifiedName + "_" + algoType);
        }
Esempio n. 12
0
        public static double CalculateHashrate(double shares, AlgoType algoType, double hashRateCalculationPeriod)
        {
            var multiplier     = GetHashrateMultiplier(algoType);
            var diffMultiplier = Math.Pow(2, 32) / multiplier;
            var hashrate       = (diffMultiplier * shares / hashRateCalculationPeriod);

            if (hashrate > 0)
            {
                return(Math.Round(hashrate, 2));
            }
            return(0.0);
        }
Esempio n. 13
0
        public static IAlgo CreateAlgo(AlgoType algoType, int?start = null, double?value = null)
        {
            IAlgoFactory factory = null;

            if (!Factories.ContainsKey(algoType))
            {
                throw new Exception("Invalid algo type");
            }
            switch (algoType)
            {
            case AlgoType.Constant:
                Factories.TryGetValue(AlgoType.Constant, out factory);
                break;

            case AlgoType.Increment:
                Factories.TryGetValue(AlgoType.Increment, out factory);
                break;

            case AlgoType.Multiple:
                Factories.TryGetValue(AlgoType.Multiple, out factory);
                break;

            case AlgoType.Exp:
                Factories.TryGetValue(AlgoType.Exp, out factory);
                break;

            case AlgoType.Fibonacci:
                Factories.TryGetValue(AlgoType.Fibonacci, out factory);
                break;
            }
            try
            {
                IAlgo algo = null;
                if (value.HasValue)
                {
                    algo = factory.CreateAlgo(start.Value, value.Value);
                }
                else if (start.HasValue)
                {
                    algo = factory.CreateAlgo(start.Value);
                }
                else
                {
                    algo = factory.CreateAlgo();
                }

                return(algo);
            }
            catch
            {
                throw new Exception($"Invalid parameters for algo type: {algoType.ToString()}");
            }
        }
Esempio n. 14
0
        public ParsingResult Parse(string code, AlgoType algotype, File[] includeFiles)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            var parsingErrors = new ParsingErrors();

            var algo = new Algo
            {
                Mq4Code  = code,
                AlgoType = algotype
            };

            string[] customIndicators;

            code = code
                   .RemoveComments()
                   .IncludeFiles(includeFiles)
                   .HandleParsingErrors(parsingErrors);

            if (parsingErrors.Errors.Any(error => error.ErrorType >= ErrorType.NotSupportedCriticalError))
            {
                return(new ParsingResult(algo, parsingErrors.Errors));
            }

            code = code
                   .ReplaceDateTimeToInt()
                   .ReplaceDateConstants()
                   .ReplaceDefines()
                   .ReplaceCSharpKeyWords()
                   .RemoveDotsFromNames()
                   .AddZeroToDecimalNumbers()
                   .ReplaceUnknownSymbols()
                   .ReplaceMq4RgbColorsToKnownColors()
                   .ReplaceColorToInt()
                   .ReplaceCAlgoKeyWords()
                   .ReplacePrintToMq4Print()
                   .RenameFunctions()
                   .AddRefModifiers()
                   .AddTypeParameterToICustom(out customIndicators);

            HandleProperties(code, algo);
            HandleParameters(code, algo);
            HandleFunctions(code, algo, parsingErrors);
            HandleFields(code, algo);

            algo.Code.ExtractStaticVariablesToFields();
            algo.Code.ReplaceSimpleTypesToMq4Types();
            algo.Code.RenameStandardFunctions();
            algo.Code.AddMq4InitFunctionIfDoesNotExist();
            algo.CustomIndicators = customIndicators;

            return(new ParsingResult(algo, parsingErrors.Errors));
        }
Esempio n. 15
0
 private static AlgoPresenter CreatePresenter(AlgoType algotype)
 {
     string template;
     switch (algotype)
     {
         case AlgoType.Indicator:
             template = new IndicatorTemplateProvider().GetTemplate();
             break;
         default:
             template = new RobotTemplateProvider().GetTemplate();
             break;
     }
     return new AlgoPresenter(new AlgoBuilder(template));
 }
Esempio n. 16
0
        public ParsingResult Parse(string code, AlgoType algotype, File[] includeFiles)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            var parsingErrors = new ParsingErrors();

            var algo = new Algo
                {
                    Mq4Code = code, 
                    AlgoType = algotype
                };
            string[] customIndicators;

            code = code
                .RemoveComments()
                .IncludeFiles(includeFiles)
                .HandleParsingErrors(parsingErrors);

            if (parsingErrors.Errors.Any(error => error.ErrorType >= ErrorType.NotSupportedCriticalError))
                return new ParsingResult(algo, parsingErrors.Errors);
            
            code = code
                .ReplaceDateTimeToInt()
                .ReplaceDateConstants()
                .ReplaceDefines()
                .ReplaceCSharpKeyWords()
                .RemoveDotsFromNames()
                .AddZeroToDecimalNumbers()
                .ReplaceUnknownSymbols()
                .ReplaceMq4RgbColorsToKnownColors()
                .ReplaceColorToInt()
                .ReplaceCAlgoKeyWords()
                .ReplacePrintToMq4Print()
                .RenameFunctions()
                .AddRefModifiers()
                .AddTypeParameterToICustom(out customIndicators);

            HandleProperties(code, algo);
            HandleParameters(code, algo);
            HandleFunctions(code, algo, parsingErrors);
            HandleFields(code, algo);

            algo.Code.ExtractStaticVariablesToFields();
            algo.Code.ReplaceSimpleTypesToMq4Types();
            algo.Code.RenameStandardFunctions();
            algo.Code.AddMq4InitFunctionIfDoesNotExist();
            algo.CustomIndicators = customIndicators;

            return new ParsingResult(algo, parsingErrors.Errors);
        }
        private static AlgoPresenter CreatePresenter(AlgoType algotype)
        {
            string template;

            switch (algotype)
            {
            case AlgoType.Indicator:
                template = new IndicatorTemplateProvider().GetTemplate();
                break;

            default:
                template = new RobotTemplateProvider().GetTemplate();
                break;
            }
            return(new AlgoPresenter(new AlgoBuilder(template)));
        }
Esempio n. 18
0
        public Question_MaxContiguousSum(AlgoType type)
        {
            switch (type)
            {
            case AlgoType.MinesCorrect:
                GetMaxContiguousSum = GetMaxContiguousSumMinesCorrect;
                break;

            case AlgoType.MinesWrong:
                GetMaxContiguousSum = GetMaxContiguousSumMinesWrong;
                break;

            case AlgoType.Kadane:
                GetMaxContiguousSum = GetMaxContiguousSumKadane;
                break;
            }
        }
        public static AlgoType?GetAlgoType(string code, AlgoType defaultValue)
        {
            if (!code.Contains("start"))
            {
                return(null);
            }
            if (RobotKeyWords.Any(code.Contains))
            {
                return(AlgoType.Robot);
            }
            if (defaultValue == AlgoType.Robot)
            {
                return(null);
            }

            return(defaultValue);
        }
Esempio n. 20
0
        public static ISortingAlgo <T> GetSortingAlgo(AlgoType algo)
        {
            switch (algo)
            {
            case AlgoType.Bubble:
                return(new BubbleSort <T>());

            case AlgoType.Insertion:
                return(null);

            case AlgoType.Selection:
                return(new SelectionSort <T>());

            case AlgoType.Merge:
                return(new MergeSort <T>());
            }
            return(null);
        }
Esempio n. 21
0
        public static double GetHashrateMultiplier(AlgoType algoType)
        {
            switch (algoType)
            {
            case AlgoType.Scrypt_jane:
            case AlgoType.Scrypt_og:
            case AlgoType.Scrypt_n:
            case AlgoType.Scrypt:
            case AlgoType.NeoScrypt:
                return(Math.Pow(2, 16));

            case AlgoType.Groestl:
            case AlgoType.Keccak:
            case AlgoType.Fugue:
                return(Math.Pow(2, 8));

            case AlgoType.Blake256:
            case AlgoType.Quark:
            case AlgoType.SHA256:
            case AlgoType.X11:
            case AlgoType.X13:
            case AlgoType.X15:
            case AlgoType.M7M:
            case AlgoType.Qubit:
            case AlgoType.Yescrypt:
            case AlgoType.C11:
            case AlgoType.CryptoNight:
            case AlgoType.Nist5:
            case AlgoType.Skein:
            case AlgoType.SHA1:
            case AlgoType.SHA2:
            case AlgoType.SHA3:
            case AlgoType.Lyra2RE:
            case AlgoType.Shavite3:
            case AlgoType.Hefty1:
                return(1);

            default:
                break;
            }
            return(1);
        }
Esempio n. 22
0
        private ConfigurationManager()
        {
            try
            {
                var config = JsonConvert.DeserializeObject <ConfigFile>(allJson);
                foreach (var item in config.Resources)
                {
                    ResourceType.AddResourceType(item.Name, item.IsFood);
                }
                foreach (var item in config.ProducerUnits)
                {
                    var type = Type.GetType(item.UnitType);
                    if (!ProducerUnits.ContainsKey(type))
                    {
                        ProducerUnits.Add(type, item);
                    }
                }
                foreach (var item in config.ConverterUnits)
                {
                    var type = Type.GetType(item.UnitType);
                    if (!ConverterUnits.ContainsKey(type))
                    {
                        ConverterUnits.Add(type, item);
                    }
                }
                foreach (var item in config.ProducerAndConverterUnits)
                {
                    var type = Type.GetType(item.UnitType);
                    if (!ProducerAndConverterUnits.ContainsKey(type))
                    {
                        ProducerAndConverterUnits.Add(type, item);
                    }
                }
                foreach (var item in config.ConstructionUnits)
                {
                    var type = Type.GetType(item.UnitType);
                    if (!ConstructionUnits.ContainsKey(type))
                    {
                        ConstructionUnits.Add(type, item);
                    }
                }
                foreach (var item in config.DecorBuildings)
                {
                    DecorBuildings.Add(Type.GetType(item.BuildingType), item);
                }
                foreach (var item in config.WorkplaceBuildings)
                {
                    var type = Type.GetType(item.BuildingType);
                    if (!WorkplaceBuildings.ContainsKey(type))
                    {
                        WorkplaceBuildings.Add(Type.GetType(item.BuildingType), item);
                    }
                }
                SatisfactionBoostAlgo        = config.SatisfactionPrice.IncrementAlgoType;
                SatisfactionBoostInitialCost = config.SatisfactionPrice.InitialCost;
                SatisfactionBoostAlgoValue   = config.SatisfactionPrice.AlgoSecondValue;

                foreach (var item in config.SellingPrices)
                {
                    if (!SellingPrices.ContainsKey(item.Key))
                    {
                        SellingPrices.Add(item.Key, item.Value.Select(r => new ResourceAmount(r.Type, r.Amount)).ToList());
                    }
                }
                foreach (var item in config.BuyingPrices)
                {
                    if (!BuyingPrices.ContainsKey(item.Key))
                    {
                        BuyingPrices.Add(item.Key, item.Value.Select(r => new ResourceAmount(r.Type, r.Amount)).ToList());
                    }
                }
                ResearchIncrementAlgo = config.ResearchAlgo;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Serialization error");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
                Debugger.Break();
                return;
            }
        }
Esempio n. 23
0
        public static double CalculateEstimatedShares(double difficulty, AlgoType algoType)
        {
            var shareStatisticMultiplier = GetStatisticMultiplier(algoType);

            return(Math.Round(GetShareMultiplier(algoType) * difficulty, 0) / shareStatisticMultiplier);
        }
Esempio n. 24
0
        // Try min profit squareoff first between 3 - 3.10 time.
        // From 3.10 to 3.15 time if squareoff of all positions is set to true and the ltp diff meets threshold for max loss pct, then do a market order squareoff
        public void TrySquareOffNearEOD(AlgoType algoType)
        {
            // if after 3 pm, then try to square off in at least no profit no loss if possible. cancel the outstanding buys anyway
            if (MarketUtils.IsTimeAfter310())
            {
                var ordPriceType   = OrderPriceType.LIMIT;
                var doUpdateOrders = false;

                // 3.20 - 3.25 pm time. market order type for forced square off given pct loss is within acceptable range
                // do it before 3.15, otherwise broker will try to squareoff on its own anytime between 3.15 - 3.30
                if (MarketUtils.IsTimeAfter320() && !MarketUtils.IsTimeAfter325() && squareOffAllPositionsAtEOD && !isEODMinLossSquareOffMarketOrderUpdated)
                {
                    double ltp;
                    var    errCode = GetLTP(out ltp);

                    if (errCode != BrokerErrorCode.Success)
                    {
                        return;
                    }

                    ordPriceType = OrderPriceType.MARKET;

                    var diff = (ltp - todayOutstandingPrice) / ltp;

                    Trace(string.Format("[Margin EOD]: diff {0} ltp {1} outstandingprice {2} pctMaxLossSquareOffPositions {3} goodPrice {4} ", diff, ltp, todayOutstandingPrice, pctMaxLossSquareOffPositions, goodPrice));

                    if ((Math.Abs(diff) < pctMaxLossSquareOffPositions || diff > 0) && todayOutstandingPrice > goodPrice)
                    {
                        Trace(string.Format("[Margin EOD]: max loss {0}% is less than {1}% and avg outstanding price {2} is greater than good price of {3}. LTP is {4}. Place squareoff @ MARKET.", diff, pctMaxLossSquareOffPositions, todayOutstandingPrice, goodPrice, ltp));
                        doUpdateOrders = true;
                        isEODMinLossSquareOffMarketOrderUpdated = true;
                    }
                }

                // 3.10 - 3.20 pm time. try simple limit order with min profit price. watch until 3.10 pm
                else if (!isEODMinProfitSquareOffLimitOrderUpdated)
                {
                    Trace(string.Format("[Margin EOD]: MinProfit Squareoff and cancel outstanding buy orders"));
                    ordPriceType = OrderPriceType.LIMIT;
                    isEODMinProfitSquareOffLimitOrderUpdated = true;
                    doUpdateOrders = true;
                }

                if (doUpdateOrders)
                {
                    if (algoType == AlgoType.AverageTheBuyThenSell)
                    {
                        // just cancel the outstanding buy order
                        if (!string.IsNullOrEmpty(todayOutstandingBuyOrderRef))
                        {
                            // cancel existing buy order
                            errCode = CancelEquityOrder("[Margin EOD]", ref todayOutstandingBuyOrderRef, EquityOrderType.MARGIN, OrderDirection.BUY);
                        }

                        // bought qty needs square off. there is outstanding sell order, revise the price to try square off
                        if (!string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                        {
                            // cancel existing sell order
                            errCode = CancelEquityOrder("[Margin EOD]", ref todayOutstandingSellOrderRef, EquityOrderType.MARGIN, OrderDirection.SELL);

                            if (errCode == BrokerErrorCode.Success)
                            {
                                // place new sell order, update sell order ref
                                var sellPrice = GetSellPrice(todayOutstandingPrice, false, true);
                                errCode = PlaceEquityOrder(stockCode, OrderPositionTypeEnum.Margin, todayOutstandingQty, todayOutstandingQty, sellPrice.ToString(), ordPriceType, OrderDirection.SELL, EquityOrderType.MARGIN, exchange, "", out todayOutstandingSellOrderRef);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 25
0
        // reads position file: qty avgprice holdingssellorderref
        // gets order and trade book
        // if holdings sell order is executed, then holding qty is updated to 0, and position file is updated with only today outstanding and empty sellorderref
        // holdings data is seperate and today outstanding data is seperate
        // single buy or sell outsanding order at any time is assumed
        // if there is no sell order for holdings then create a sell order and update position file with holdings and sellorderref
        // position file contains only the holding data along with the holding sell order ref. it does not have today's outstanding. Only at EOD if conversion to delivery is done then that is assumed to be holding and written to postion file
        // holding sell order if reqd is placed only once at start in Init, not in loop run. that time iffordeliveryflag is set so that sell price is calculated as per deliverymarkup parameter
        // in normal run , sell orders are placed as per normal marginmarkup parameter
        // today's outstanding is derived from the tradebook and outstanding orders derived from order book. no state is saved outside. day before holdings are present in positions file
        public void Init(AlgoType algoType)
        {
            if (!File.Exists(positionFile))
            {
                File.WriteAllText(positionFile, "");
            }

            // just place squareoff orders for previous days open positions pending for delivery - develop it later

            // Position file always contains the holding qty, holding price and different type of holdings' details (demat/btst, qty, sell order ref) etc
            ReadPositionFile();

            var orders = new Dictionary <string, EquityOrderBookRecord>();
            var trades = new Dictionary <string, EquityTradeBookRecord>();

            // latest (wrt time) trades or orders appear at start of the output
            errCode = broker.GetEquityTradeBookToday(false, stockCode, out trades);
            errCode = broker.GetEquityOrderBookToday(false, true, stockCode, out orders);

            // get all holding qty trades
            var holdingTradesRef = holdingsOrders.Select(h => h.OrderRef);

            // any outstanding qty (buy minus sell trades) today except from holding qty trade
            todayOutstandingQty = trades.Where(t => !holdingTradesRef.Contains(t.Key)).Sum(t => t.Value.Direction == OrderDirection.SELL ? -t.Value.Quantity : t.Value.Quantity);

            var buyTrades = trades.Where(t => t.Value.Direction == OrderDirection.BUY);

            lastBuyPrice     = buyTrades.Any() ? buyTrades.First().Value.Price : holdingOutstandingPrice;
            settlementNumber = buyTrades.Any() ? buyTrades.First().Value.SettlementNumber : "";

            var numOutstandingBuyTrades = todayOutstandingQty > 0 ? todayOutstandingQty / ordQty : 0;

            // these are latest trades taken. each buy trade is for single lot and thus for each lot there is a trade
            todayOutstandingPrice = numOutstandingBuyTrades == 0 ? 0 : buyTrades.Take(numOutstandingBuyTrades).Average(t => t.Value.Price);

            ProcessHoldingSellOrderExecution(trades);

            var buyOrders  = orders.Values.Where(o => o.Direction == OrderDirection.BUY && o.Status == OrderStatus.ORDERED);
            var sellOrders = orders.Values.Where(o => o.Direction == OrderDirection.SELL && o.Status == OrderStatus.ORDERED && !holdingTradesRef.Contains(o.OrderRefenceNumber)); // pick only today's outstanding related sell orders

            // assumed that there is always at max only single outstanding buy order and a at max single outstanding sell order
            todayOutstandingBuyOrderRef  = buyOrders.Any() ? buyOrders.First().OrderRefenceNumber : "";
            todayOutstandingSellOrderRef = sellOrders.Any() ? sellOrders.First().OrderRefenceNumber : "";

            var sellOrder = sellOrders.Any() ? sellOrders.First() : null;

            isFirstBuyOrder = string.IsNullOrEmpty(todayOutstandingBuyOrderRef) && !trades.Where(t => t.Value.Direction == OrderDirection.BUY).Any();

            // if sqoff sell order for holdings is needed then place it
            //assumption is: if there is a holding pending from day before then it would have been converted to delivery
            if (holdingOutstandingQty > 0)
            {
                // get demat and btst listings
                List <EquityDematHoldingRecord> dematHoldings;
                errCode = broker.GetDematAllocation(stockCode, out dematHoldings);
                List <EquityBTSTTradeBookRecord> btstHoldings;
                errCode = broker.GetBTSTListings(stockCode, out btstHoldings);
                List <EquityPendingPositionForDelivery> pendingPositions;
                errCode = broker.GetOpenPositionsPendingForDelivery(stockCode, out pendingPositions);

                // place sq off sell order, update sell order ref
                var    sellPrice    = GetSellPrice(holdingOutstandingPrice, true, false);
                string sellOrderRef = "";
                if (dematHoldings.Any())
                {
                    var dematHolding = dematHoldings.First();
                    if (dematHolding.AvailableQuantity > 0)
                    {
                        errCode = PlaceEquityOrder(stockCode, OrderPositionTypeEnum.Demat, dematHolding.AvailableQuantity, dematHolding.AvailableQuantity, sellPrice.ToString(), OrderPriceType.LIMIT, OrderDirection.SELL, EquityOrderType.DELIVERY, exchange, "", out sellOrderRef);
                        if (errCode == BrokerErrorCode.Success)
                        {
                            holdingsOrders.Add(new HoldingOrder {
                                Type = OrderPositionTypeEnum.Demat, OrderRef = sellOrderRef, Qty = dematHolding.AvailableQuantity, SettlementNumber = ""
                            });
                        }
                    }
                }
                if (btstHoldings.Any())
                {
                    foreach (var btstHolding in btstHoldings)
                    {
                        if (btstHolding.AvailableQuantity > 0)
                        {
                            errCode = PlaceEquityOrder(stockCode, OrderPositionTypeEnum.Btst, btstHolding.AvailableQuantity, btstHolding.AvailableQuantity, sellPrice.ToString(), OrderPriceType.LIMIT, OrderDirection.SELL, EquityOrderType.DELIVERY, exchange, btstHolding.SettlementNumber, out sellOrderRef);
                            if (errCode == BrokerErrorCode.Success)
                            {
                                holdingsOrders.Add(new HoldingOrder {
                                    Type = OrderPositionTypeEnum.Btst, OrderRef = sellOrderRef, Qty = btstHolding.AvailableQuantity, SettlementNumber = btstHolding.SettlementNumber
                                });
                            }
                        }
                    }
                }
                if (pendingPositions.Any())
                {
                    foreach (var pendingPosition in pendingPositions)
                    {
                        if (pendingPosition.AvailableQuantity > 0)
                        {
                            errCode = PlaceEquityOrder(stockCode, OrderPositionTypeEnum.OpenPendingDelivery, pendingPosition.AvailableQuantity, pendingPosition.AvailableQuantity, sellPrice.ToString(), OrderPriceType.LIMIT, OrderDirection.SELL, EquityOrderType.DELIVERY, exchange, pendingPosition.SettlementNumber, out sellOrderRef);
                            if (errCode == BrokerErrorCode.Success)
                            {
                                holdingsOrders.Add(new HoldingOrder {
                                    Type = OrderPositionTypeEnum.OpenPendingDelivery, OrderRef = sellOrderRef, Qty = pendingPosition.AvailableQuantity, SettlementNumber = pendingPosition.SettlementNumber
                                });
                            }
                        }
                    }
                }
                UpdatePositionFile();
            }

            // For AverageTheBuyThenSell algo - place sell order for outstanding qty if not already present
            if (algoType == AlgoType.AverageTheBuyThenSell)
            {
                // check if the outstanding sell order has matching qty or not
                if (sellOrder != null && !string.IsNullOrEmpty(todayOutstandingSellOrderRef) && sellOrder.Quantity < todayOutstandingQty)
                {
                    // Cancel existing sell order
                    errCode = CancelEquityOrder("[Init Update Sell Qty]", ref todayOutstandingSellOrderRef, EquityOrderType.MARGIN, OrderDirection.SELL);
                }

                if (string.IsNullOrEmpty(todayOutstandingSellOrderRef) && todayOutstandingQty > 0)
                {
                    var sellPrice = GetSellPrice(todayOutstandingPrice, false, false);
                    errCode = PlaceEquityOrder(stockCode, OrderPositionTypeEnum.Margin, todayOutstandingQty, todayOutstandingQty, sellPrice.ToString(), OrderPriceType.LIMIT, OrderDirection.SELL, EquityOrderType.MARGIN, exchange, "", out todayOutstandingSellOrderRef);
                }
            }

            todayBuyOrderCount = buyOrders.Count();
        }
Esempio n. 26
0
        public static double GetEstimatedNetworkHashrate(AlgoType algoType, double difficulty, int blocktime)
        {
            var estShares = CalculateEstimatedShares(difficulty, algoType);

            return(CalculateHashrate(estShares, algoType, blocktime));
        }
Esempio n. 27
0
        private static string GetMq4Name(string mq4Code, AlgoType algoType)
        {
            var match = Mq4NameRegex.Match(mq4Code);
            if (!match.Success)
                return "Converted" + algoType.ToString();

            return AlgoNameProvider.GetSimplifiedName(match.Groups["name"].Value, algoType);
        }
 public PeakFinding2D(
     AlgoType algoType)
 {
     _algoType = algoType;
 }
Esempio n. 29
0
        // Try min profit squareoff first between 3 - 3.10 time.
        // From 3.10 to 3.15 time if squareoff of all positions is set to true and the ltp diff meets threshold for max loss pct, then do a market order squareoff
        public void TrySquareOffNearEOD(AlgoType algoType)
        {
            // if after 3 pm, then try to square off in at least no profit no loss if possible. either buy or sell is outstanding
            if (MarketUtils.IsTimeAfter3())
            {
                var ordPriceType   = OrderPriceType.LIMIT;
                var doUpdateOrders = false;

                // 3.10 - 3.15 pm time. market order type for forced square off given pct loss is within acceptable range
                // do it before 3.15, otherwise broker will try to squareoff on its own anytime between 3.15 - 3.30
                if (MarketUtils.IsTimeAfter310() && !MarketUtils.IsTimeAfter315() && squareOffAllPositionsAtEOD && !isEODMinLossSquareOffMarketOrderUpdated)
                {
                    var ltp = GetLTP();
                    ordPriceType = OrderPriceType.MARKET;

                    var diff = Math.Abs((ltp - todayOutstandingPrice) / ltp);
                    if (diff < pctMaxLossSquareOffPositions && todayOutstandingPrice > goodPrice)
                    {
                        Trace(string.Format("TrySquareOffNearEOD: max loss % {0} is within acceptable range of {1} and avg outstanding price {2} is greater than good price of {3}. Update squareoff at MARKET price type.", diff, pctMaxLossSquareOffPositions, todayOutstandingPrice, goodPrice));
                        doUpdateOrders = true;
                        isEODMinLossSquareOffMarketOrderUpdated = true;
                    }
                }

                // 3 - 3.10 pm time. try simple limit order with min profit price
                else if (!isEODMinProfitSquareOffLimitOrderUpdated)
                {
                    Trace(string.Format("TrySquareOffNearEOD: Update squareoff LIMIT order with min profit % price or cancel outstanding orders"));
                    ordPriceType = OrderPriceType.LIMIT;
                    isEODMinProfitSquareOffLimitOrderUpdated = true;
                    doUpdateOrders = true;
                }

                if (doUpdateOrders)
                {
                    if (algoType == AlgoType.AverageTheBuyThenSell)
                    {
                        // just cancel the outstanding buy order
                        if (!string.IsNullOrEmpty(todayOutstandingBuyOrderRef))
                        {
                            // cancel existing buy order
                            errCode = CancelEquityOrder("(EOD squareoff) @ " + ordPriceType, ref todayOutstandingBuyOrderRef, OrderDirection.BUY);
                        }

                        // bought qty needs square off. there is outstanding sell order, revise the price to try square off
                        if (!string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                        {
                            // cancel existing sell order
                            errCode = CancelEquityOrder("(EOD squareoff) @ " + ordPriceType, ref todayOutstandingSellOrderRef, OrderDirection.SELL);

                            if (errCode == BrokerErrorCode.Success)
                            {
                                todayOutstandingSellOrderRef = "";
                                // place new sell order, update sell order ref
                                Trace("Placing EOD squareoff updated order");
                                var sellPrice = GetSellPrice(todayOutstandingPrice, false, true);
                                errCode = PlaceEquityOrder(stockCode, todayOutstandingQty, sellPrice.ToString(), ordPriceType, OrderDirection.SELL, EquityOrderType.MARGIN, exchange, out todayOutstandingSellOrderRef);
                            }
                        }
                    }
                    else if (algoType == AlgoType.SimultaneousBuySell)
                    {
                        // if there is an outstanding order pair, just cancel both
                        if (!string.IsNullOrEmpty(todayOutstandingBuyOrderRef) && !string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                        {
                            // cancel existing sell order
                            errCode = CancelEquityOrder("(EOD squareoff) @ " + ordPriceType, ref todayOutstandingSellOrderRef, OrderDirection.SELL);

                            // cancel existing buy order
                            errCode = CancelEquityOrder("(EOD squareoff) @ " + ordPriceType, ref todayOutstandingBuyOrderRef, OrderDirection.BUY);
                        }

                        // bought qty needs square off.  there is outstanding sell order, revise the price to try square off
                        else if (string.IsNullOrEmpty(todayOutstandingBuyOrderRef) && !string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                        {
                            // cancel existing sell order
                            errCode = CancelEquityOrder("(EOD squareoff) @ " + ordPriceType, ref todayOutstandingSellOrderRef, OrderDirection.SELL);

                            if (errCode == BrokerErrorCode.Success)
                            {
                                todayOutstandingSellOrderRef = "";
                                // place new sell order, update sell order ref
                                Trace("Placing EOD squareoff updated order");
                                var sellPrice = GetSellPrice(todayOutstandingPrice, false, true);
                                errCode = PlaceEquityOrder(stockCode, ordQty, sellPrice.ToString(), ordPriceType, OrderDirection.SELL, EquityOrderType.MARGIN, exchange, out todayOutstandingSellOrderRef);
                            }
                        }

                        // sold qty needs square off. there is outstanding buy order, revise the price to try square off
                        else if (string.IsNullOrEmpty(todayOutstandingSellOrderRef) && !string.IsNullOrEmpty(todayOutstandingBuyOrderRef))
                        {
                            // cancel existing buy order
                            errCode = CancelEquityOrder("(EOD squareoff) @ " + ordPriceType, ref todayOutstandingBuyOrderRef, OrderDirection.BUY);

                            if (errCode == BrokerErrorCode.Success)
                            {
                                todayOutstandingBuyOrderRef = "";
                                // place new buy order, update buy order ref
                                Trace("Placing EOD squareoff updated order");
                                var buyPrice = GetBuySquareOffPrice(todayOutstandingPrice);
                                errCode = PlaceEquityOrder(stockCode, ordQty, buyPrice.ToString(), ordPriceType, OrderDirection.BUY, EquityOrderType.MARGIN, exchange, out todayOutstandingBuyOrderRef);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 30
0
 public static string PoolConnection(AlgoType algoType)
 {
     return($"poolconnection-{algoType}");
 }
Esempio n. 31
0
        // reads position file: qty avgprice holdingssellorderref
        // gets order and trade book
        // if holdings sell order is executed, then holding qty is updated to 0, and position file is updated with only today outstanding and empty sellorderref
        // holdings data is seperate and today outstanding data is seperate
        // single buy or sell outsanding order at any time is assumed
        // if there is no sell order for holdings then create a sell order and update position file with holdings and sellorderref
        // position file contains only the holding data along with the holding sell order ref. it does not have today's outstanding. Only at EOD if conversion to delivery is done then that is assumed to be holding and written to postion file
        // holding sell order if reqd is placed only once at start in Init, not in loop run. that time iffordeliveryflag is set so that sell price is calculated as per deliverymarkup parameter
        // in normal run , sell orders are placed as per normal marginmarkup parameter
        // today's outstanding is derived from the tradebook and outstanding orders derived from order book. no state is saved outside. day before holdings are present in positions file
        public void Init(AlgoType algoType)
        {
            if (!File.Exists(positionFile))
            {
                File.WriteAllText(positionFile, "");
            }

            // Position file always contains the holding qty, holding price and holding sell order ref
            ReadPositionFile();

            var orders = new Dictionary <string, EquityOrderBookRecord>();
            var trades = new Dictionary <string, EquityTradeBookRecord>();

            // latest (wrt time) trades or orders appear at start of the output
            errCode = broker.GetEquityTradeBookToday(false, stockCode, out trades);
            errCode = broker.GetEquityOrderBookToday(false, true, stockCode, out orders);

            // any outstanding qty (buy minus sell trades) today except from holding qty trade
            todayOutstandingQty = trades.Where(t => t.Key != holdingSellOrderRef).Sum(t => t.Value.Direction == OrderDirection.SELL ? -t.Value.Quantity : t.Value.Quantity);

            var buyTrades = trades.Where(t => t.Value.Direction == OrderDirection.BUY);

            lastBuyPrice = buyTrades.Any() ? buyTrades.First().Value.Price : 0;

            var numOutstandingBuyTrades = todayOutstandingQty > 0 ? todayOutstandingQty / ordQty : 0;

            // these are latest trades taken. each buy trade is for single lot and thus for each lot there is a trade
            todayOutstandingPrice = numOutstandingBuyTrades == 0 ? 0 : buyTrades.Take(numOutstandingBuyTrades).Average(t => t.Value.Price);

            if (trades.ContainsKey(holdingSellOrderRef))
            {
                ProcessHoldingSellOrderExecution();
            }

            var buyOrders  = orders.Values.Where(o => o.Direction == OrderDirection.BUY && o.Status == OrderStatus.ORDERED);
            var sellOrders = orders.Values.Where(o => o.Direction == OrderDirection.SELL && o.Status == OrderStatus.ORDERED && o.OrderRefenceNumber != holdingSellOrderRef); // pick only today's outstanding related sell orders

            // assumed that there is always at max only single outstanding buy order and a at max single outstanding sell order
            todayOutstandingBuyOrderRef  = buyOrders.Any() ? buyOrders.First().OrderRefenceNumber : "";
            todayOutstandingSellOrderRef = sellOrders.Any() ? sellOrders.First().OrderRefenceNumber : "";

            isFirstBuyOrder = string.IsNullOrEmpty(todayOutstandingBuyOrderRef) && !trades.Where(t => t.Value.Direction == OrderDirection.BUY).Any();

            // if sqoff sell order for holdings is needed then place it
            //assumption is: if there is a holding pending from day before then it would have been converted to delivery
            if (holdingOutstandingQty > 0 && string.IsNullOrEmpty(holdingSellOrderRef))
            {
                // place sq off sell order, update sell order ref
                var sellPrice = GetSellPrice(holdingOutstandingPrice, true);
                errCode = PlaceEquityOrder(stockCode, holdingOutstandingQty, sellPrice.ToString(), OrderPriceType.LIMIT, OrderDirection.SELL, EquityOrderType.DELIVERY, exchange, out holdingSellOrderRef);
                if (errCode == BrokerErrorCode.Success)
                {
                    UpdatePositionFile(holdingOutstandingQty, holdingOutstandingPrice, holdingSellOrderRef);
                    Trace(string.Format(orderTraceFormat, stockCode, "cash holding squareoff sell", holdingOutstandingQty, sellPrice, "CASH", errCode, OrderPriceType.LIMIT));
                }
            }

            // For AverageTheBuyThenSell algo - place sell order for outstanding qty if not already present
            if (algoType == AlgoType.AverageTheBuyThenSell)
            {
                if (string.IsNullOrEmpty(todayOutstandingSellOrderRef) && todayOutstandingQty > 0)
                {
                    var sellPrice = GetSellPrice(todayOutstandingPrice, false);
                    errCode = PlaceEquityOrder(stockCode, todayOutstandingQty, sellPrice.ToString(), OrderPriceType.LIMIT, OrderDirection.SELL, EquityOrderType.MARGIN, exchange, out todayOutstandingSellOrderRef);
                }
            }

            buyOrderCount = buyOrders.Count();
        }