Example #1
0
        public bool Equals(ISpatial2DThing <T> other)
        {
            if (other == null)
            {
                return(false);
            }

            if (ReferenceEquals(other, this))
            {
                return(true);
            }

            if (other.Data == null && Data != null)
            {
                return(false);
            }

            if (!other.Data.Equals(Data))
            {
                return(false);
            }

            if (!string.Equals(Id, other.Id))
            {
                return(false);
            }

            if (other.Positions.Count() != Positions.Count())
            {
                return(false);
            }

            return(other.Positions.Zip(Positions, (p1, p2) => p1.Equals(p2)).All(x => x));
        }
Example #2
0
 private void SetDefault()
 {
     if (RentValues.Count() == 0 && Positions.Count() == 0 && Users.Count() == 0)
     {
         Positions.Add(new Position()
         {
             Name = "јдминистратор"
         });
         Positions.Add(new Position()
         {
             Name = "ѕользователь"
         });
         Users.Add(new User()
         {
             FirstName = "јдмин", LastName = "јдмин", Login = "******", Password = "******", PositionId = 1
         });
         RentValues.Add(new RentValue {
             Name = "—уточный", Price = 10
         });
         RentValues.Add(new RentValue {
             Name = "ћес¤чный", Price = 100,
         });
         this.SaveChanges();
     }
 }
        private string GenerateStatusText()
        {
            var statusText    = "";
            var buyPositions  = "";
            var sellPositions = "";
            var spread        = "";
            var buyDistance   = "";
            var sellDistance  = "";

            spread        = "\nSpread = " + Math.Round(Symbol.Spread / Symbol.PipSize, 1);
            buyPositions  = "\nBuy Positions = " + Positions.Count(x => x.TradeType == TradeType.Buy && x.SymbolName == SymbolName && x.Label == ThiscBotLabel);
            sellPositions = "\nSell Positions = " + Positions.Count(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel);
            if (Positions.Count(x => x.TradeType == TradeType.Buy && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) > 0)
            {
                var averageBuyFromCurrent = Math.Round((Positions.Where(x => x.TradeType == TradeType.Buy && x.SymbolName == SymbolName && x.Label == ThiscBotLabel).Average(x => x.EntryPrice) - Symbol.Bid) / Symbol.PipSize, 1);
                buyDistance = "\nBuy Target Away = " + averageBuyFromCurrent;
            }
            if (Positions.Count(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) > 0)
            {
                var averageSellFromCurrent = Math.Round((Symbol.Ask - Positions.Where(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel).Average(x => x.EntryPrice)) / Symbol.PipSize, 1);
                sellDistance = "\nSell Target Away = " + averageSellFromCurrent;
            }
            if (Symbol.Spread / Symbol.PipSize > MaxSpread)
            {
                statusText = "MAX SPREAD EXCEED";
            }
            else
            {
                statusText = ThiscBotLabel + buyPositions + spread + sellPositions + buyDistance + sellDistance;
            }
            return(statusText);
        }
        public BasketPositionEditMessage BuildMessage()
        {
            using (MarketBotDbContext db = new MarketBotDbContext())
            {
                Positions = db.Basket.Where(b => b.FollowerId == FollowerId && b.ProductId == ProductId).Include(b => b.Product).ToList();
                Product   = db.Product.Where(p => p.Id == ProductId).FirstOrDefault();
            }

            if (Positions != null && Positions.Count() > 0)
            {
                base.TextMessage = Positions.FirstOrDefault().Product.Name + " " + Positions.Count() + " шт.";
                AddBtn           = new InlineKeyboardCallbackButton("+", BuildCallData(Bot.BasketBot.AddProductToBasketCmd, Bot.BasketBot.ModuleName, Positions.FirstOrDefault().ProductId));
                RemoveBtn        = new InlineKeyboardCallbackButton("-", BuildCallData(Bot.BasketBot.RemoveProductFromBasketCmd, Bot.BasketBot.ModuleName, Positions.FirstOrDefault().ProductId));
                SetInlineKeyBoard();
            }

            else // Пользователь удалил последнюю еденицу этого товара. Значит теперь его 0 шт.
            {
                base.TextMessage = Product.Name + " 0 шт.";
                AddBtn           = new InlineKeyboardCallbackButton("+", BuildCallData(Bot.BasketBot.AddProductToBasketCmd, Bot.BasketBot.ModuleName, ProductId));
                RemoveBtn        = new InlineKeyboardCallbackButton("-", BuildCallData(Bot.BasketBot.RemoveProductFromBasketCmd, Bot.BasketBot.ModuleName, ProductId));
                SetInlineKeyBoard();
            }

            return(this);
        }
