//added 2018-05-31
        public bool IsAllPosClosed()
        {
            if (DictPositionsOfBots == null)
            {
                return(false);
            }

            lock (LckDictPositionsOfBots)
            {
                foreach (var kvp in DictPositionsOfBots)
                {
                    foreach (var kvp2 in kvp.Value)
                    {
                        if (kvp2.Value != null)
                        {
                            CBotPos bp = kvp2.Value;
                            if (bp.Amount != 0)
                            {
                                return(false);
                            }
                        }
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Call from OnUserDealData
        /// </summary>
        /// <param name="isin"></param>
        /// <param name="bp"></param>
        protected override void UpdateMonitorPosisionsAll(string isin, CBotPos bp)
        {
            base.UpdateMonitorPosisionsAll(isin, bp);

            BindTradersDispatcher();

            if (_tradersDispatcher == null)
            {
                _tradersDispatcher = _dealingServer.TradersDispatcher;
            }
            if (_tradersDispatcher != null)
            {
                _tradersDispatcher.EnqueueUpdatUserPositionsMonitor(this, BotId);
                _tradersDispatcher.EnqueueUpdateVm(BotId);
            }

            lock (MonitorPositionsAll)
            {
                CBotPos pos = new CBotPos();
                if (MonitorPositionsAll.TryGetValue(isin, out pos))
                {
                    _subBots[isin].OnUpdatePosition(pos);
                }
            }
        }
        /// <summary>
        /// Updates historical log of user positions
        ///
        /// Trigger update for GUI, Database and
        ///  client classB (which transmit to traderdipatcher, and
        ///  then to clients)
        /// Call from UserDealsPosBox
        ///
        /// this.CalculateBotsPos
        ///
        /// </summary>
        /// <param name="botId"></param>
        /// <param name="instrument"></param>
        /// <param name="bp"></param>
        /// <param name="rd"></param>
        public void UpdateUserPosLog(int botId, string instrument, CBotPos bp, CRawUserDeal rd)
        {
            try
            {
                CBotPos botPos = (CBotPos)bp.Copy();

                DicBotPosLog.Update(botId, instrument, botPos);



                UserDealsPosBoxClient.GUIBotUpdatePosLog(botPos, botId);
                UserDealsPosBoxClient.UpdateTradersPosLog(botId);



                //  UpdateLatestBotPos(botId, instrument, bp);



                UserDealsPosBoxClient.UpdateDBPosLog(botId,
                                                     UserDealsPosBoxClient.StockExchId,
                                                     instrument,
                                                     (CBotPos)bp.Copy());
            }
            catch (Exception e)
            {
                Error("UpdateUserPosLog(", e);
            }
        }
        /// <summary>
        /// Retrieve botpos from storage
        /// if need create it (lazy creation)
        ///
        /// Call from
        /// 1) CalculateBotsPos
        /// 2) IsRawDealLaterThenOpenedPos
        /// </summary>
        /// <param name="botID"></param>
        /// <param name="isin"></param>
        /// <returns></returns>
        public CBotPos GetBotPos(int botID, string isin)
        {
            //LckDictPositionsOfBots.WaitOne();
            lock (LckDictPositionsOfBots)
            {
                if ((!DictPositionsOfBots.ContainsKey(botID)))
                {
                    DictPositionsOfBots[botID] = new Dictionary <string, CBotPos>();
                }

                //  try
                {
                    if (!DictPositionsOfBots[botID].ContainsKey(isin))
                    {
                        DictPositionsOfBots[botID][isin] = new CBotPos(isin, this,
                                                                       AcconuntsFeeProc[botID]);
                    }
                }
                // catch (Exception e)
                {
                    //   Thread.Sleep(0);
                }

                CBotPos bp = (CBotPos)DictPositionsOfBots[botID][isin].Copy();
                // CBotPos bp = DictPositionsOfBots[botID][isin];
                //tempo remove !!!!!



                return(bp);
            }
        }
        /// <summary>
        /// 1)Triggers recalculation of bot positions
        /// 2)Trigger update bot positions on GUI
        ///
        /// Call when bid and ask ins stock changed
        ///
        /// Call from:
        ///
        /// Plaza2Connector\CStockConverterP2.ThreadStockConverter
        /// ASTS\CStockCOnverterASTS.ProcessConvert
        /// </summary>
        /// <param name="instrument"></param>
        public void RefreshBotPos(string instrument)
        {
            if (!UserDealsPosBoxClient.IsReadyRefreshBotPos())
            {
                return;
            }

            lock (LckDictPositionsOfBots)
            {
                try
                {
                    foreach (KeyValuePair <int, Dictionary <string, CBotPos> > kvp in DictPositionsOfBots)
                    {
                        int botId = kvp.Key;

                        if (kvp.Value.ContainsKey(instrument))
                        {
                            CBotPos bp = kvp.Value[instrument];

                            bp.CalcCurrentPos();
                            UserDealsPosBoxClient.GUIBotUpdateMonitorPos(bp, instrument, botId);
                        }
                    }
                }

                catch (Exception e)
                {
                    Error("RefreshBotPos", e);
                }
            }
        }
        /// <summary>
        /// Checks if RawDeal is later than Open posittion.
        /// Disabled 2017-10-19
        /// </summary>
        /// <param name="botID"></param>
        /// <param name="instrument"></param>
        /// <param name="rdTimeMili">Time in millisecs of raw deal</param>
        /// <returns></returns>
        private bool IsRawDealLaterThenOpenedPos(int botID, string instrument, long rdTimeMili)
        {
            lock (LckDictPositionsOfBots)
            {
                CBotPos bp = GetBotPos(botID, instrument);



                //no opened pos rd is later
                if (bp.Amount == 0)
                {
                    return(true);
                }


                long botposTimeMili = CUtilTime.GetUnixTimestampMillis(bp.DtOpen);

                if (rdTimeMili > botposTimeMili)
                {
                    return(true);
                }



                return(false);
            }
        }
Ejemplo n.º 7
0
        private void CheckDisableTimeExpired()
        {
            if (_disableTradeData == null)
            {
                return;
            }

            //if time expired trigger diasble modes
            if (!_modeDisableTraderTrading &&
                _disableTradeData.TradeDisableCode == CodeDisableTradeByTime._03_DisableAll &&
                _client.ServerTime > _disableTradeData.DtDisable)
            {
                _modeDisableTraderTrading = true;
                Log("Mode disable trader trading was set");
            }



            if (_modeDisableTraderTrading)
            {
                CBotPos bp          = GetPositionCurr();
                decimal amountPos   = bp.Amount;
                int     orderAmount = GetUserOrderAmountTotal();

                if (orderAmount == 0)   //No opedned orders
                {
                    if (amountPos == 0) //No opened position
                    {
                        if (!IS(EnmTraderState._0200_TradeDisableByTimeExpired))
                        {
                            //disable trading
                            SetState(EnmTraderState._0200_TradeDisableByTimeExpired);
                        }
                    }
                    else // opened position exists
                    {
                        if (!IS(EnmTraderState._0202_WaitClosePosOnTimeTradeExpired))
                        {
                            // DO Close all positions
                            CloseAllPositions();
                            SetState(EnmTraderState._0202_WaitClosePosOnTimeTradeExpired);
                        }
                    }
                }
                else // opened order exist
                {
                    if (!IS(EnmTraderState._0201_WaitCancellOrdersOnTimeTradeExpired))
                    {
                        //Do cancell all orders
                        _operations.CancellAllOrdersByInstrument(_instrument);
                        SetState(EnmTraderState._0201_WaitCancellOrdersOnTimeTradeExpired);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public MonitorPosInst(string isin, CBotPos bp, string stFormat)
        {
            Id     = isin;
            Amount = bp.Amount;
            AvPos  = bp.AvPos;
            //string stFormat = "0.0";
            AvPosString = AvPos.ToString(stFormat);

            VMCurrent_Points = bp.VMCurrent_Points;
            VMCurrent_RUB    = bp.VMCurrent_RUB;
            VMCurrent_Steps  = bp.VMCurrent_Steps;
        }
Ejemplo n.º 9
0
        private CBotPos GetPositionCurr()
        {
            CBotPos pos = new CBotPos();

            lock (_positionCurr)
            {
                pos.Amount = _positionCurr.Amount;
                pos.AvPos  = _positionCurr.AvPos;
            }

            return(pos);
        }
Ejemplo n.º 10
0
        protected override void RecalcBotStructs(CBotEventStruct botEvent)
        {
            try
            {
                base.RecalcBotStructs(botEvent);

                if (MonitorMarketDataAll.ContainsKey(m_isin))
                {
                    MonitorMarketData = MonitorMarketDataAll[m_isin];
                }
                if (MonitorPositionsAll.ContainsKey(m_isin))
                {
                    MonitorPositions = MonitorPositionsAll[m_isin];
                }
                lock (MonitorOrdersAll)
                {
                    if (MonitorOrdersAll.ContainsKey(m_isin))
                    {
                        MonitorOrders = MonitorOrdersAll[m_isin];
                    }
                }
                mxCurrentStocks[m_isin].WaitOne();

                if (m_currentStocks.ContainsKey(m_isin) &&
                    m_currentStocks[m_isin].ContainsKey(Direction.Down) &&
                    m_currentStocks[m_isin].ContainsKey(Direction.Up)
                    )
                {
                    if (m_currentStocks[m_isin][Direction.Down].Count > 0 &&
                        m_currentStocks[m_isin][Direction.Down][0].Price > 0)
                    {
                        MonitorMarketData.Bid = m_currentStocks[m_isin][Direction.Down][0].Price;
                    }

                    if (m_currentStocks[m_isin][Direction.Up].Count > 0 &&
                        m_currentStocks[m_isin][Direction.Up][0].Price > 0)
                    {
                        MonitorMarketData.Ask = m_currentStocks[m_isin][Direction.Up][0].Price;
                    }
                }
            }
            catch (Exception e)
            {
                Error("RecalcBotStructs bot=" + Name, e);
            }
            finally
            {
                mxCurrentStocks[m_isin].ReleaseMutex();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Check if position is more than maximum allowed in contracts
        /// </summary>
        private void CheckOpenedPositions()
        {
            foreach (KeyValuePair <string, CBotPos> kv in MonitorPositionsAll)
            {
                string  isin   = kv.Key;
                CBotPos botPos = kv.Value;


                if (Math.Abs(botPos.Amount) >
                    SettingsBot.DictBotIsinLimits[isin].MaxPosition)
                {
                    SelfTerminate("Position is more than maximum alllowed. Amount=" + botPos.Amount);
                }
            }
        }
Ejemplo n.º 12
0
        public void AddOrderRest(decimal price, EnmOrderDir dir)
        {
            CBotPos bp         = GetPositionCurr();
            decimal amountNeed = 0;

            if ((dir == EnmOrderDir.Buy && bp.Amount < 0) ||
                (dir == EnmOrderDir.Sell && bp.Amount > 0))

            {
                amountNeed = Math.Abs(bp.Amount);
                if (amountNeed > 0)
                {
                    _operations.AddOrder(_instrument, price, dir, amountNeed);
                    Log(String.Format("Order rest added price={0} amount={1} dir={2}",
                                      price, amountNeed, dir.ToString()));
                }
            }
        }
        /// <summary>
        /// Updates latest botpos
        /// </summary>
        /// <param name="botId"></param>
        /// <param name="instrument"></param>
        /// <param name="botPos"></param>
        private void UpdateLatestBotPos(int botId, string instrument, CBotPos botPos)
        {
            try
            {
                long timeMili = CUtilTime.GetUnixTimestampMillis(botPos.DtClose);


                LatestBotPosData.Update(botId, instrument,
                                        new CLatestTradeData
                {
                    Dt_timestamp_ms = timeMili,
                    ReplId          = botPos.ReplIdClosed
                }
                                        );
            }
            catch (Exception e)
            {
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// If stoporder condition is satisfied
        /// send stop order and set wait state
        /// </summary>
        private void CheckStopOrdersConditions()
        {
            //if not trading state (wait etc..,) no need
            //to trigger stoporders
            if (!IS(EnmTraderState._0110_Trading))
            {
                return;
            }

            CBotPos currPos = GetPositionCurr();

            if (BuyStopPrice != 0)
            {
                if (Ask >= BuyStopPrice)
                {
                    if (BuyStopAmount != 0)
                    {
                        _operations.TriggerStopOrder(_instrument, EnmOrderTypes.BuyStop, BuyStopAmount);
                        SetState(EnmTraderState._0115_WaitBuyStopApplyed);
                        _posBeforeStopOrder.Amount = currPos.Amount;
                        Log("BuyStop sent");
                        return;
                    }
                }
            }



            if (SellStopPrice != 0)
            {
                if (Bid <= SellStopPrice)
                {
                    if (SellStopAmount != 0)
                    {
                        SetState(EnmTraderState._0116_WaitSellStopApplyed);
                        _operations.TriggerStopOrder(_instrument, EnmOrderTypes.SellStop, SellStopAmount);
                        _posBeforeStopOrder.Amount = currPos.Amount;
                        Log("SellStopSent");
                        return;
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public void OnUpdatePosition(CBotPos pos)
        {
            lock (_positionCurr)
            {
                _positionCurr.Amount = pos.Amount;
                _positionCurr.AvPos  = pos.AvPos;
            }
            //changed 2017-03-08
            // CheckPositionClosedOrInvert();
            // CheckPositionJustOpened();

            CheckForStateChange();


            //prev value for detect closing/inversing position
            _positionPrev.Amount = pos.Amount;
            _positionPrev.AvPos  = pos.Amount;


            // CheckOrderThrowApplied();
        }
Ejemplo n.º 16
0
        public void SendStopLossInvert(string instrument, CBotPos pos)
        {
            //2017-03-13 was checked recently
            //if (pos.Amount == 0)
            //return;



            /*OrderDirection*/ EnmOrderDir dir;

            if (pos.Amount > 0)         //buy need sell
            {
                dir = EnmOrderDir.Sell; //OrderDirection.Sell;
            }
            else //sell need buy
            {
                dir = EnmOrderDir.Buy;//OrderDirection.Buy;
            }
            decimal amount = Math.Abs(pos.Amount * 2);

            AddMarketOrder(instrument, dir, amount);
        }
        public void Update(int botId, CBotPos botPos)
        {
            lock (this)
            {
                bool bFound = false;
                for (int i = 0; i < Lst.Count; i++)
                {
                    if (Lst[i].BotId == botId &&
                        Lst[i].Instrument == botPos.Instrument)
                    {
                        if (botPos.Amount == 0)
                        {
                            Lst.RemoveAt(i);
                        }
                        else
                        {
                            //update
                            Lst[i].Amount = botPos.Amount;
                        }

                        bFound = true;
                    }
                }

                if (!bFound)
                {
                    if (botPos.Amount != 0)
                    {
                        Lst.Add(new CBotPosTrdMgr
                        {
                            StockExchId = this.StockExchId,
                            BotId       = botId,
                            Instrument  = botPos.Instrument,
                            Amount      = botPos.Amount
                        });
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public void UpdateMonitorPos(string isin, CBotPos pos)
        {
            if (pos.Amount == 0)
            {
                m_plaza2Connector.GUIBox.ExecuteWindowsUpdate(new Action(() =>
                                                                         MonitorPos.RemoveWithId(isin)
                                                                         ));
            }
            else
            {
                m_plaza2Connector.GUIBox.ExecuteWindowsUpdate(new Action(() =>
                                                                         MonitorPos.UpdateWithId(new MonitorPosInst(isin, (CBotPos)pos.Copy(), GetPriceFormat(isin)))
                                                                         ));
            }



            if (m_plaza2Connector.IsOnlineUserDeals && !m_plaza2Connector.GUIBox.IsOnlineUserDealsDelayed)
            {
                m_plaza2Connector.GUIBox.ExecuteWindowsUpdate(new Action(() =>
                                                                         m_plaza2Connector.GUIBox.IsOnlineUserDealsDelayed = true));
            }
        }
Ejemplo n.º 19
0
        public void DoTest(List <CRawUserDeal> lstRawDeal,
                           List <Tuple <int, CBotPos> > lstCtrlPointsOpened,
                           List <Tuple <int, CBotPos> > lstCtrlPointsClosed
                           )
        {
            for (int i = 0; i < lstRawDeal.Count; i++)
            {
                _userDealPosBox.CalculateBotsPos(lstRawDeal[i]);



                var resOpened = lstCtrlPointsOpened.FirstOrDefault(a => a.Item1 == i + 1);
                if (resOpened != null)
                {
                    CBotPos bp = _userDealPosBox.DictPositionsOfBots[_botId][Ticker];
                    Assert.AreEqual(bp.Amount, resOpened.Item2.Amount);
                    Assert.AreEqual(bp.AvPos, resOpened.Item2.AvPos);
                    Assert.AreEqual(bp.VMCurrent_Steps, resOpened.Item2.VMCurrent_Steps);
                    Assert.AreEqual(bp.VMCurrent_Points, resOpened.Item2.VMCurrent_Points);
                }


                var resClosed = lstCtrlPointsClosed.FirstOrDefault(a => a.Item1 == i + 1);
                if (resClosed != null)
                {
                    int     cnt          = _userDealPosBox.DicBotPosLog[_botId][Ticker].Count - 1;
                    CBotPos botPosClosed = _userDealPosBox.DicBotPosLog[_botId][Ticker][cnt];


                    Assert.AreEqual(botPosClosed.CloseAmount, resClosed.Item2.CloseAmount);
                    Assert.AreEqual(botPosClosed.VMClosed_Points, resClosed.Item2.VMClosed_Points);
                    Assert.That(IsInRange(botPosClosed.VMClosed_Steps, resClosed.Item2.VMClosed_Steps));
                    Assert.That(IsInRange(botPosClosed.VMClosed_RUB_clean, resClosed.Item2.VMClosed_RUB_clean));
                    Assert.That(IsInRange(botPosClosed.VMClosed_RUB, resClosed.Item2.VMClosed_RUB));
                }
            }
        }
Ejemplo n.º 20
0
        public bool IsShortDisabled(EnmOrderDir dir, decimal amountOrdersToAdd)
        {
            if (!_modeDisableTraderShortTrading)
            {
                return(false);
            }

            if (EnmOrderDir.Buy == dir)
            {
                return(false); //any buy orders are possible
            }
            CBotPos bp        = GetPositionCurr();
            decimal amountPos = bp.Amount;
            decimal amountExistingShortOrders = GetUserOrderAmountByDir(dir);

            if (amountPos >= amountExistingShortOrders + amountOrdersToAdd)
            {
                return(false);
            }


            Log("IsShortDisabled.");
            return(true);
        }
Ejemplo n.º 21
0
 public override decimal GetVMClosed_RUB_clean(CBotPos botPos, decimal closedAmount)
 {
     return(botPos.VMClosed_Points * closedAmount);
 }
Ejemplo n.º 22
0
 public void UpdatePosLog(CBotPos bp)
 {
     m_plaza2Connector.GUIBox.ExecuteWindowsUpdate(new Action(() =>
                                                              PosLog.Add(bp)
                                                              ));
 }
Ejemplo n.º 23
0
 public override decimal GetVMClosed_RUB_clean(CBotPos botPos, decimal closedAmount)
 {
     return(botPos.VMClosed_Steps * botPos.StepPrice * closedAmount);
 }
Ejemplo n.º 24
0
 public void UpdateDBPosLog(long accountTradeId, int stockExchId, string Instrument,
                            CBotPos botPos)
 {
 }
Ejemplo n.º 25
0
 public void GUIBotUpdatePosLog(CBotPos BotPos, int extId)
 {
 }
Ejemplo n.º 26
0
 public void GUIBotUpdateMonitorPos(CBotPos bp, string isin, int botId)
 {
 }
        /// <summary>
        /// Late updates fee data of BotPos. Deals data (id, price etc)
        /// was already saved before to specific lists of CPosChangeFrag structs:
        /// ListOpeningPosChanges and ListClosingPosChanges
        /// So we need to find CPosChangeFrag element with DealId and update
        /// it's fee.
        /// Could be three cases:
        /// 1) If BotPos is opened (is not fully closed yet) than update fee of DictPositionsOfBots
        ///     element.
        /// 2) If BotPot was fully closed than update fee of DicBotPosLog
        /// 3) If position "rotated". For that case, if botpos is opening,
        ///   we check last DicBotPosLog element and if IsFeeLateCalced is not set
        ///   we perform recalc fee for this element. Note: fee of rotating deal
        ///   adds to the new "opened" position.
        ///
        /// If position was fully closed or rotated, saved to DicBotPosLog and all fees are
        /// not zeroes do update BotPos fee, and update other systems(Database, bots, etc)
        ///
        ///     2018-06-16 - as could be two deals with the same DealId (cross situation)
        ///                  do check DealId and Dir now.
        ///
        /// Call from:
        /// 1) CryptoDealingServer.UpdateUserDealsLateUpd
        /// 2) UserDealsPosBoxCrypto.Update
        /// </summary>
        /// <param name="botId"></param>
        /// <param name="instrument"></param>
        /// <param name="dealId"></param>
        /// <param name="fee"></param>
        public void UpdateFee(int botId, string instrument, long dealId, decimal fee, EnmDealDir dir)
        {
            bool bDealWithNoFee         = false;
            bool bFoundInPosLog         = false;
            bool bFoundInOpenedPos      = false;
            bool bFoundHistNotFeeCalced = false;
            bool bNullAnomalyFound      = false;

            CBotPos bpClosed   = null;
            decimal calcedFee  = 0;
            decimal feeDealing = 0;
            decimal feeStock   = 0;


            decimal calcedFeeForPos  = 0;
            decimal feeDealingForPos = 0;
            decimal feeStockForPos   = 0;

            Log(String.Format("[UpdateFee] botId={0} instrument={1} dealId={2} fee={3}",
                              botId, instrument, dealId, fee));



            //first find in opened positions

            lock (LckDictPositionsOfBots)
            {
                if (DictPositionsOfBots.ContainsKey(botId))
                {
                    if (DictPositionsOfBots[botId].ContainsKey(instrument))
                    {
                        CBotPos bp = DictPositionsOfBots[botId][instrument];
                        foreach (var el in bp.ListOpeningPosChanges)
                        {
                            if (el.IdDeal == dealId && el.Dir == dir)                             //2018-06-16 check dir
                            {
                                //2018-06-07 protect against override fee with wrong "0" value
                                if (fee == 0 && el.Fee != 0)
                                {
                                    Log("Protect to owerrite with zero. ListOpeningPosChanges");
                                }
                                else
                                {
                                    Log("Deals of DictPositionsOfBot's opening positions. Do Update fee.");
                                    //2018-07-19
                                    //2018-08-03 removed check
                                    // if (el.Fee == 0)
                                    CalculateFees(botId, fee, ref calcedFee, ref feeDealing, ref feeStock, el);



                                    bFoundInOpenedPos = true;
                                }
                                //return; //2018-05-23 removed
                            }
                        }

                        foreach (var el in bp.ListClosingPosChanges)
                        {
                            if (el.IdDeal == dealId && el.Dir == dir)  //2018-06-16 check dir
                            {
                                //2018-06-07 protect against override fee with wrong "0" value
                                if (fee == 0 && el.Fee != 0)
                                {
                                    Log("Protect to owerrite with zero. ListClosingPosChanges");
                                }
                                else
                                {
                                    Log("Deals of DictPositionsOfBot's closing positions. Do Update fee.");
                                    //2018-07-19
                                    //2018-08-03 removed check
                                    //if (el.FeeDealing == 0)
                                    CalculateFees(botId, fee, ref calcedFee, ref feeDealing, ref feeStock, el);


                                    bFoundInOpenedPos = true;
                                }
                                //return; //2018-05-23 removed
                            }
                        }
                    }
                }
            }

            //then look in historical positions
            lock (DicBotPosLog)
            {
                //if not found in opened pos find in poslog
                if (!bFoundInOpenedPos)
                {
                    if (DicBotPosLog.ContainsKey(botId))
                    {
                        if (DicBotPosLog[botId].ContainsKey(instrument))
                        {
                            if (DicBotPosLog[botId][instrument].Count > 0)
                            {
                                bpClosed = DicBotPosLog[botId][instrument].Last();
                                foreach (var el in bpClosed.ListClosingPosChanges)
                                {
                                    if (el.IdDeal == dealId && el.Dir == dir) //2018-06-16 check dir
                                    {
                                        //TODO normal loading  from DB after disconnect
                                        //2018-07-19
                                        //   //2018-08-03 removed check
                                        //if (el.FeeDealing == 0)
                                        CalculateFees(botId, fee, ref calcedFee, ref feeDealing, ref feeStock, el);



                                        bFoundInPosLog = true;
                                        Log("bFoundInPosLog");
                                    }
                                    else if (el.Fee == 0)
                                    {
                                        bDealWithNoFee = true;
                                        Log(String.Format("bDealWithNoFee DealId={0}", el.IdDeal));
                                    }
                                }
                            }
                        }
                    }
                }

                //2018-05-23 check if last pos "fee processed".
                //This is for processing "rotate" position case
                if (bFoundInOpenedPos)
                {
                    if (DicBotPosLog.ContainsKey(botId))
                    {
                        if (DicBotPosLog[botId].ContainsKey(instrument))
                        {
                            if (DicBotPosLog[botId][instrument].Count > 0)
                            {
                                bpClosed = DicBotPosLog[botId][instrument].Last();
                                if (bpClosed != null)
                                {
                                    if (bpClosed.IsFeeLateCalced == 0)
                                    {
                                        bFoundHistNotFeeCalced = true;
                                        Log("bFoundHistNotFeeCalced");
                                    }
                                }
                            }
                        }
                    }
                }

                //2018-06-03 protect against  bpClosed==null "anlomaly"
                if (bFoundInPosLog && bpClosed == null)
                {
                    bpClosed          = DicBotPosLog[botId][instrument].Last();
                    bNullAnomalyFound = true;
                    Log("Null anomaly found");
                }
                //end protect amomaly


                //TODO check if fee not recalc yet
                //if all deals of historical postions are closed, all fees are saved (no bDealWithNoFee)
                // perform recalc and set botpos as fee calculated.
                //2018-05-23 also perform calc when "rotate pos" situation (bFoundHistNotFeeCalced)
                //2018-06-20 try to remove bDealWithNoFee and IsFeeLateCalced condition becaused
                //fee COULD BE zero in a "very little" amount case. Note: as we check "bpClosed!=null"
                //we calcuylate and update total position fee after position close.
                if (bpClosed != null)
                {
                    if (/*bpClosed.IsFeeLateCalced==0 &&*/ (bFoundInPosLog || bFoundHistNotFeeCalced)
                        /*&& !bDealWithNoFee*/)
                    {
                        Log("Update fee of historical position");
                        if (bpClosed.ListOpeningPosChanges != null) //2018-07-19 protect against null data (when loaded from DB to poslog)
                        {
                            bpClosed.ListOpeningPosChanges.ForEach(el =>
                            {
                                calcedFeeForPos  += el.Fee;
                                feeStockForPos   += el.Fee_Stock;
                                feeDealingForPos += el.FeeDealing;
                            }
                                                                   );
                        }

                        if (bpClosed.ListClosingPosChanges != null) //2018-07-19  protect against null data (when loaded from DB to poslog)
                        {
                            bpClosed.ListClosingPosChanges.ForEach(el =>
                            {
                                calcedFeeForPos  += el.Fee;
                                feeStockForPos   += el.Fee_Stock;
                                feeDealingForPos += el.FeeDealing;
                            }
                                                                   );
                        }

                        if (calcedFeeForPos != 0)                                                           //2018-07-19 protect against owerride fee (if null we do not need)
                        {
                            bpClosed.Fee_Stock  = feeStockForPos;;                                          //fee recieved from stock
                            bpClosed.FeeDealing = feeDealingForPos;                                         //fee by dealing
                            bpClosed.Fee        = calcedFeeForPos;                                          //  2018-07-19
                            bpClosed.Fee_Total  = bpClosed.Fee;                                             //is equal fee

                            bpClosed.VMClosed_RUB_stock = bpClosed.VMClosed_RUB_clean - bpClosed.Fee_Stock; //is equal VM on stock exchange (for checking), substract only stock fee
                            bpClosed.VMClosed_RUB       = bpClosed.VMClosed_RUB_clean - bpClosed.Fee;       //resulting VM substract full fee
                            bpClosed.VMClosed_RUB_user  = bpClosed.VMClosed_RUB;                            //is equal VMClosed_RUB

                            bpClosed.IsFeeLateCalced = 1;

                            _client.UpdateUserPosLogLate(new CDBUpdateLate
                            {
                                Instrument         = instrument,
                                ReplId             = bpClosed.ReplIdClosed,
                                BotId              = botId,
                                Fee_Total          = bpClosed.Fee_Total,
                                Fee                = bpClosed.Fee,
                                Fee_Stock          = bpClosed.Fee_Stock,
                                FeeDealing         = bpClosed.FeeDealing,
                                VMClosed_RUB       = bpClosed.VMClosed_RUB,
                                VMClosed_RUB_user  = bpClosed.VMClosed_RUB_user,
                                VMClosed_RUB_stock = bpClosed.VMClosed_RUB_stock,
                                IsFeeLateCalced    = bpClosed.IsFeeLateCalced
                            });
                        }
                    }
                }

                //===================== DEBUGGING START
                //2018-06-03 this is for debugging
                //to catch bpClosed==null situation
                if (bFoundInPosLog)
                {
                    if (bpClosed == null || bNullAnomalyFound)
                    {
                        Log("bpClosed == null catching situation");
                        if (DicBotPosLog.ContainsKey(botId))
                        {
                            if (DicBotPosLog[botId].ContainsKey(instrument))
                            {
                                if (DicBotPosLog[botId][instrument].Count != 0)
                                {
                                    var lastEl = DicBotPosLog[botId][instrument].Last();
                                    if (lastEl == null)
                                    {
                                        Log("Last el is null");
                                    }

                                    foreach (var elBp in DicBotPosLog[botId][instrument])
                                    {
                                        Log(String.Format("DtOpen={0} DtClosed={1} BuySell={2} " +
                                                          "CloseAmount={3} Priceopen={4} Priceopen={4} PriceClose={5}",
                                                          elBp.DtOpen,
                                                          elBp.DtClose,
                                                          elBp.BuySell,
                                                          elBp.CloseAmount,
                                                          elBp.PriceOpen,
                                                          elBp.PriceClose));
                                    }
                                }
                                else
                                {
                                    Log("Count is 0");
                                }
                            }
                            else
                            {
                                Log("Doesn't contain instrument");
                            }
                        }
                        else
                        {
                            Log("Doesn't contain botId");
                        }
                    }
                }
                //DEBUGGING END
            } //end lock (DicBotPosLog)



            _client.TriggerRecalculateBot(botId, "", EnmBotEventCode.OnForceUpdTotalVM, null);

            _client.UpdateFeeUserDealsLog(new CDBUpdateFeeUserDealsLog
            {
                DealId     = dealId,
                Fee        = calcedFee,
                FeeDealing = feeDealing,
                FeeStock   = feeStock
            });

            //
        }
Ejemplo n.º 28
0
 public abstract decimal GetVMClosed_RUB_clean(CBotPos botPos, decimal closedAmount);
Ejemplo n.º 29
0
 public abstract decimal GetVMCurrent_RUB_clean(CBotPos botPos, decimal openedAmount);
Ejemplo n.º 30
0
 public override decimal GetVMCurrent_RUB_clean(CBotPos botPos, decimal openedAmount)
 {
     return(botPos.VMCurrent_Points * openedAmount);
 }