Example #5
0
        private void NewOpenOrFixInLength()
        {
            try
            {
                Print(">>NewOpenOrFixInLength");

                //มีออเดอร์ค้างไหม คือ ไม่่มีเข้าลูปเริ่มต้นวางไม้อย่างง่ายๆเลย ปล.ต้องไม่นับรวมไม้จากสูตรอื่น
                if (Positions.Count(x => x.SymbolCode == Symbol.Code && x.Comment == CommentSytem) == 0)
                {
                    InitialPendingOrder();
                }
                else
                {
                    //Task fix = Task.Factory.StartNew(() => FixInPendingLength());
                    //Task clean = Task.Factory.StartNew(() => CleanDupOrderAndPending());

                    //Task tPlusBuy = Task.Factory.StartNew(() => CalTP_SL_PlusWay_BuyWay_OnOpened());
                    //Task tPlusSell = Task.Factory.StartNew(() => CalTP_SL_PlusWay_SellWay_OnOpened());
                    //tPlusBuy.Wait();
                    //tPlusSell.Wait();

                    //Cal_TpSl_MinusWay(TradeType.Buy);
                    //Cal_TpSl_MinusWay(TradeType.Sell);

                    //fix.Wait();
                    //clean.Wait();
                }

                Print("-----NewOpenOrFixInLength-----");
            } catch (Exception ex)
            {
                Print("Error NewOpenOrFixInLength >> " + ex.Message);
            }
        }
Example #6
0
        /// <summary>
        /// 检查该点存在,且数量是1
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual bool ExistsPos(string name)
        {
            if (Positions.Exists(p => p.Name == name))
            {
                return(Positions.Count(p => p.Name == name) == 1);
            }

            return(true);
        }
Example #7
0
        public void Recalculate(double newValue)
        {
            double amountPerPortfolio = newValue / Positions.Count();

            foreach (var position in Positions)
            {
                position.Amount = amountPerPortfolio;
            }
            RaisePropertyChanged("TotalValue");
        }
 private bool IsThePositionAuthorized()
 {
     if (SinglePositionOnly)
     {
         return(Positions.Count(x => x.SymbolCode == Symbol.Code) <= 0);
     }
     else
     {
         return(true);
     }
 }
Example #9
0
        internal bool IsTimeToSell(Candlestick LastClosed)
        {
            bool bRet = (!bsBot.EnableBB || (bsBot.EnableBB && LastClosed.High > bb.Top.Last(1))) &&
                        (!bsBot.EnableRSI || (bsBot.EnableRSI && rsi.Result.Last(1) > bsBot.RSIUpperLevel)) &&
                        (!bsBot.EnableADX || (bsBot.EnableADX && adx.ADX.Last(1) < bsBot.DMSLevel)) &&
                        (bsBot.Aggressive || (!bsBot.Aggressive && Positions.Count() == 0));

            if (bRet)
            {
                bsBot.Print("LastClosed.High: {0} > BB Top: {1}, RSI: {2} > RSIUpperLevel: {3}", LastClosed.High, bb.Top.Last(1), rsi.Result.Last(1), bsBot.RSIUpperLevel);
            }
            return(bRet);
        }
Example #10
0
        internal bool IsTimeToBuy(Candlestick LastClosed)
        {
            bool bRet = (!bsBot.EnableBB || (bsBot.EnableBB && LastClosed.Low < bb.Bottom.Last(1))) &&
                        (!bsBot.EnableRSI || (bsBot.EnableRSI && rsi.Result.Last(1) < bsBot.RSILowerLevel)) &&
                        (!bsBot.EnableADX || (bsBot.EnableADX && adx.ADX.Last(1) < bsBot.DMSLevel)) &&
                        (bsBot.Aggressive || (!bsBot.Aggressive && Positions.Count() == 0));

            if (bRet)
            {
                bsBot.Print("LastClosed.Low: {0} < BB Bottom: {1}, RSI: {2} < RSILowerLevel: {3}", LastClosed.Low, bb.Bottom.Last(1), rsi.Result.Last(1), bsBot.RSILowerLevel);
            }
            return(bRet);
        }
        protected override void OnTick()
        {
            // Close all buy positions if all buy positions' target profit is met
            if (Positions.Count(x => x.TradeType == TradeType.Buy && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) > 0)
            {
                if (Positions.Where(x => x.TradeType == TradeType.Buy && x.SymbolName == SymbolName && x.Label == ThiscBotLabel).Average(x => x.NetProfit) >= FirstVolume * AverageTakeProfit * Symbol.PipSize)
                {
                    foreach (var position in Positions)
                    {
                        if (position.TradeType == TradeType.Buy && position.SymbolName == SymbolName && position.Label == ThiscBotLabel)
                        {
                            ClosePosition(position);
                        }
                    }
                }
            }
            // Close all sell positions if all sell positions' target profit is met
            if (Positions.Count(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) > 0)
            {
                if (Positions.Where(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel).Average(x => x.NetProfit) >= FirstVolume * AverageTakeProfit * Symbol.PipSize)
                {
                    foreach (var position in Positions)
                    {
                        if (position.TradeType == TradeType.Sell && position.SymbolName == SymbolName && position.Label == ThiscBotLabel)
                        {
                            ClosePosition(position);
                        }
                    }
                }
            }
            // Conditions check before process trade
            if (Symbol.Spread / Symbol.PipSize <= MaxSpread)
            {
                if (Positions.Count(x => x.TradeType == TradeType.Buy && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) < MaxOpenBuy)
                {
                    ProcessBuy();
                }
                if (Positions.Count(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) < MaxOpenSell)
                {
                    ProcessSell();
                }
            }

            if (!this.IsBacktesting)
            {
                DisplayStatusOnChart();
            }
        }
 private void ProcessSell()
 {
     if (Positions.Count(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) == 0 && MarketSeries.Close.Last(2) > MarketSeries.Close.Last(1))
     {
         ExecuteMarketOrder(TradeType.Sell, SymbolName, FirstVolume, ThiscBotLabel, StopLossPips, null);
         LastSellTradeTime = MarketSeries.OpenTime.Last(0);
     }
     if (Positions.Count(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) > 0)
     {
         if (Symbol.Bid > (Positions.Where(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel).Max(x => x.EntryPrice) + PipStep * Symbol.PipSize) && LastSellTradeTime != MarketSeries.OpenTime.Last(0))
         {
             ExecuteMarketOrder(TradeType.Sell, SymbolName, CalculateVolume(TradeType.Sell), ThiscBotLabel, StopLossPips, null);
             LastSellTradeTime = MarketSeries.OpenTime.Last(0);
         }
     }
 }
Example #13
0
        public async Task Perform_ActionPhase()
        {
            // If there is a Position, you are to perform Kagari Protection
            if (Positions?.Count() > 0)
            {
                var actualPos = Positions.ElementAt(0);

                // Before anything, Kotori will establish a new Presence in that area, to set up a Barrier.
                var newPresence = new Presence()
                {
                    Attack    = 0,
                    Protect   = 10,
                    Invisible = true,
                    Role      = this
                };
                GameMap.GameMap[actualPos.X, actualPos.Y].Add(newPresence);


                Queue += new Action(() =>
                {
                    if (GameMap.PoisonedTiles.Contains(actualPos))
                    {
                        Status = GameRoleStatus.Poisoned;
                    }
                    if (GameMap.GameMap[actualPos.X, actualPos.Y].Find(x => x.Role.Faction == Faction.Guardian) != null &&
                        GameMap.GameMap[actualPos.X, actualPos.Y].Find(x => x.Role.Faction == Faction.Gaia) != null)
                    {
                        // Kotori's Scouting ability
                        var allOtherRoles = GameMap.GameMap[actualPos.X, actualPos.Y].Select(x => x.Role).Except(new IGameRole[] { this });
                        foreach (var role in allOtherRoles)
                        {
                            role.WhoKnowsYou.Add(this);
                        }
                    }
                    if (Status == GameRoleStatus.Poisoned)
                    {
                        HP -= GameMap.RNG.Next(1);
                    }
                    if (HP < 1)
                    {
                        Died(new RoleContext());
                    }
                });
            }
        }
        private int GetPositionsSide()
        {
            int result = -1;

            int buySide  = Positions.Count(position1 => position1.Label == cBotLabel && position1.TradeType == TradeType.Buy);
            int sellSide = Positions.Count(position1 => position1.Label == cBotLabel && position1.TradeType == TradeType.Sell);

            if (buySide == PositionsCount)
            {
                result = 0;
            }
            if (sellSide == PositionsCount)
            {
                result = 1;
            }

            return(result);
        }
        protected override void OnPositionOpened(Position openedPosition)
        {
            double?stopLossPrice   = null;
            double?takeProfitPrice = null;

            // Checks only the positions opened by this robot
            if (Positions.Count(position1 => position1.Label == cBotLabel) == 1)
            {
                _position = openedPosition;

                if (_position.TradeType == TradeType.Buy)
                {
                    takeProfitPrice = _position.EntryPrice + TakeProfit * Symbol.TickSize;
                }

                if (_position.TradeType == TradeType.Sell)
                {
                    takeProfitPrice = _position.EntryPrice - TakeProfit * Symbol.TickSize;
                }
            }
            else
            {
                switch (GetPositionsSide())
                {
                case 0:
                    takeProfitPrice = GetAveragePrice(TradeType.Buy) + TakeProfit * Symbol.TickSize;
                    break;

                case 1:
                    takeProfitPrice = GetAveragePrice(TradeType.Sell) - TakeProfit * Symbol.TickSize;
                    break;
                }
            }
            // Checks only the positions opened by this robot
            foreach (var position1 in Positions.Where(position1 => position1.Label == cBotLabel))
            {
                _position = position1;

                if (stopLossPrice != null || takeProfitPrice != null)
                {
                    ModifyPosition(_position, _position.StopLoss, takeProfitPrice);
                }
            }
        }
        /// <summary>
        /// Updates the instrument data for the portfolio and populates a collection of daily returns
        /// </summary>
        /// <param name="portfolio"></param>
        private void UpdateCurrentPortfolioPrices(Portfolio portfolio)
        {
            HistoricalReturnSeries = new List <Analytic>();
            if (Positions.Count() > 0)
            {
                foreach (Position position in Positions)
                {
                    UpdatePositionInstrumentData(position);
                    CalculateHistoricalReturn(position);
                }


                HistoricalReturnSeries = PortfolioAnalytics.CombineAnalyticsInParallel(CombinedAnalytic).ToList();
            }

            else
            {
                HistoricalReturnSeries.Clear();
            }
        }
Example #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ruleNumber"></param>
        /// <param name="maxIterations"></param>
        /// <returns></returns>
        public Task <bool> TrainANFIS(int ruleNumber, int maxIterations, bool useAnalicitalOutcomeForTraining = false)
        {
            return(Task.Run(() => {
                if (!IsDataSetCalculated)
                {
                    throw new ApplicationException("DataSet is not calculated or provided.");
                }

                var sampleSize = Positions.Count() - 1;
                var dynamicObj = useAnalicitalOutcomeForTraining ? Positions.Select(x => new { Point = x, KinematicOutCome = CalculateArmJoint(x).GetAwaiter().GetResult().FirstOrDefault() }) : null;

                var input = useAnalicitalOutcomeForTraining
                                                                ? dynamicObj.Select(x => x.Point).ConvertToANFISParameter()
                                                                : Positions.ConvertToANFISParameter();
                var theta1ANFIS = Task.Run(() => {
                    var sPropTheta1 = new StochasticQprop(sampleSize);
                    var extractorForTheta1 = new KMEANSExtractorIO(ruleNumber);
                    var expectedOutcome = useAnalicitalOutcomeForTraining
                                                                                        ? dynamicObj.Select(x => new[] { x.KinematicOutCome.Theta1.ConvertRadiansToDegrees() }).ToArray()
                                                                                        : AnglesGrid.First().ConvertToANFISParameter();
                    Theta1ANFIS = ANFISBuilder <GaussianRule> .Build(input,
                                                                     expectedOutcome, extractorForTheta1, sPropTheta1, maxIterations);
                });
                var theta2ANFIS = Task.Run(() => {
                    var sPropTheta2 = new StochasticQprop(sampleSize);
                    var extractorForTheta2 = new KMEANSExtractorIO(ruleNumber);
                    var expectedOutcome2 = useAnalicitalOutcomeForTraining
                                                                                ? dynamicObj.Select(x => new[] { x.KinematicOutCome.Theta2.ConvertRadiansToDegrees() }).ToArray()
                                                                                : AnglesGrid.Last().ConvertToANFISParameter();

                    Theta2ANFIS = ANFISBuilder <GaussianRule> .Build(input,
                                                                     expectedOutcome2, extractorForTheta2, sPropTheta2, maxIterations);
                });

                Task.WaitAll(theta1ANFIS, theta2ANFIS);
                IsANFISTrained = true;
                return true;
            }));
        }
 private void DisplayStatusOnChart()
 {
     if (Positions.Count(x => x.TradeType == TradeType.Buy && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) > 1)
     {
         var y = Positions.Where(x => x.TradeType == TradeType.Buy && x.SymbolName == SymbolName && x.Label == ThiscBotLabel).Average(x => x.EntryPrice);
         Chart.DrawHorizontalLine("bpoint", y, Color.Yellow, 2, LineStyle.Dots);
     }
     else
     {
         Chart.RemoveObject("bpoint");
     }
     if (Positions.Count(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel) > 1)
     {
         var z = Positions.Where(x => x.TradeType == TradeType.Sell && x.SymbolName == SymbolName && x.Label == ThiscBotLabel).Average(x => x.EntryPrice);
         Chart.DrawHorizontalLine("spoint", z, Color.HotPink, 2, LineStyle.Dots);
     }
     else
     {
         Chart.RemoveObject("spoint");
     }
     Chart.DrawStaticText("pan", GenerateStatusText(), VerticalAlignment.Top, HorizontalAlignment.Left, Color.Tomato);
 }
        /// <summary>Called when new data is received</summary>
        public override void Step()
        {
            base.Step();
            if (Instrument.NewCandle)
            {
                Dump();
            }

            var mcs             = Instrument.MCS;
            var price           = Instrument.LatestPrice;
            var trend_sign_slow = TrendSignSlow;
            var trend_sign_fast = TrendSignFast;

            // On a significantly extreme price level, buy/sell
            // For opening positions, use Bid when the price is high, Ask when the price is low.
            var sign = -ProbSign;
            var prob = Prob(sign);

            if (Math.Abs(prob) > OpenPositionProb)
            {
                // Todo:
                // The TrendSignFast is preventing trades being taken
                // If this worked it would offset the bad trades at MA crosses
                Dump();

                // Buy the lows, Sell the highs
                var ep   = Instrument.CurrentPrice(sign);
                var risk = Risk / 2;                 // Divide the risk amongst the number of positions that can be opened (1 in each direction)
                Debugging.Trace("Entry Trigger - {0} - prob={1:N3}".Fmt(sign > 0 ? "Buy" : "Sell", prob));
                Debugging.Trace(" FastTrend = {0}, SlowTrend = {1}".Fmt(trend_sign_fast, trend_sign_slow));

                for (;;)
                {
                    // Only allow one trade in each direction using this method
                    if (Positions.Count(x => x.Sign() == sign) != 0)
                    {
                        Debugging.Trace("  -Position with this sign already exists");
                        break;
                    }
                    Debugging.Trace("  +No existing {0} position".Fmt(sign));

                    // Only open positions in the direction of the trend
                    if (sign == -trend_sign_fast)
                    {
                        Debugging.Trace("  -Against the trend ({0})".Fmt(trend_sign_fast));
                        break;
                    }
                    Debugging.Trace("  +Not against the trend ({0} vs. {1})".Fmt(sign, trend_sign_fast));

                    // Don't open positions too close together
                    if (Broker.NearbyPositions(Label, ep, Instrument.MCS * MinTradeSeparation, sign))
                    {
                        Debugging.Trace("  -Nearby trades with the same sign ({0})".Fmt(sign));
                        break;
                    }
                    Debugging.Trace("  +No nearby trades with the same sign ({0})".Fmt(sign));

                    // Only open positions when the recent price has been heading in the direction we want to trade
                    var price_trend = Instrument.HighRes.FirstDerivative(-1) / Instrument.PipSize;
                    if (Math.Sign(price_trend) == -sign)
                    {
                        Debugging.Trace("  -Price trend ({0:N3}) against trade sign ({1})".Fmt(price_trend, sign));
                        break;
                    }
                    Debugging.Trace("  +Price trend ({0:N3} pips/tick) matches trade sign ({1})".Fmt(price_trend, sign));

                    // Don't open a position if the MA's look like they're about to cross
                    // in a direction that would make the trade against the trend.
                    var next_cross_idx = NextCrossIndex;
                    var ma_cross_sign  = MA0[0].CompareTo(MA1[0]);
                    if (next_cross_idx != null && next_cross_idx.Value < 2.5 && ma_cross_sign == sign)
                    {
                        Debugging.Trace("  -MA cross predicted in {0:N3} candles".Fmt(next_cross_idx.Value));
                        break;
                    }
                    Debugging.Trace("  +No MA cross from {0} to {1} predicted soon ({2})".Fmt(ma_cross_sign, -ma_cross_sign, next_cross_idx != null ? ((double)next_cross_idx.Value).ToString("N3") : ">5"));

                    // Choose a SL based on SnR levels and the slow MA
                    var rel = Math.Abs(ep - MA1[0]) + mcs;

                    // Create the positions
                    var tt    = CAlgo.SignToTradeType(sign);
                    var sl    = ep - sign * rel;
                    var tp    = ep + sign * rel * 1.5;
                    var vol   = Broker.ChooseVolume(Instrument, rel, risk: risk);
                    var trade = new Trade(Instrument, tt, Label, ep, sl, tp, vol, result: Trade.EResult.Open);
                    //Debugging.LogTrade(trade);
                    Broker.CreateOrder(trade);
                    break;
                }
            }
        }
        public void LoadPositionFile(ILogger writer)
        {
            if (Positions == null)
            {
                Positions = new List <GPSPositionDataLine>();
            }
            else
            {
                Positions.Clear();
            }

            string[] files = Directory.GetFiles(project.Folder + "\\" + this.SubFolder, "*.pos");
            if (files.Count() > 0)
            {
                foreach (string fpath in files)
                {
                    using (StreamReader reader = File.OpenText(fpath))
                    {
                        // skip header
                        for (int k = 0; k < 24; k++)
                        {
                            reader.ReadLine();
                        }

                        String header = reader.ReadLine();
                        double offset = 0;
                        if (header.Contains("GPST"))
                        {
                            //offset = project.GPSTLeapSeconds;
                        }

                        String line = "";
                        while ((line = reader.ReadLine()) != null)
                        {
                            string[] linesplt = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                            // get time
                            string[] datesplt = linesplt[0].Split('/');
                            string[] timesplt = linesplt[1].Split(':');
                            DateTime dt       = new DateTime(Convert.ToInt32(datesplt[0]), Convert.ToInt32(datesplt[1]), Convert.ToInt32(datesplt[2]),
                                                             Convert.ToInt32(timesplt[0]), Convert.ToInt32(timesplt[1]), 0);
                            dt = dt.AddSeconds(Convert.ToDouble(timesplt[2]) + offset);
                            GPSPositionDataLine dataLine = new GPSPositionDataLine(dt, TimeType.GPS);

                            //get coors
                            int    latd  = Convert.ToInt32(linesplt[2]);
                            int    lath  = Convert.ToInt32(linesplt[3]);
                            double latss = Convert.ToDouble(linesplt[4]);

                            double lat = (double)latd + (double)lath / 60.0 + (double)latss / 3600.0;
                            if (latd < 0)
                            {
                                lat = (double)latd - (double)lath / 60.0 - (double)latss / 3600.0;
                            }

                            dataLine.Lat = lat;

                            int    lond  = Convert.ToInt32(linesplt[5]);
                            int    lonh  = Convert.ToInt32(linesplt[6]);
                            double lonss = Convert.ToDouble(linesplt[7]);
                            double lon   = (double)lond + (double)lonh / 60.0 + (double)lonss / 3600.0;
                            if (lond < 0)
                            {
                                lon = (double)lond - (double)lonh / 60.0 - (double)lonss / 3600.0;
                            }
                            dataLine.Lon = lon;


                            double height = Convert.ToDouble(linesplt[8]);
                            dataLine.Height = height;

                            double q = Convert.ToInt32(linesplt[9]);
                            dataLine.Quality = q;

                            this.Positions.Add(dataLine);
                        }
                    }
                }
            }

            Positions.Sort((x, y) => DateTime.Compare(x.TimeStamp, y.TimeStamp));
            if ((Positions.Count) == 0)
            {
                writer.WriteLineWarning("No postion file is found or no coordiantes!");
            }
            {
                writer.WriteLineInfo("\t            # of position entries : " + Positions.Count());
                writer.WriteLineInfo("\t                   First position : " + Positions.Min(x => x.TimeStamp));
                writer.WriteLineInfo("\t                    Last position : " + Positions.Max(x => x.TimeStamp));
            }
        }
Example #21
0
        /// <summary>Called when new data is received</summary>
        public override void Step()
        {
            base.Step();
            if (!Instrument.NewCandle)
            {
                return;
            }

            var mcs = Instrument.MCS;

            // If there is an existing position, wait for it to close
            if (Positions.Count() >= MaxPositions)
            {
                return;
            }

            // If there is no price channel
            if (Channel == null)
            {
                return;
            }

            // Cancel any pending orders and replace them with new ones based on this channel
            Broker.CancelAllPendingOrders(Label);

            Dump();

            // The Channel
            var chan = Channel.Value;
            var risk = Risk / MaxPositions;
            var sign = chan.PrecedingTrendSign;

            //		// Create a pending order on the side opposite the preceding trend
            //		var ep = sign > 0 ? chan.Price.End + 0.5*mcs : chan.Price.Beg - 0.5*mcs;
            //		var sl = (QuoteCurrency?)null;//sign > 0 ? chan.Price.Beg : chan.Price.End;
            //		var tp = (QuoteCurrency?)null;//ep + sign * Math.Abs(ep - sl);
            //		var sl_rel = 5*mcs;//Math.Abs(ep - sl);
            //		var vol = Broker.ChooseVolume(Instrument, sl_rel, risk:risk);
            //		var trade = new Trade(Instrument, CAlgo.SignToTradeType(chan.PrecedingTrendSign), Label, ep, sl, tp, vol);
            //		trade.Expiration = Instrument.ExpirationTime(5);
            //		Broker.CreatePendingOrder(trade);

            // Create pending orders on either side of the channel
            {
                var ep    = chan.Price.End + 0.5 * mcs;
                var sl    = chan.Price.Beg;
                var tp    = (QuoteCurrency?)null;             // ep + chan.Price.Size * 5;
                var vol   = Broker.ChooseVolume(Instrument, Math.Abs(ep - sl), risk: risk);
                var trade = new Trade(Instrument, TradeType.Buy, Label, ep, sl, tp, vol);
                trade.Expiration = Instrument.ExpirationTime(5);
                Broker.CreatePendingOrder(trade);
            }
            {
                var ep    = chan.Price.Beg - 0.5 * mcs;
                var sl    = chan.Price.End;
                var tp    = (QuoteCurrency?)null;             // ep - chan.Price.Size * 5;
                var vol   = Broker.ChooseVolume(Instrument, Math.Abs(ep - sl), risk: risk);
                var trade = new Trade(Instrument, TradeType.Sell, Label, ep, sl, tp, vol);
                trade.Expiration = Instrument.ExpirationTime(5);
                Broker.CreatePendingOrder(trade);
            }

            // Debugging
            {
                var c = chan;
                for (; Channels.Count != 0 && c.Idx.Contains(Channels.Back().Idx);)
                {
                    Channels.PopBack();
                }
                Channels.Add(c);
            }
        }
 private double CalculateVolume(TradeType tradeType)
 {
     return(Symbol.NormalizeVolumeInUnits(FirstVolume * Math.Pow(VolumeExponent, Positions.Count(x => x.TradeType == tradeType && x.SymbolName == SymbolName && x.Label == ThiscBotLabel))));
 }
Example #23
0
        /////////////////////////////////////////////////////////////////////////////////////////////////////
        #region NON-PUBLIC PROCEDURES
        /////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Gets a random position.
        /// </summary>
        /// <returns>A random position.</returns>
        private static string GetRandomPosition()
        {
            int position = random.Next(0, Positions.Count());

            return(Positions.ElementAt(position));
        }
 public static bool CanOpenPosition(Positions positions, int maxOpenPositions)
 {
     if (positions.Count() < maxOpenPositions)
         return true;
     return false;
 }