Пример #1
0
        public virtual bool Initialize()
        {
            // get remote cash and positions
            cash = strategy.GetCash();
            
            if (cash == null)
            {
                strategy.WriteError("不能打开账户");
                strategy.Stop();
                return false;
            }

            strategy.WriteInfo(string.Format("账户总资产({0:N2}), 可用资金({1:N2})", cash.nav, cash.available));

            string info = "持仓:";
            positions = strategy.GetPositions();
            foreach (Position pos in positions)
            {               
                info += string.Format("[{0}:{1}({2})]",pos.sec_id, pos.volume, pos.side == 1 ? "多" : "空");

                Monitor monitor = strategy.GetMonitor(string.Format("{0}.{1}", pos.exchange, pos.sec_id));
                if (monitor != null)
                {
                    monitor.OnPosition(pos);
                }
            }
            strategy.WriteInfo(info);

            return true;
        }
Пример #2
0
        public static int Verify(Cash cash, Stream stream)
        {
            if (cash == null) return 0;
            if (stream == null) throw new ArgumentNullException(nameof(stream));

            if (cash.CashAlgorithm == CashAlgorithm.Version1)
            {
                var minerUtils = new MinerUtils();

                return minerUtils.Verify_1(cash.Key, Sha256.ComputeHash(stream));
            }

            return 0;
        }
Пример #3
0
Файл: Cfd.cs Проект: neosb/Lean
 /// <summary>
 /// Constructor for the CFD security
 /// </summary>
 /// <param name="exchangeHours">Defines the hours this exchange is open</param>
 /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
 /// <param name="config">The subscription configuration for this security</param>
 /// <param name="symbolProperties">The symbol properties for this security</param>
 public Cfd(SecurityExchangeHours exchangeHours, Cash quoteCurrency, SubscriptionDataConfig config, SymbolProperties symbolProperties)
     : base(config,
         quoteCurrency,
         symbolProperties,
         new CfdExchange(exchangeHours),
         new CfdCache(),
         new SecurityPortfolioModel(),
         new ImmediateFillModel(),
         new ConstantFeeModel(0),
         new SpreadSlippageModel(),
         new ImmediateSettlementModel(),
         new SecurityMarginModel(50m),
         new CfdDataFilter()
         )
 {
     Holdings = new CfdHolding(this);
 }
Пример #4
0
 /// <summary>
 /// Construct the Equity Object
 /// </summary>
 public Equity(Symbol symbol, SecurityExchangeHours exchangeHours, Cash quoteCurrency, SymbolProperties symbolProperties)
     : base(symbol,
         quoteCurrency,
         symbolProperties,
         new EquityExchange(exchangeHours),
         new EquityCache(),
         new SecurityPortfolioModel(),
         new ImmediateFillModel(),
         new InteractiveBrokersFeeModel(),
         new ConstantSlippageModel(0m),
         new ImmediateSettlementModel(),
         Securities.VolatilityModel.Null,
         new SecurityMarginModel(2m),
         new EquityDataFilter()
         )
 {
     Holdings = new EquityHolding(this);
 }
Пример #5
0
 /// <summary>
 /// Constructor for the CFD security
 /// </summary>
 /// <param name="symbol">The security's symbol</param>
 /// <param name="exchangeHours">Defines the hours this exchange is open</param>
 /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
 /// <param name="symbolProperties">The symbol properties for this security</param>
 public Cfd(Symbol symbol, SecurityExchangeHours exchangeHours, Cash quoteCurrency, SymbolProperties symbolProperties)
     : base(symbol,
         quoteCurrency,
         symbolProperties,
         new CfdExchange(exchangeHours),
         new CfdCache(),
         new SecurityPortfolioModel(),
         new ImmediateFillModel(),
         new ConstantFeeModel(0),
         new SpreadSlippageModel(),
         new ImmediateSettlementModel(),
         Securities.VolatilityModel.Null,
         new SecurityMarginModel(50m),
         new CfdDataFilter()
         )
 {
     Holdings = new CfdHolding(this);
 }
Пример #6
0
        /********************************************************
        * CLASS VARIABLES
        *********************************************************/
        /********************************************************
        * CONSTRUCTOR/DELEGATE DEFINITIONS
        *********************************************************/
        /// <summary>
        /// Constructor for the forex security
        /// </summary>
        /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
        /// <param name="config">The subscription configuration for this security</param>
        /// <param name="leverage">The leverage used for this security</param>
        /// <param name="isDynamicallyLoadedData">True for custom data, false otherwise</param>
        public Forex(Cash quoteCurrency, SubscriptionDataConfig config, decimal leverage, bool isDynamicallyLoadedData = false)
            : base(config, leverage, isDynamicallyLoadedData)
        {
            QuoteCurrency = quoteCurrency;
            //Holdings for new Vehicle:
            Cache = new ForexCache();
            Exchange = new ForexExchange();
            DataFilter = new ForexDataFilter();
            TransactionModel = new ForexTransactionModel();
            PortfolioModel = new ForexPortfolioModel();
            MarginModel = new ForexMarginModel(leverage);
            Holdings = new ForexHolding(this, TransactionModel, MarginModel);

            // decompose the symbol into each currency pair
            string baseCurrencySymbol, quoteCurrencySymbol;
            DecomposeCurrencyPair(config.Symbol, out baseCurrencySymbol, out quoteCurrencySymbol);
            BaseCurrencySymbol = baseCurrencySymbol;
            QuoteCurrencySymbol = quoteCurrencySymbol;
        }
Пример #7
0
 /// <summary>
 /// Constructor for the option security
 /// </summary>
 /// <param name="exchangeHours">Defines the hours this exchange is open</param>
 /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
 /// <param name="config">The subscription configuration for this security</param>
 /// <param name="symbolProperties">The symbol properties for this security</param>
 public Option(SecurityExchangeHours exchangeHours, SubscriptionDataConfig config, Cash quoteCurrency, SymbolProperties symbolProperties)
     : base(config,
         quoteCurrency,
         symbolProperties,
         new OptionExchange(exchangeHours),
         new OptionCache(),
         new SecurityPortfolioModel(),
         new ImmediateFillModel(),
         new InteractiveBrokersFeeModel(),
         new SpreadSlippageModel(),
         new ImmediateSettlementModel(),
         Securities.VolatilityModel.Null,
         new SecurityMarginModel(2m),
         new OptionDataFilter()
         )
 {
     PriceModel = new CurrentPriceOptionPriceModel();
     ContractFilter = new StrikeExpiryOptionFilter(-5, 5, TimeSpan.Zero, TimeSpan.FromDays(35));
 }
Пример #8
0
        /// <summary>
        /// Constructor for the forex security
        /// </summary>
        /// <param name="exchangeHours">Defines the hours this exchange is open</param>
        /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
        /// <param name="config">The subscription configuration for this security</param>
        /// <param name="leverage">The leverage used for this security</param>
        public Forex(SecurityExchangeHours exchangeHours, Cash quoteCurrency, SubscriptionDataConfig config, decimal leverage)
            : base(exchangeHours, config, leverage)
        {
            QuoteCurrency = quoteCurrency;
            //Holdings for new Vehicle:
            Cache = new ForexCache();
            Exchange = new ForexExchange(exchangeHours);
            DataFilter = new ForexDataFilter();
            TransactionModel = new ForexTransactionModel();
            PortfolioModel = new ForexPortfolioModel();
            MarginModel = new ForexMarginModel(leverage);
            Holdings = new ForexHolding(this);

            // decompose the symbol into each currency pair
            string baseCurrencySymbol, quoteCurrencySymbol;
            DecomposeCurrencyPair(config.Symbol.Value, out baseCurrencySymbol, out quoteCurrencySymbol);
            BaseCurrencySymbol = baseCurrencySymbol;
            QuoteCurrencySymbol = quoteCurrencySymbol;
        }
Пример #9
0
        /// <summary>
        /// Constructor for the forex security
        /// </summary>
        /// <param name="exchangeHours">Defines the hours this exchange is open</param>
        /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
        /// <param name="config">The subscription configuration for this security</param>
        /// <param name="symbolProperties">The symbol properties for this security</param>
        public Forex(SecurityExchangeHours exchangeHours, Cash quoteCurrency, SubscriptionDataConfig config, SymbolProperties symbolProperties)
            : base(config,
                quoteCurrency,
                symbolProperties,
                new ForexExchange(exchangeHours),
                new ForexCache(),
                new SecurityPortfolioModel(),
                new ImmediateFillModel(),
                new InteractiveBrokersFeeModel(),
                new SpreadSlippageModel(),
                new ImmediateSettlementModel(),
                new SecurityMarginModel(50m),
                new ForexDataFilter()
                )
        {
            Holdings = new ForexHolding(this);

            // decompose the symbol into each currency pair
            string baseCurrencySymbol, quoteCurrencySymbol;
            DecomposeCurrencyPair(config.Symbol.Value, out baseCurrencySymbol, out quoteCurrencySymbol);
            BaseCurrencySymbol = baseCurrencySymbol;
        }
Пример #10
0
        /// <summary>
        /// Constructor for the CFD security
        /// </summary>
        /// <param name="exchangeHours">Defines the hours this exchange is open</param>
        /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
        /// <param name="config">The subscription configuration for this security</param>
        /// <param name="symbolProperties">The symbol properties for this security</param>
        public Cfd(SecurityExchangeHours exchangeHours, Cash quoteCurrency, SubscriptionDataConfig config, SymbolProperties symbolProperties)
            : base(config,
                new CfdExchange(exchangeHours),
                new CfdCache(),
                new CfdPortfolioModel(),
                new ImmediateFillModel(),
                new ConstantFeeModel(0),
                new SpreadSlippageModel(),
                new ImmediateSettlementModel(),
                new CfdMarginModel(50m),
                new CfdDataFilter()
                )
        {
            QuoteCurrency = quoteCurrency;
            Holdings = new CfdHolding(this);
            SymbolProperties = symbolProperties;

            if (symbolProperties == null)
                throw new ArgumentException("CFD requires a valid SymbolProperties argument");

            if (symbolProperties.QuoteCurrency != quoteCurrency.Symbol)
                throw new ArgumentException("CFD SymbolProperties.QuoteCurrency and QuoteCurrency.Symbol do not match.");
        }
Пример #11
0
        private void TradeCash_HeartPusle(Cash cash, long elapsed, bool isWeb)
        {
            if (this.splitContainer1.Panel1.InvokeRequired == false)
            {
                DateTime dt = DateTime.Now;
                if (isWeb)
                {
                    grpWEB.Text = string.Format("Web 账户({0}, 用时{1})", dt.ToString("hh:mm:ss"), elapsed);
                    ShowWebCashInfo(cash);
                }
                else
                {
                    grpGM.Text = string.Format("GM 账户({0}, 用时{1})", dt.ToString("hh:mm:ss"), elapsed);
                    ShowGMCashInfo(cash);
                }

            }
            else
            {
                MyStrategy.TradeCashHeartPusleCallback handler = new MyStrategy.TradeCashHeartPusleCallback(this.TradeCash_HeartPusle);
                this.splitContainer1.Panel1.BeginInvoke(handler, cash, elapsed, isWeb);
            }
        }
Пример #12
0
 private void ShowWebCashInfo(Cash cash)
 {
     txtNavW.Text = cash.nav.ToString("N");
     txtAvailableW.Text = cash.available.ToString("N");
     txtFrozenW.Text = cash.frozen.ToString("N");
     txtOrderFrozenW.Text = cash.order_frozen.ToString("N");
 }
Пример #13
0
        /// <summary>
        /// 单据生成
        /// </summary>
        /// <param name="cfile">模板文件</param>
        /// <param name="path">生成路径</param>
        /// <param name="file">生成文件</param>
        /// <param name="isOpen">是否用IE打开?</param>
        public void MakeDoc(string cfile, string path, string file, string replaceVals, bool isOpen)
        {
            string str = Cash.GetBillStr(cfile, false).Substring(0);

            if (this.HisEns.Count == 0)
            {
                if (this.HisGEEntity == null)
                {
                    throw new Exception("@您没有为报表设置数据源...");
                }
            }

            this.ensStrs = "";
            if (this.HisEns.Count != 0)
            {
                foreach (Entity en in this.HisEns)
                {
                    ensStrs += en.ToString();
                }
            }
            else
            {
                ensStrs = this.HisGEEntity.ToString();
            }

            string error = "";

            string[] paras = null;
            if (this.HisGEEntity != null)
            {
                paras = Cash.GetBillParas(cfile, ensStrs, this.HisGEEntity);
            }
            else
            {
                paras = Cash.GetBillParas(cfile, ensStrs, this.HisEns);
            }

            this.TempFilePath = path + file;
            try
            {
                string key = "";
                string ss  = "";

                #region 替换主表标记
                foreach (string para in paras)
                {
                    if (para == null || para == "")
                    {
                        continue;
                    }
                    try
                    {
                        if (para.Contains("ImgAth"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueByKey(para));
                        }
                        else if (para.Contains("Siganture"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueByKey(para));
                        }
                        else if (para.Contains("Img@AppPath"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueImgStrs(para));
                        }
                        else if (para.Contains(".BPPaint"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueBPPaintStrs(para));
                        }
                        else if (para.Contains(".M2M"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueM2MStrs(para));
                        }
                        else if (para.Contains(".RMB"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueByKey(para));
                        }
                        else if (para.Contains(".RMBDX"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueByKey(para));
                        }
                        else if (para.Contains(".Boolen"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueByKey(para));
                        }
                        else if (para.Contains(".BoolenText"))
                        {
                            str = str.Replace("<" + para + ">", this.GetValueByKey(para));
                        }
                        else if (para.Contains(".NYR"))
                        {
                            str = str.Replace("<" + para + ">", this.GetCode(this.GetValueByKey(para)));
                        }
                        else if (para.Contains(".Yes") == true)
                        {
                            str = str.Replace("<" + para + ">", this.GetCode(this.GetValueByKey(para)));
                        }
                        else if (para.Contains(".") == true)
                        {
                            continue; /*有可能是明细表数据.*/
                        }
                        else
                        {
                            str = str.Replace("<" + para + ">", this.GetCode(this.GetValueByKey(para)));
                        }
                    }
                    catch (Exception ex)
                    {
                        error += "替换主表标记取参数[" + para + "]出现错误:有以下情况导致此错误;1你用Text取值时间,此属性不是外键。2,类无此属性。3,该字段是明细表字段但是丢失了明细表标记.<br>更详细的信息:<br>" + ex.Message;
                        if (SystemConfig.IsDebug)
                        {
                            throw new Exception(error);
                        }
                        Log.DebugWriteError(error);
                    }
                }
                #endregion 替换主表标记

                #region 从表
                string    shortName = "";
                ArrayList al        = this.EnsDataDtls;
                foreach (Entities dtls in al)
                {
                    Entity dtl       = dtls.GetNewEntity;
                    string dtlEnName = dtl.ToString();
                    shortName = dtlEnName.Substring(dtlEnName.LastIndexOf(".") + 1);

                    if (str.IndexOf(shortName) == -1)
                    {
                        continue;
                    }

                    int pos_rowKey = str.IndexOf(shortName);
                    int row_start = -1, row_end = -1;
                    if (pos_rowKey != -1)
                    {
                        row_start = str.Substring(0, pos_rowKey).LastIndexOf("\\row");
                        row_end   = str.Substring(pos_rowKey).IndexOf("\\row");
                    }

                    if (row_start != -1 && row_end != -1)
                    {
                        string row = str.Substring(row_start, (pos_rowKey - row_start) + row_end);
                        str = str.Replace(row, "");

                        Map map = dtls.GetNewEntity.EnMap;
                        int i   = dtls.Count;
                        while (i > 0)
                        {
                            i--;
                            string rowData = row.Clone() as string;
                            dtl = dtls[i];
                            //替换序号
                            int rowIdx = i + 1;
                            rowData = rowData.Replace("<IDX>", rowIdx.ToString());

                            foreach (Attr attr in map.Attrs)
                            {
                                switch (attr.MyDataType)
                                {
                                case DataType.AppDouble:
                                case DataType.AppFloat:
                                case DataType.AppRate:
                                    rowData = rowData.Replace("<" + shortName + "." + attr.Key + ">", dtl.GetValStringByKey(attr.Key));
                                    break;

                                case DataType.AppMoney:
                                    rowData = rowData.Replace("<" + shortName + "." + attr.Key + ">", dtl.GetValDecimalByKey(attr.Key).ToString("0.00"));
                                    break;

                                case DataType.AppInt:

                                    if (attr.MyDataType == DataType.AppBoolean)
                                    {
                                        rowData = rowData.Replace("<" + shortName + "." + attr.Key + ">", dtl.GetValStrByKey(attr.Key));
                                        int v = dtl.GetValIntByKey(attr.Key);
                                        if (v == 1)
                                        {
                                            rowData = rowData.Replace("<" + shortName + "." + attr.Key + "Text>", "是");
                                        }
                                        else
                                        {
                                            rowData = rowData.Replace("<" + shortName + "." + attr.Key + "Text>", "否");
                                        }
                                    }
                                    else
                                    {
                                        if (attr.IsEnum)
                                        {
                                            rowData = rowData.Replace("<" + shortName + "." + attr.Key + "Text>", GetCode(dtl.GetValRefTextByKey(attr.Key)));
                                        }
                                        else
                                        {
                                            rowData = rowData.Replace("<" + shortName + "." + attr.Key + ">", dtl.GetValStrByKey(attr.Key));
                                        }
                                    }
                                    break;

                                default:
                                    rowData = rowData.Replace("<" + shortName + "." + attr.Key + ">", GetCode(dtl.GetValStrByKey(attr.Key)));
                                    break;
                                }
                            }

                            str = str.Insert(row_start, rowData);
                        }
                    }
                }
                #endregion 从表

                #region 明细 合计信息。
                al = this.EnsDataDtls;
                foreach (Entities dtls in al)
                {
                    Entity dtl       = dtls.GetNewEntity;
                    string dtlEnName = dtl.ToString();
                    shortName = dtlEnName.Substring(dtlEnName.LastIndexOf(".") + 1);
                    //shortName = dtls.ToString().Substring(dtls.ToString().LastIndexOf(".") + 1);
                    Map map = dtl.EnMap;
                    foreach (Attr attr in map.Attrs)
                    {
                        switch (attr.MyDataType)
                        {
                        case DataType.AppDouble:
                        case DataType.AppFloat:
                        case DataType.AppMoney:
                        case DataType.AppRate:
                            key = "<" + shortName + "." + attr.Key + ".SUM>";
                            if (str.IndexOf(key) != -1)
                            {
                                str = str.Replace(key, dtls.GetSumFloatByKey(attr.Key).ToString());
                            }

                            key = "<" + shortName + "." + attr.Key + ".SUM.RMB>";
                            if (str.IndexOf(key) != -1)
                            {
                                str = str.Replace(key, dtls.GetSumFloatByKey(attr.Key).ToString("0.00"));
                            }

                            key = "<" + shortName + "." + attr.Key + ".SUM.RMBDX>";
                            if (str.IndexOf(key) != -1)
                            {
                                str = str.Replace(key,
                                                  GetCode(DA.DataType.ParseFloatToCash(dtls.GetSumFloatByKey(attr.Key))));
                            }
                            break;

                        case DataType.AppInt:
                            key = "<" + shortName + "." + attr.Key + ".SUM>";
                            if (str.IndexOf(key) != -1)
                            {
                                str = str.Replace(key, dtls.GetSumIntByKey(attr.Key).ToString());
                            }
                            break;

                        default:
                            break;
                        }
                    }
                }
                #endregion 从表合计

                #region 要替换的字段
                if (replaceVals != null && replaceVals.Contains("@"))
                {
                    string[] vals = replaceVals.Split('@');
                    foreach (string val in vals)
                    {
                        if (val == null || val == "")
                        {
                            continue;
                        }

                        if (val.Contains("=") == false)
                        {
                            continue;
                        }

                        string myRep = val.Clone() as string;

                        myRep = myRep.Trim();
                        myRep = myRep.Replace("null", "");
                        string[] myvals = myRep.Split('=');
                        str = str.Replace("<" + myvals[0] + ">", "<" + myvals[1] + ">");
                    }
                }
                #endregion

                StreamWriter wr = new StreamWriter(this.TempFilePath, false, Encoding.ASCII);
                str = str.Replace("<", "");
                str = str.Replace(">", "");
                wr.Write(str);
                wr.Close();
            }
            catch (Exception ex)
            {
                string msg = "";
                if (SystemConfig.IsDebug)
                {  // 异常可能与单据的配置有关系。
                    try
                    {
                        this.CyclostyleFilePath = SystemConfig.PathOfDataUser + "\\CyclostyleFile\\" + cfile;
                        str = Cash.GetBillStr(cfile, false);
                        string s = RepBill.RepairBill(this.CyclostyleFilePath);
                        msg = "@已经成功的执行修复线  RepairLineV2,您重新发送一次或者,退后重新在发送一次,是否可以解决此问题。@" + s;
                    }
                    catch (Exception ex1)
                    {
                        msg = "执行修复线失败.  RepairLineV2 " + ex1.Message;
                    }
                }
                throw new Exception("生成文档失败:单据名称[" + this.CyclostyleFilePath + "] 异常信息:" + ex.Message + " @自动修复单据信息:" + msg);
            }
            if (isOpen)
            {
                PubClass.Print(BP.Sys.Glo.Request.ApplicationPath + "Temp/" + file);
            }
        }
Пример #14
0
 private void UpdateCashOnHand()
 {
     Cash.Subtract(purchasePrice);
 }
Пример #15
0
        public void RefreshesOptionChainUniverseOnDateChange()
        {
            var startTime    = new DateTime(2018, 10, 19, 10, 0, 0);
            var timeProvider = new ManualTimeProvider(startTime);

            var canonicalSymbol = Symbol.Create("SPY", SecurityType.Option, Market.USA, "?SPY");

            var quoteCurrency = new Cash(Currencies.USD, 0, 1);
            var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, canonicalSymbol, SecurityType.Option);
            var config        = new SubscriptionDataConfig(
                typeof(ZipEntryName),
                canonicalSymbol,
                Resolution.Minute,
                TimeZones.Utc,
                TimeZones.NewYork,
                true,
                false,
                false,
                false,
                TickType.Quote,
                false,
                DataNormalizationMode.Raw
                );

            var option = new Option(
                canonicalSymbol,
                exchangeHours,
                quoteCurrency,
                new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache(),
                null
                );

            var fillForwardResolution = Ref.CreateReadOnly(() => Resolution.Minute.ToTimeSpan());
            var symbolUniverse        = new TestDataQueueUniverseProvider(timeProvider);
            EnqueueableEnumerator <BaseData> underlyingEnumerator = null;
            Func <SubscriptionRequest, IEnumerator <BaseData> > underlyingEnumeratorFunc =
                (req) =>
            {
                underlyingEnumerator = new EnqueueableEnumerator <BaseData>();
                return(new LiveFillForwardEnumerator(
                           timeProvider,
                           underlyingEnumerator,
                           option.Exchange,
                           fillForwardResolution,
                           false,
                           Time.EndOfTime,
                           Resolution.Minute.ToTimeSpan(),
                           TimeZones.Utc));
            };
            var factory = new OptionChainUniverseSubscriptionEnumeratorFactory(underlyingEnumeratorFunc, symbolUniverse, timeProvider);

            var universeSettings = new UniverseSettings(Resolution.Minute, 0, true, false, TimeSpan.Zero);
            var universe         = new OptionChainUniverse(option, universeSettings, true);
            var request          = new SubscriptionRequest(true, universe, option, config, startTime, Time.EndOfTime);
            var enumerator       = (DataQueueOptionChainUniverseDataCollectionEnumerator)factory.CreateEnumerator(request, new DefaultDataProvider());

            // 2018-10-19 10:00 AM UTC
            underlyingEnumerator.Enqueue(new Tick {
                Symbol = Symbols.SPY, Value = 280m
            });

            // 2018-10-19 10:01 AM UTC
            timeProvider.Advance(Time.OneMinute);

            underlyingEnumerator.Enqueue(new Tick {
                Symbol = Symbols.SPY, Value = 280m
            });

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNotNull(enumerator.Current);
            Assert.AreEqual(1, symbolUniverse.TotalLookupCalls);
            var data = enumerator.Current;

            Assert.IsNotNull(data);
            Assert.AreEqual(1, data.Data.Count);
            Assert.IsNotNull(data.Underlying);

            // 2018-10-19 10:02 AM UTC
            timeProvider.Advance(Time.OneMinute);

            underlyingEnumerator.Enqueue(new Tick {
                Symbol = Symbols.SPY, Value = 280m
            });

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNotNull(enumerator.Current);
            Assert.AreEqual(1, symbolUniverse.TotalLookupCalls);
            data = enumerator.Current;
            Assert.IsNotNull(data);
            Assert.AreEqual(1, data.Data.Count);
            Assert.IsNotNull(data.Underlying);

            // 2018-10-19 10:03 AM UTC
            timeProvider.Advance(Time.OneMinute);

            underlyingEnumerator.Enqueue(new Tick {
                Symbol = Symbols.SPY, Value = 280m
            });

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNotNull(enumerator.Current);
            Assert.AreEqual(1, symbolUniverse.TotalLookupCalls);
            data = enumerator.Current;
            Assert.IsNotNull(data);
            Assert.AreEqual(1, data.Data.Count);
            Assert.IsNotNull(data.Underlying);

            // 2018-10-20 10:03 AM UTC
            timeProvider.Advance(Time.OneDay);

            underlyingEnumerator.Enqueue(new Tick {
                Symbol = Symbols.SPY, Value = 280m
            });

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNotNull(enumerator.Current);
            Assert.AreEqual(2, symbolUniverse.TotalLookupCalls);
            data = enumerator.Current;
            Assert.IsNotNull(data);
            Assert.AreEqual(2, data.Data.Count);
            Assert.IsNotNull(data.Underlying);

            // 2018-10-20 10:04 AM UTC
            timeProvider.Advance(Time.OneMinute);

            underlyingEnumerator.Enqueue(new Tick {
                Symbol = Symbols.SPY, Value = 280m
            });

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNotNull(enumerator.Current);
            Assert.AreEqual(2, symbolUniverse.TotalLookupCalls);
            data = enumerator.Current;
            Assert.IsNotNull(data);
            Assert.AreEqual(2, data.Data.Count);
            Assert.IsNotNull(data.Underlying);

            enumerator.Dispose();
        }
        public static void StorePresents(IEnumerable <XElement> presentsXml)
        {
            using (var context = new WeddingsPlannerContext())
            {
                foreach (var p in presentsXml)
                {
                    var type            = p.Attribute("type");
                    var invitationIdXml = p.Attribute("invitation-id");
                    if (type == null || invitationIdXml == null)
                    {
                        Console.WriteLine("Error. Invalid data provided");
                        continue;
                    }

                    var invitationId = int.Parse(invitationIdXml.Value);
                    if (invitationId < 0 || invitationId > context.Invitations.Count())
                    {
                        Console.WriteLine("Error. Invalid data provided");
                        continue;
                    }

                    if (type.Value == "cash")
                    {
                        var amount = p.Attribute("amount");
                        if (amount == null)
                        {
                            Console.WriteLine("Error. Invalid data provided");
                            continue;
                        }

                        Cash present = new Cash()
                        {
                            CashAmount = decimal.Parse(amount.Value)
                        };

                        var invitation = context.Invitations.Find(invitationId);
                        invitation.Present = present;
                        try
                        {
                            context.SaveChanges();
                            Console.WriteLine($"Succesfully imported gift from {invitation.Guest.FullName}");
                        }
                        catch (DbEntityValidationException)
                        {
                            Console.WriteLine("Error. Invalid data provided");
                        }
                    }
                    else if (type.Value == "gift")
                    {
                        var nameXml = p.Attribute("present-name");
                        if (nameXml == null)
                        {
                            Console.WriteLine("Error. Invalid data provided");
                            continue;
                        }

                        var presentSize = p.Attribute("size");
                        var size        = PresentSize.NotSpecified;
                        if (presentSize != null)
                        {
                            if (!Enum.TryParse(presentSize.Value, out size))
                            {
                                Console.WriteLine("Error. Invalid data provided");
                                continue;
                            }
                        }

                        var gift = new Gift()
                        {
                            Size = size,
                            Name = nameXml.Value
                        };

                        var invitation = context.Invitations.Find(invitationId);
                        invitation.Present = gift;
                        try
                        {
                            context.SaveChanges();
                            Console.WriteLine($"Succesfully imported gift from {invitation.Guest.FullName}");
                        }
                        catch (DbEntityValidationException)
                        {
                            Console.WriteLine("Error. Invalid data provided");
                        }
                    }
                }
            }
        }
Пример #17
0
        public void ConstructorOnCustomSymbolLength(string currency)
        {
            var cash = new Cash(currency, 0, 0);

            Assert.AreEqual(currency.ToUpper(CultureInfo.InvariantCulture), cash.Symbol);
        }
Пример #18
0
        private void AddTrade(Order order, DateTime time, decimal price, long tradeNo)
        {
            Cash    cash    = _data.GetCash();
            Account account = _data.GetAccount();

            decimal summa            = price * order.LotCount * GetLotSize(order.InsID);
            decimal commission_summa = summa * account.CommPerc / 100;
            decimal total_summa      = summa + commission_summa;

            Holding holding = _data.GetHolding(order.InsID);

            if (order.BuySell == BuySell.Buy)
            {
                if (total_summa > cash.Current)
                {
                    order.Status = OrderStatus.Reject;
                    _data.MarkAsModified(order);
                    RaiseOnOrderChangeEvent(order);
                    _isChangeData = true;
                    return;
                }
            }
            else
            {
                if (!account.IsShortEnable && (holding == null || holding.LotCount < order.LotCount))
                {
                    order.Status = OrderStatus.Reject;
                    _data.MarkAsModified(order);
                    RaiseOnOrderChangeEvent(order);
                    _isChangeData = true;
                    return;
                }
            }

            int oldHold = 0; if (holding != null)
            {
                oldHold = holding.LotCount;
            }

            int tradeID = _data.AddTrade(order.OrderID, time, order.InsID, order.BuySell, order.LotCount, price,
                                         commission_summa, tradeNo);

            order.Status = OrderStatus.Trade;
            _data.MarkAsModified(order);
            RaiseOnOrderChangeEvent(order);

            if (order.BuySell == BuySell.Buy)
            {
                if (holding == null)
                {
                    holding = _data.AddHolding(order);
                }
                else
                {
                    holding.LotCount += order.LotCount;
                }

                cash.Current -= total_summa;
                cash.Buy     += summa;
                cash.BuyComm += commission_summa;
            }
            else
            {
                if (holding == null)
                {
                    holding = _data.AddHolding(order, true);
                }
                else
                {
                    holding.LotCount -= order.LotCount;
                }

                cash.Current  += (summa - commission_summa);
                cash.Sell     += summa;
                cash.SellComm += commission_summa;
            }

            _isChangeData = true;

            RaiseOnTradeEvent(time, order.InsID, (BuySell)order.BuySell, order.LotCount, price);

            int newHold = 0; if (holding != null)

            {
                newHold = holding.LotCount;
            }

            if (oldHold != newHold)
            {
                RaiseOnHoldingChangeEvent(order.InsID, newHold);
            }
        }
Пример #19
0
        /// <summary>
        /// Parses the string info into an asset.
        /// </summary>
        /// <param name="instrumentId"></param>
        /// <returns></returns>
        public static Asset Parse(string instrumentId)
        {
            Asset underlyingAsset;
            var   properties = new PriceableAssetProperties(instrumentId);

            switch (properties.AssetType)
            {
            case AssetTypesEnum.ZeroRate:
            {
                var zeroRate = new Cash {
                    id = instrumentId
                };
                underlyingAsset = zeroRate;
                break;
            }

            case AssetTypesEnum.Xibor:
            case AssetTypesEnum.OIS:
            {
                var rateIndex = new RateIndex {
                    id = instrumentId, term = properties.TermTenor
                };
                underlyingAsset = rateIndex;
                break;
            }

            case AssetTypesEnum.IRSwap:
            case AssetTypesEnum.ClearedIRSwap:
            case AssetTypesEnum.OISSwap:
            case AssetTypesEnum.XccySwap:
            case AssetTypesEnum.SimpleIRSwap:
            case AssetTypesEnum.XccyBasisSwap:
            case AssetTypesEnum.BasisSwap:
            case AssetTypesEnum.ResettableXccyBasisSwap:
            {
                var simpleIRSwap = new SimpleIRSwap {
                    id = instrumentId, term = properties.TermTenor
                };
                underlyingAsset = simpleIRSwap;
                break;
            }

            case AssetTypesEnum.Deposit:
            case AssetTypesEnum.SpreadDeposit:
            case AssetTypesEnum.XccyDepo:
            case AssetTypesEnum.BankBill:
            case AssetTypesEnum.Repo:
            case AssetTypesEnum.RepoSpread:
            {
                var deposit = new Deposit {
                    id = instrumentId, term = properties.TermTenor
                };
                underlyingAsset = deposit;
                break;
            }

            case AssetTypesEnum.SimpleFra:
            case AssetTypesEnum.Fra:
            case AssetTypesEnum.BillFra:
            case AssetTypesEnum.SpreadFra:
            {
                var simpleFra = new SimpleFra {
                    id = instrumentId, startTerm = properties.TermTenor
                };
                if (properties.ForwardIndex == null)
                {
                    throw new ArgumentException("ForwardIndex must be set in the instrumentId " + instrumentId,
                                                nameof(instrumentId));
                }
                simpleFra.endTerm = simpleFra.startTerm.Sum(properties.ForwardIndex);
                underlyingAsset   = simpleFra;
                break;
            }

            case AssetTypesEnum.IRFloor:
            case AssetTypesEnum.IRCap:
            {
                var simpleIRCap = new SimpleIRSwap {
                    id = instrumentId, term = properties.TermTenor
                };
                underlyingAsset = simpleIRCap;
                break;
            }

            case AssetTypesEnum.IRFutureOption:
            case AssetTypesEnum.IRFuture:
            {
                var future = new Future {
                    id = instrumentId
                };
                underlyingAsset = future;
                break;
            }

            case AssetTypesEnum.CommodityFuture:
            case AssetTypesEnum.CommodityFutureSpread:
            {
                var future = new Future {
                    id = instrumentId
                };
                underlyingAsset = future;
                break;
            }

            case AssetTypesEnum.CPIndex:
            {
                var rateIndex = new RateIndex {
                    id = instrumentId, term = properties.TermTenor
                };
                underlyingAsset = rateIndex;
                break;
            }

            case AssetTypesEnum.SimpleCPISwap:
            case AssetTypesEnum.CPISwap:
            case AssetTypesEnum.ZCCPISwap:
            {
                var simpleIRSwap = new SimpleIRSwap {
                    id = instrumentId, term = properties.TermTenor
                };
                underlyingAsset = simpleIRSwap;
                break;
            }

            case AssetTypesEnum.Equity:
            case AssetTypesEnum.EquityForward:
            {
                //  var tenor = results[2];
                var equityAsset = new EquityAsset {
                    id = instrumentId
                };
                underlyingAsset = equityAsset;
                break;
            }

            case AssetTypesEnum.FxSpot:
            case AssetTypesEnum.FxForward:
            {
                //  var tenor = results[2];
                var fxRateAsset = new FxRateAsset {
                    id = instrumentId
                };
                underlyingAsset = fxRateAsset;
                break;
            }

            case AssetTypesEnum.CommoditySpot:
            case AssetTypesEnum.CommodityForward:
            case AssetTypesEnum.CommodityAverageForward:
            case AssetTypesEnum.CommoditySpread:
            {
                var commodityAsset = new Commodity {
                    id = instrumentId
                };
                underlyingAsset = commodityAsset;
                break;
            }

            case AssetTypesEnum.Bond:
            case AssetTypesEnum.BondSpot:
            case AssetTypesEnum.BondForward:
            {
                var bond = new Bond {
                    id = instrumentId
                };
                underlyingAsset = bond;
                break;
            }

            default:
                throw new NotSupportedException($"Asset type {properties.AssetType} is not supported");
            }
            return(underlyingAsset);
        }
Пример #20
0
 public void OnMoneyCollected(Cash c)
 {
     PointBurst burst = (Instantiate(Game.Instance.PointBurst, Vector3.zero, Quaternion.identity) as GameObject).GetComponent<PointBurst>();
     burst.SetUpForCash( Vector2.zero, (float)c.amount );
     PointBursts.Enqueue( burst );
 }
Пример #21
0
        private static TestCaseData[] GetValueTestParameters()
        {
            const decimal delta           = 1m;
            const decimal price           = 1.2345m;
            const int     quantity        = 100;
            const decimal pricePlusDelta  = price + delta;
            const decimal priceMinusDelta = price - delta;
            var           tz = TimeZones.NewYork;

            var time = new DateTime(2016, 2, 4, 16, 0, 0).ConvertToUtc(tz);

            var equity = new Equity(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false),
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            equity.SetMarketPrice(new Tick {
                Value = price
            });

            var gbpCash    = new Cash("GBP", 0, 1.46m);
            var properties = SymbolProperties.GetDefault(gbpCash.Symbol);
            var forex      = new Forex(
                SecurityExchangeHours.AlwaysOpen(tz),
                gbpCash,
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.EURGBP, Resolution.Minute, tz, tz, true, false, false),
                properties,
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            forex.SetMarketPrice(new Tick {
                Value = price
            });

            var eurCash = new Cash("EUR", 0, 1.12m);

            properties = new SymbolProperties("Euro-Bund", eurCash.Symbol, 10, 0.1m, 1);
            var cfd = new Cfd(
                SecurityExchangeHours.AlwaysOpen(tz),
                eurCash,
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.DE10YBEUR, Resolution.Minute, tz, tz, true, false, false),
                properties,
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            cfd.SetMarketPrice(new Tick {
                Value = price
            });
            var multiplierTimesConversionRate = properties.ContractMultiplier * eurCash.ConversionRate;

            var option = new Option(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(
                    typeof(TradeBar),
                    Symbols.SPY_P_192_Feb19_2016,
                    Resolution.Minute,
                    tz,
                    tz,
                    true,
                    false,
                    false
                    ),
                new Cash(Currencies.USD, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            option.SetMarketPrice(new Tick {
                Value = price
            });

            return(new List <ValueTestParameters>
            {
                // equity orders
                new ValueTestParameters("EquityLongMarketOrder", equity, new MarketOrder(Symbols.SPY, quantity, time), quantity * price),
                new ValueTestParameters("EquityShortMarketOrder", equity, new MarketOrder(Symbols.SPY, -quantity, time), -quantity * price),
                new ValueTestParameters("EquityLongLimitOrder", equity, new LimitOrder(Symbols.SPY, quantity, priceMinusDelta, time), quantity * priceMinusDelta),
                new ValueTestParameters("EquityShortLimit Order", equity, new LimitOrder(Symbols.SPY, -quantity, pricePlusDelta, time), -quantity * pricePlusDelta),
                new ValueTestParameters("EquityLongStopLimitOrder", equity, new StopLimitOrder(Symbols.SPY, quantity, .5m * priceMinusDelta, priceMinusDelta, time), quantity * priceMinusDelta),
                new ValueTestParameters("EquityShortStopLimitOrder", equity, new StopLimitOrder(Symbols.SPY, -quantity, 1.5m * pricePlusDelta, pricePlusDelta, time), -quantity * pricePlusDelta),
                new ValueTestParameters("EquityLongStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, quantity, priceMinusDelta, time), quantity * priceMinusDelta),
                new ValueTestParameters("EquityLongStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, quantity, pricePlusDelta, time), quantity * price),
                new ValueTestParameters("EquityShortStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, -quantity, pricePlusDelta, time), -quantity * pricePlusDelta),
                new ValueTestParameters("EquityShortStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, -quantity, priceMinusDelta, time), -quantity * price),

                // forex orders
                new ValueTestParameters("ForexLongMarketOrder", forex, new MarketOrder(Symbols.EURGBP, quantity, time), quantity * price * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortMarketOrder", forex, new MarketOrder(Symbols.EURGBP, -quantity, time), -quantity * price * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongLimitOrder", forex, new LimitOrder(Symbols.EURGBP, quantity, priceMinusDelta, time), quantity * priceMinusDelta * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortLimit Order", forex, new LimitOrder(Symbols.EURGBP, -quantity, pricePlusDelta, time), -quantity * pricePlusDelta * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopLimitOrder", forex, new StopLimitOrder(Symbols.EURGBP, quantity, .5m * priceMinusDelta, priceMinusDelta, time), quantity * priceMinusDelta * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopLimitOrder", forex, new StopLimitOrder(Symbols.EURGBP, -quantity, 1.5m * pricePlusDelta, pricePlusDelta, time), -quantity * pricePlusDelta * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, quantity, priceMinusDelta, time), quantity * priceMinusDelta * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, quantity, pricePlusDelta, time), quantity * price * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, -quantity, pricePlusDelta, time), -quantity * pricePlusDelta * forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, -quantity, priceMinusDelta, time), -quantity * price * forex.QuoteCurrency.ConversionRate),

                // cfd orders
                new ValueTestParameters("CfdLongMarketOrder", cfd, new MarketOrder(Symbols.DE10YBEUR, quantity, time), quantity * price * multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortMarketOrder", cfd, new MarketOrder(Symbols.DE10YBEUR, -quantity, time), -quantity * price * multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongLimitOrder", cfd, new LimitOrder(Symbols.DE10YBEUR, quantity, priceMinusDelta, time), quantity * priceMinusDelta * multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortLimit Order", cfd, new LimitOrder(Symbols.DE10YBEUR, -quantity, pricePlusDelta, time), -quantity * pricePlusDelta * multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopLimitOrder", cfd, new StopLimitOrder(Symbols.DE10YBEUR, quantity, .5m * priceMinusDelta, priceMinusDelta, time), quantity * priceMinusDelta * multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopLimitOrder", cfd, new StopLimitOrder(Symbols.DE10YBEUR, -quantity, 1.5m * pricePlusDelta, pricePlusDelta, time), -quantity * pricePlusDelta * multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, quantity, priceMinusDelta, time), quantity * priceMinusDelta * multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, quantity, pricePlusDelta, time), quantity * price * multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, -quantity, pricePlusDelta, time), -quantity * pricePlusDelta * multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, -quantity, priceMinusDelta, time), -quantity * price * multiplierTimesConversionRate),

                // equity/index option orders
                new ValueTestParameters("OptionLongMarketOrder", option, new MarketOrder(Symbols.SPY_P_192_Feb19_2016, quantity, time), quantity * price),
                new ValueTestParameters("OptionShortMarketOrder", option, new MarketOrder(Symbols.SPY_P_192_Feb19_2016, -quantity, time), -quantity * price),
                new ValueTestParameters("OptionLongLimitOrder", option, new LimitOrder(Symbols.SPY_P_192_Feb19_2016, quantity, priceMinusDelta, time), quantity * priceMinusDelta),
                new ValueTestParameters("OptionShortLimit Order", option, new LimitOrder(Symbols.SPY_P_192_Feb19_2016, -quantity, pricePlusDelta, time), -quantity * pricePlusDelta),
                new ValueTestParameters("OptionLongStopLimitOrder", option, new StopLimitOrder(Symbols.SPY_P_192_Feb19_2016, quantity, .5m * priceMinusDelta, priceMinusDelta, time), quantity * priceMinusDelta),
                new ValueTestParameters("OptionShortStopLimitOrder", option, new StopLimitOrder(Symbols.SPY_P_192_Feb19_2016, -quantity, 1.5m * pricePlusDelta, pricePlusDelta, time), -quantity * pricePlusDelta),
                new ValueTestParameters("OptionLongStopMarketOrder", option, new StopMarketOrder(Symbols.SPY_P_192_Feb19_2016, quantity, priceMinusDelta, time), quantity * priceMinusDelta),
                new ValueTestParameters("OptionLongStopMarketOrder", option, new StopMarketOrder(Symbols.SPY_P_192_Feb19_2016, quantity, pricePlusDelta, time), quantity * price),
                new ValueTestParameters("OptionShortStopMarketOrder", option, new StopMarketOrder(Symbols.SPY_P_192_Feb19_2016, -quantity, pricePlusDelta, time), -quantity * pricePlusDelta),
                new ValueTestParameters("OptionShortStopMarketOrder", option, new StopMarketOrder(Symbols.SPY_P_192_Feb19_2016, -quantity, priceMinusDelta, time), -quantity * price),

                new ValueTestParameters("OptionExercisetOrderPut", option, new OptionExerciseOrder(Symbols.SPY_P_192_Feb19_2016, quantity, time), quantity * option.Symbol.ID.StrikePrice),
                new ValueTestParameters("OptionAssignmentOrderPut", option, new OptionExerciseOrder(Symbols.SPY_P_192_Feb19_2016, -quantity, time), -quantity * option.Symbol.ID.StrikePrice),
                new ValueTestParameters("OptionExercisetOrderCall", option, new OptionExerciseOrder(Symbols.SPY_C_192_Feb19_2016, quantity, time), quantity * option.Symbol.ID.StrikePrice),
                new ValueTestParameters("OptionAssignmentOrderCall", option, new OptionExerciseOrder(Symbols.SPY_C_192_Feb19_2016, -quantity, time), -quantity * option.Symbol.ID.StrikePrice),
            }.Select(x => new TestCaseData(x).SetName(x.Name)).ToArray());
        }
Пример #22
0
    public SageWoodResponse PaySageWoodElectricity(string MNo, string amount, string transactionId)
    {
        SageWoodResponse woodResponse = new SageWoodResponse();
        string           rawRequest;
        DatabaseHandler  dh = new DatabaseHandler();

        try
        {
            string    clientId     = "2019112800001";
            string    opName       = "UDEMO";
            string    password     = "******";
            string    meterno      = "14012018064";
            string    date         = DateTime.Now.ToString("yyyyMMddHHmmss").ToString();
            string    randomnumber = GenerateRandomNumber().ToString();
            MeterInfo custInfo     = new MeterInfo();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback
                                                                          (delegate { return(true); });
            EANDeviceID deviceId = new EANDeviceID();
            deviceId.ean = clientId;
            GenericDeviceID genericDeviceID = new GenericDeviceID();
            genericDeviceID.id = clientId;
            PurchaseValueCurrency purchaseValue = new PurchaseValueCurrency();
            purchaseValue.amt        = new Currency();
            purchaseValue.amt.symbol = "UGX";
            purchaseValue.amt.value  = Decimal.Parse("10");
            Electricity electricity = new Electricity();
            MsgID       msg         = new MsgID();
            msg.dateTime     = DateTime.Now.ToString("yyyyMMddHHmmss").ToString();
            msg.uniqueNumber = randomnumber;
            AuthCred authCred = new AuthCred();
            authCred.opName      = opName;
            authCred.password    = password;
            authCred.newPassword = "";
            MsgID       messageId = msg;
            AuthCred    creds     = authCred;
            MeterDetail meter     = new MeterDetail();
            meter.msno = meterno;
            Cash pay = new Cash();
            pay.tenderAmt        = new Currency();
            pay.tenderAmt.symbol = "UGX";
            pay.tenderAmt.value  = Decimal.Parse("100");
            VendIDMethod vendIDMethod = new VendIDMethod();
            vendIDMethod.meterIdentifier = meter;
            CreditVendReq    request  = new CreditVendReq();
            XMLVendService21 sageWood = new XMLVendService21();
            request.clientID      = deviceId;
            request.msgID         = msg;
            request.authCred      = authCred;
            request.terminalID    = genericDeviceID;
            request.idMethod      = vendIDMethod;
            request.resource      = electricity;
            request.purchaseValue = purchaseValue;
            request.payType       = pay;
            rawRequest            = XmlCreditVend(request);
            CreditVendResp    response     = sageWood.CreditVendRequest(request);
            Tx                tx           = response.creditVendReceipt.transactions.tx[0];
            CreditVendTx      creditVendTx = (CreditVendTx)tx;
            CreditVendReceipt resp         = response.creditVendReceipt;
            STS1Token         sts1Token    = (STS1Token)creditVendTx.creditTokenIssue.token;
            woodResponse.Token     = sts1Token.stsCipher;
            woodResponse.ReceiptNo = response.creditVendReceipt.receiptNo;
            woodResponse.Units     = creditVendTx.creditTokenIssue.units.value.ToString();
            string rawResponse = XmlCreditVendResp(response);

            //log raw request and response
            dh.LogRequestAndResponse("SAGEWOOD", transactionId, rawRequest, rawResponse);
        }
        catch (SoapException soapException)
        {
            // XMLVendFaultResp xmlVendFaultResp = XMLDeserialize.Deserialize(soapException.Detail);

            // if (xmlVendFaultResp.fault.GetType() ==
            //typeof(UnknownMeterEx))
            // {
            //     Console.WriteLine("Unknown Meter Serial Number!");
            // }
            // else
            // {
            //     string fert = xmlVendFaultResp.fault.GetType().ToString();
            //     Console.WriteLine("Unexpected XMLVend Fault Response" +
            //                 "received: (" + xmlVendFaultResp.fault.GetType().ToString()
            //     + ")" + xmlVendFaultResp.fault.desc);
            // }
            dh.LogError(soapException.Detail.InnerXml, transactionId, DateTime.Now, "SAGEWOOD");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex);
            dh.LogError(ex.ToString(), transactionId, DateTime.Now, "SAGEWOOD");
        }
        return(woodResponse);
    }
Пример #23
0
        private void ShowGMCashInfo(Cash cash)
        {
            txtNav.Text = cash.nav.ToString("N");
            txtAvailable.Text = cash.available.ToString("N");
            txtFrozen.Text = cash.frozen.ToString("N");
            txtOrderFrozen.Text = cash.order_frozen.ToString("N");

            txtPnl.Text = cash.pnl.ToString("N");
            txtFpnl.Text = cash.fpnl.ToString("N");
        }
Пример #24
0
 public void ConstructorThrowsOnSymbolTooShort()
 {
     var cash = new Cash("s", 0, 0);
 }
Пример #25
0
 public void OnMoneyCollected( Cash c )
 {
     Cash += (int)c.amount;
 }
Пример #26
0
        /// <summary>
        /// Parses the string info into an asset.
        /// </summary>
        /// <param name="instrumentId"></param>
        /// <param name="value"></param>
        /// <param name="adjustment"></param>
        /// <returns></returns>
        public static Pair <Asset, BasicAssetValuation> Parse(string instrumentId, decimal value, decimal?adjustment)
        {
            const string rateQuotationType       = PriceableSimpleRateAsset.RateQuotationType;
            const string volatilityQuotationType = PriceableCapRateAsset.VolatilityQuotationType;
            Asset        underlyingAsset;
            decimal      additional = 0.0m;

            if (adjustment != null)
            {
                additional = (decimal)adjustment;
            }
            var listBasicQuotations = new List <BasicQuotation>();
            var properties          = new PriceableAssetProperties(instrumentId);

            switch (properties.AssetType)
            {
            //This is in place to handle volatility curves where the tenor is the expiry.
            case AssetTypesEnum.Period:
            {
                //There is no underlying asset.
                underlyingAsset = null;
                listBasicQuotations.Add(BasicQuotationHelper.Create(instrumentId, value, volatilityQuotationType, "LognormalVolatility"));
                break;
            }

            case AssetTypesEnum.ZeroRate:
            {
                underlyingAsset = new Cash {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "DecimalRate"));
                break;
            }

            case AssetTypesEnum.Xibor:
            case AssetTypesEnum.OIS:
            {
                underlyingAsset = new RateIndex {
                    id = instrumentId, term = properties.TermTenor
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "DecimalRate"));
                break;
            }

            case AssetTypesEnum.IRSwap:
            case AssetTypesEnum.ClearedIRSwap:
            case AssetTypesEnum.OISSwap:
            case AssetTypesEnum.XccySwap:
            case AssetTypesEnum.SimpleIRSwap:
            case AssetTypesEnum.XccyBasisSwap:
            case AssetTypesEnum.BasisSwap:
            case AssetTypesEnum.ResettableXccyBasisSwap:
            {
                underlyingAsset = new SimpleIRSwap {
                    id = instrumentId, term = properties.TermTenor
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "DecimalRate"));
                break;
            }

            case AssetTypesEnum.Caplet:
            case AssetTypesEnum.Floorlet:
            case AssetTypesEnum.BillCaplet:
            case AssetTypesEnum.BillFloorlet:
            {
                underlyingAsset = new SimpleFra
                {
                    id        = instrumentId,
                    startTerm = properties.TermTenor,
                    endTerm   = properties.TermTenor.Sum(properties.ForwardIndex)
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value, volatilityQuotationType, "LognormalVolatility"));
                if (adjustment != null)
                {
                    listBasicQuotations.Add(BasicQuotationHelper.Create(additional, "Strike", "DecimalRate"));
                }
                break;
            }

            case AssetTypesEnum.Deposit:
            case AssetTypesEnum.SpreadDeposit:
            case AssetTypesEnum.XccyDepo:
            case AssetTypesEnum.BankBill:
            case AssetTypesEnum.Repo:
            case AssetTypesEnum.RepoSpread:
            {
                underlyingAsset = new Deposit {
                    id = instrumentId, term = properties.TermTenor
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "DecimalRate"));
                break;
            }

            case AssetTypesEnum.SimpleFra:
            case AssetTypesEnum.Fra:
            case AssetTypesEnum.BillFra:
            case AssetTypesEnum.SpreadFra:
            {
                underlyingAsset = new SimpleFra
                {
                    id        = instrumentId,
                    startTerm = properties.TermTenor,
                    endTerm   = properties.TermTenor.Sum(properties.ForwardIndex)      //TODO this restricts the perios to be the same!!!
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "DecimalRate"));
                break;
            }

            case AssetTypesEnum.Swaption:
            {
                underlyingAsset = new SimpleIRSwap {
                    id = instrumentId, term = properties.TermTenor
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value, volatilityQuotationType, "LognormalVolatility"));
                if (adjustment != null)
                {
                    listBasicQuotations.Add(BasicQuotationHelper.Create(additional, "Strike", "DecimalRate"));
                }
                break;
            }

            case AssetTypesEnum.IRFloor:
            case AssetTypesEnum.IRCap:
            {
                underlyingAsset = new SimpleIRSwap {
                    id = instrumentId, term = properties.TermTenor
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value, volatilityQuotationType, "LognormalVolatility"));
                if (adjustment != null)
                {
                    listBasicQuotations.Add(BasicQuotationHelper.Create(additional, "Strike", "DecimalRate"));
                }
                break;
            }

            case AssetTypesEnum.IRFutureOption:
            case AssetTypesEnum.IRCallFutureOption:
            case AssetTypesEnum.IRPutFutureOption:
            {
                underlyingAsset = new Future {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value, volatilityQuotationType, "LognormalVolatility"));
                if (adjustment != null)
                {
                    listBasicQuotations.Add(BasicQuotationHelper.Create(additional, "Strike", "DecimalRate"));
                }
                break;
            }

            case AssetTypesEnum.IRFuture:
            {
                underlyingAsset = new Future {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "DecimalRate"));
                if (adjustment != null)
                {
                    listBasicQuotations.Add(BasicQuotationHelper.Create(additional, "Volatility", "LognormalVolatility"));
                }
                break;
            }

            case AssetTypesEnum.CommodityFuture:
            case AssetTypesEnum.CommodityFutureSpread:
            {
                underlyingAsset = new Future {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "DecimalRate"));
                break;
            }

            case AssetTypesEnum.CPIndex:
            {
                underlyingAsset = new RateIndex {
                    id = instrumentId, term = properties.TermTenor
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "DecimalRate"));
                break;
            }

            case AssetTypesEnum.SimpleCPISwap:
            case AssetTypesEnum.CPISwap:
            case AssetTypesEnum.ZCCPISwap:
            {
                underlyingAsset = new SimpleIRSwap {
                    id = instrumentId, term = properties.TermTenor
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "DecimalRate"));
                break;
            }

            case AssetTypesEnum.FxSpot:
            case AssetTypesEnum.FxForward:
            {
                underlyingAsset = new FxRateAsset {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "FxRate"));
                break;
            }

            case AssetTypesEnum.Equity:
            case AssetTypesEnum.EquityForward:
            {
                underlyingAsset = new EquityAsset {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "Price"));
                break;
            }

            case AssetTypesEnum.CommoditySpot:
            case AssetTypesEnum.CommodityForward:
            case AssetTypesEnum.CommodityAverageForward:
            case AssetTypesEnum.CommoditySpread:
            {
                underlyingAsset = new Commodity {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "Price"));
                break;
            }

            case AssetTypesEnum.Bond:
            case AssetTypesEnum.BondSpot:
            case AssetTypesEnum.BondForward:
            {
                underlyingAsset = new Bond {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "DecimalRate"));        //Changed from DirtyPrice.
                break;
            }

            case AssetTypesEnum.Lease:
            {
                underlyingAsset = new Lease {
                    id = instrumentId
                };
                listBasicQuotations.Add(BasicQuotationHelper.Create(value + additional, rateQuotationType, "Price"));
                break;
            }

            default:
                throw new NotSupportedException($"Asset type {properties.AssetType} is not supported");
            }
            var id = underlyingAsset?.id;

            if (underlyingAsset == null)
            {
                id = listBasicQuotations[0].id;
            }
            return(new Pair <Asset, BasicAssetValuation>(underlyingAsset, BasicAssetValuationHelper.Create(id, listBasicQuotations.ToArray())));
        }
Пример #27
0
 public void Setup()
 {
     f14CHF = new Cash(14, "CHF");
     Console.WriteLine("This is SetUp");
 }
Пример #28
0
        public MapleItem Search(int id, Func <int, int[]> getDroppedBy)
        {
            WZProperty stringWz = WZ.Resolve("String");

            string    idString = id.ToString();
            MapleItem result   = null;

            WZProperty item = (stringWz.Resolve("Eqp/Eqp") ?? stringWz.Resolve("Item/Eqp")).Children.FirstOrDefault(c => c.Children.Any(b => b.NameWithoutExtension.Equals(idString)))?.Resolve(idString);

            if (item != null)
            {
                result = Equip.Parse(item);
            }

            if (result == null)
            {
                item = (stringWz.Resolve("Etc/Etc") ?? stringWz.Resolve("Item/Etc"))?.Resolve(idString);
                if (item != null)
                {
                    result = Etc.Parse(item);
                }
            }

            if (result == null)
            {
                item = (stringWz.Resolve("Ins") ?? stringWz.Resolve("Item/Ins")).Resolve(idString);
                if (item != null)
                {
                    result = Install.Parse(item);
                }
            }

            if (result == null)
            {
                item = (stringWz.Resolve("Cash") ?? stringWz.Resolve("Item/Cash")).Resolve(idString);
                if (item != null)
                {
                    result = Cash.Parse(item);
                }
            }

            if (result == null)
            {
                item = (stringWz.Resolve("Consume") ?? stringWz.Resolve("Item/Con")).Resolve(idString);
                if (item != null)
                {
                    result = Consume.Parse(item);
                }
            }

            if (result == null)
            {
                item = (stringWz.Resolve("Pet") ?? stringWz.Resolve("Item/Pet")).Resolve(idString);
                if (item != null)
                {
                    result = Pet.Parse(item);
                }
            }

            MobFactory mobs = new MobFactory();

            mobs.CloneWZFrom(this);

            if (result != null && result.MetaInfo != null)
            {
                result.MetaInfo.DroppedBy = getDroppedBy(id)?.Join(mobs.GetMobs().Where(c => c != null), c => c, c => c.Id, (a, b) => b)?.ToArray();
            }

            return(result);
        }
Пример #29
0
 private void SaveAsset(Cash cash)
 {
     Cash.Add(cash);
     SaveChanges();
 }
Пример #30
0
    protected void OnRunReferenceItemDialog(object sender, Reference.RunReferenceItemDlgEventArgs e)
    {
        ResponseType Result;
        switch (e.TableName) {
        case "meter_types":
            MeterType MeterTypeEdit = new MeterType (e.NewItem);
            if (!e.NewItem)
                MeterTypeEdit.Fill (e.ItemId);
            MeterTypeEdit.Show ();
            Result = (ResponseType)MeterTypeEdit.Run ();
            MeterTypeEdit.Destroy ();
            break;
        case "contact_persons":
            Contact ContactEdit = new Contact ();
            ContactEdit.NewContact = e.NewItem;
            if (!e.NewItem)
                ContactEdit.ContactFill (e.ItemId);
            ContactEdit.Show ();
            Result = (ResponseType)ContactEdit.Run ();
            ContactEdit.Destroy ();
            break;
        case "lessees":
            lessee LesseeEdit = new lessee ();
            LesseeEdit.NewLessee = e.NewItem;
            if (!e.NewItem)
                LesseeEdit.LesseeFill (e.ItemId);
            LesseeEdit.Show ();
            Result = (ResponseType)LesseeEdit.Run ();
            LesseeEdit.Destroy ();
            break;
        case "services":
            Service ServiceEdit = new Service ();
            ServiceEdit.NewService = e.NewItem;
            if (!e.NewItem)
                ServiceEdit.ServiceFill (e.ItemId);
            ServiceEdit.Show ();
            Result = (ResponseType)ServiceEdit.Run ();
            ServiceEdit.Destroy ();
            break;
        case "cash":
            Cash CashEdit = new Cash ();
            CashEdit.NewItem = e.NewItem;
            if (!e.NewItem)
                CashEdit.Fill (e.ItemId);
            CashEdit.Show ();
            Result = (ResponseType)CashEdit.Run ();
            CashEdit.Destroy ();
            break;

        default:
            Result = ResponseType.None;
            break;
        }
        e.Result = Result;
    }
Пример #31
0
 /// <summary>
 /// Constructor for the option security
 /// </summary>
 /// <param name="exchangeHours">Defines the hours this exchange is open</param>
 /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
 /// <param name="config">The subscription configuration for this security</param>
 /// <param name="symbolProperties">The symbol properties for this security</param>
 public Option(SecurityExchangeHours exchangeHours, SubscriptionDataConfig config, Cash quoteCurrency, SymbolProperties symbolProperties)
     : base(config,
            quoteCurrency,
            symbolProperties,
            new OptionExchange(exchangeHours),
            new OptionCache(),
            new SecurityPortfolioModel(),
            new ImmediateFillModel(),
            new InteractiveBrokersFeeModel(),
            new SpreadSlippageModel(),
            new ImmediateSettlementModel(),
            Securities.VolatilityModel.Null,
            new SecurityMarginModel(2m),
            new OptionDataFilter()
            )
 {
     PriceModel     = new CurrentPriceOptionPriceModel();
     ContractFilter = new StrikeExpiryOptionFilter(-5, 5, TimeSpan.Zero, TimeSpan.FromDays(35));
 }
        public void EditCash(float cash_edit, CashTransactionType ctt = CashTransactionType.Edit)
        {
            //Error check
            if (cash_edit < 0)
            {
                if (Math.Abs(cash_edit) > Cash)
                {
                    throw new Exception("Trying to withdraw more cash than portfolio has.  Trying to withdraw: $" + cash_edit.ToString("#,##0.00") + ", portfolio has $" + Cash.ToString("#,##0.00"));
                }
            }

            //Perform the edit!
            Cash = Cash + cash_edit;
            CashTransaction ct = new CashTransaction();

            ct.ChangeType = ctt;
            ct.UpdateTransactionTime();
            ct.CashChange = cash_edit;
            CashTransactionLog.Add(ct);
        }
Пример #33
0
        public void DoesNotEmitInvalidData()
        {
            var startTime = new DateTime(2014, 06, 06, 0, 0, 0);
            var endTime   = new DateTime(2014, 06, 09, 20, 0, 0);

            var canonicalSymbol = Symbol.Create("AAPL", SecurityType.Option, Market.USA, "?AAPL");

            var quoteCurrency = new Cash(Currencies.USD, 0, 1);
            var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, canonicalSymbol, SecurityType.Option);
            var config        = new SubscriptionDataConfig(
                typeof(ZipEntryName),
                canonicalSymbol,
                Resolution.Minute,
                TimeZones.Utc,
                TimeZones.NewYork,
                true,
                false,
                false,
                false,
                TickType.Quote,
                false,
                DataNormalizationMode.Raw
                );

            var option = new Option(
                canonicalSymbol,
                exchangeHours,
                quoteCurrency,
                new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache(),
                null
                );

            var dataProvider          = TestGlobals.DataProvider;
            var enumeratorFactory     = new BaseDataSubscriptionEnumeratorFactory(false, MapFileResolver.Create(Globals.DataFolder, Market.USA), TestGlobals.FactorFileProvider);
            var fillForwardResolution = Ref.CreateReadOnly(() => Resolution.Minute.ToTimeSpan());
            Func <SubscriptionRequest, IEnumerator <BaseData> > underlyingEnumeratorFunc = (req) =>
            {
                var input = enumeratorFactory.CreateEnumerator(req, dataProvider);

                input = new BaseDataCollectionAggregatorEnumerator(input, req.Configuration.Symbol);
                return(new FillForwardEnumerator(
                           input,
                           option.Exchange,
                           fillForwardResolution,
                           false,
                           endTime,
                           Resolution.Minute.ToTimeSpan(),
                           TimeZones.Utc));
            };
            var factory = new OptionChainUniverseSubscriptionEnumeratorFactory(underlyingEnumeratorFunc);

            var request    = new SubscriptionRequest(true, null, option, config, startTime, endTime);
            var enumerator = factory.CreateEnumerator(request, new DefaultDataProvider());

            var emittedCount = 0;

            foreach (var data in enumerator.AsEnumerable())
            {
                emittedCount++;
                var optionData = data as OptionChainUniverseDataCollection;

                Assert.IsNotNull(optionData);
                Assert.IsNotNull(optionData.Underlying);
                Assert.AreNotEqual(0, optionData.Data.Count);
            }

            // 9:30 to 15:59 -> 6.5 hours * 60 => 390 minutes * 2 days = 780
            Assert.AreEqual(780, emittedCount);
        }
        public async Task TradeEquityAsync(string symbol, int quantity, TransactionType order_type)
        {
            Equity e = Equity.Create(symbol);

            try
            {
                await e.DownloadSummaryAsync();
            }
            catch
            {
                throw new Exception("Critical error while fetching equity '" + symbol + "'.  Does this equity exist?");
            }


            if (order_type == TransactionType.Buy)
            {
                //Be sure we have enough cash to buy
                float cash_needed = e.Summary.Price * quantity;
                if (Cash < cash_needed)
                {
                    throw new Exception("You do not have enough cash to execute this buy order of " + symbol.ToUpper() + ".  Cash needed: $" + cash_needed.ToString("#,##0.00") + ".  Cash balance: $" + Cash.ToString("#,##0.00"));
                }


                AddSharesAndCalculateNewAverageCostBasis(symbol.ToUpper().Trim(), quantity, e.Summary.Price, DateTimeOffset.Now);

                //Edit cash and add the shares we are buying to the balane
                Cash = Cash - cash_needed;
            }
            else if (order_type == TransactionType.Sell)
            {
                //Find our holding
                EquityHolding eh = null;
                foreach (EquityHolding ceh in EquityHoldings)
                {
                    if (ceh.Symbol.ToUpper() == symbol.ToUpper())
                    {
                        eh = ceh;
                    }
                }

                //Throw an error if we do not have any of those shares.
                if (eh == null)
                {
                    throw new Exception("You do not have any shares of " + symbol.ToUpper() + " to sell.");
                }

                //Throw an error if we do not have enough shares
                if (eh.Quantity < quantity)
                {
                    throw new Exception("You do not have " + quantity.ToString() + " shares to sell!  You only have " + eh.Quantity.ToString() + " shares.");
                }

                //Execute the transaction
                Cash        = Cash + (quantity * e.Summary.Price);
                eh.Quantity = eh.Quantity - quantity;

                //Save the transaction log
                EquityTransaction et = new EquityTransaction();
                et.UpdateTransactionTime();
                et.StockSymbol     = symbol.ToUpper().Trim();
                et.OrderType       = TransactionType.Sell;
                et.Quantity        = quantity;
                et.PriceExecutedAt = e.Summary.Price;
                EquityTransactionLog.Add(et);

                //Remove the holding if it now 0
                if (eh.Quantity == 0)
                {
                    EquityHoldings.Remove(eh);
                }
            }

            //Take out the commission (if any)
            if (TradeCost > 0)
            {
                EditCash(TradeCost * -1, CashTransactionType.TradingRelatedCharge);
            }
        }
        protected void add_Callback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            List <Payment> payments;

            if (e.Parameters == "clear")
            {
                Session["listPayment"] = null;
            }

            #region Add Payment

            else
            {
                payments = new List <Payment>();
                decimal amount = 0.0M, amountCheque = 0.0M, amountChequeForTransaction = 0.0M;
                if (cbxPayMethod.SelectedItem == null)
                {
                    throw new ApplicationException("เลือกวิธีการชำระเงิน");
                }
                String payMethod = (String)cbxPayMethod.SelectedItem.Value;
                String payType   = (cbxPayType.SelectedItem == null ? "Cash" : (String)cbxPayType.SelectedItem.Value);
                //Party payee = Organization.FindByCode(iSabayaContext, CommonConstants.PayeeOrgCode);
                Payment payment = null;

                #region BankDeposit

                if (payMethod.Equals("BankAccountDeposit"))
                {
                    BankDeposit bankDeposit = new BankDeposit();
                    bankDeposit.PaymentType = "BankDeposit";
                    if (payType.Equals("Cash"))
                    {
                        amount                  = (decimal)spnAmount.Value;
                        payment                 = new Cash();
                        bankDeposit.Amount      = new Money(amount, iSabayaContext.imSabayaConfig.DefaultCurrency);
                        bankDeposit.BankAccount = ToBankAccount;
                        bankDeposit.PaymentDate = paymentDate.Date;
                        bankDeposit.AmountForThisTransaction = amount;
                    }
                    else if (payType.Equals("Cheque"))
                    {
                        amountCheque = (decimal)spnChequeAmount.Value;
                        amountChequeForTransaction = (decimal)spnChequeUsedAmount.Value;
                        Cheque c = FindByChequeNo(iSabayaContext, bteChequeNo.Text);
                        if (c == null) // New Cheque
                        {
                            payment = new Cheque();
                            Cheque cheque = (Cheque)payment;
                            cheque.Amount     = new Money(amountCheque, iSabayaContext.imSabayaConfig.DefaultCurrency);
                            cheque.StatusDate = DateTime.Now;
                            cheque.AmountForThisTransaction = amountChequeForTransaction;
                            cheque.Bank             = BankControl1.Organization;
                            cheque.ChequeNo         = bteChequeNo.Text;
                            cheque.ChequeDate       = (DateTime)ChequeDate.Date;
                            cheque.PaymentDate      = paymentDate.Date;
                            cheque.PrintChequeDate  = TimeInterval.MaxDate;
                            bankDeposit.Amount      = cheque.Amount;
                            bankDeposit.BankAccount = ToBankAccount;
                            bankDeposit.PaymentDate = paymentDate.Date;
                            bankDeposit.DueDate     = cheque.DueDate.Date;
                            bankDeposit.AmountForThisTransaction = amountChequeForTransaction;
                            bankDeposit.Cheque = cheque;
                        }
                        else // 0ld Cheque
                        {
                            c.AmountForThisTransaction           = amountChequeForTransaction;
                            bankDeposit.Amount                   = c.Amount;
                            bankDeposit.PaymentDate              = paymentDate.Date;
                            bankDeposit.DueDate                  = c.DueDate.Date;
                            bankDeposit.AmountForThisTransaction = amountChequeForTransaction;
                            bankDeposit.Cheque                   = c;
                        }
                    }
                    payments.Add(bankDeposit);
                }

                #endregion BankDeposit

                #region FundTransfer

                else if (payMethod.Equals("FundTransfer"))
                {
                    amount = (decimal)spnAmount.Value;
                    FundTransfer fundTransfer = new FundTransfer();
                    fundTransfer.PaymentType              = "FundTransfer";
                    fundTransfer.FromBankAccount          = FromBankAccount;
                    fundTransfer.ToBankAccount            = ToBankAccount;
                    fundTransfer.Amount                   = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);
                    fundTransfer.AmountForThisTransaction = fundTransfer.Amount.Amount;
                    fundTransfer.PaymentDate              = DateTime.Now;
                    if (fundTransfer.FromBankAccount == null)
                    {
                        throw new ApplicationException("ไม่พบบัญชีต้นทาง");
                    }
                    if (fundTransfer.ToBankAccount == null)
                    {
                        throw new ApplicationException("ไม่พบบัญชีปลายทาง");
                    }
                    payments.Add(fundTransfer);
                }

                #endregion FundTransfer

                #region Cash

                else if (payMethod.Equals("Cash"))
                {
                    amount  = (decimal)spnAmount.Value;
                    payment = new Cash();
                    Cash cash = (Cash)payment;
                    cash.PaymentType = "Cash";
                    cash.Amount      = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);
                    cash.PaymentDate = DateTime.Now.Date;
                    cash.AmountForThisTransaction = amount;
                    payments.Add(cash);
                }

                #endregion Cash

                #region Cheque

                else if (payMethod.Equals("Cheque"))
                {
                    amountCheque = (decimal)spnChequeAmount.Value;
                    amountChequeForTransaction = (decimal)spnChequeUsedAmount.Value;
                    Cheque c = FindByChequeNo(iSabayaContext, bteChequeNo.Text);
                    if (c == null) // New cheque
                    {
                        payment             = new Cheque();
                        payment.PaymentType = "Cheque";
                        Cheque cheque = (Cheque)payment;
                        cheque.Amount                   = new Money(amountCheque, iSabayaContext.imSabayaConfig.DefaultCurrency);
                        cheque.PaymentDate              = DateTime.Now.Date;
                        cheque.StatusDate               = DateTime.Now;
                        cheque.PrintChequeDate          = TimeInterval.MinDate;
                        cheque.AmountForThisTransaction = amountChequeForTransaction;
                        cheque.Bank            = BankControl1.Organization;
                        cheque.ChequeNo        = bteChequeNo.Text;
                        cheque.ChequeDate      = (DateTime)ChequeDate.Date;
                        cheque.PayableTo       = "";
                        cheque.PrintChequeDate = TimeInterval.MaxDate;
                        payments.Add(cheque);
                    }
                    else
                    {
                        c.AmountForThisTransaction = amountChequeForTransaction;
                        payments.Add(c);
                    }
                }

                #endregion Cheque

                #region BillPayment

                else if (payMethod.Equals("BillPayment"))
                {
                    //no class
                    BillPayment billPayment = new BillPayment();
                    billPayment.PaymentType = "Bill Payment";
                    if (payType.Equals("Cash"))
                    {
                        amount  = (decimal)spnAmount.Value;
                        payment = new Cash();
                        Cash cash = (Cash)payment;
                        billPayment.Amount      = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);
                        billPayment.PaymentDate = paymentDate.Date.Date;
                        billPayment.AmountForThisTransaction = amount;
                    }
                    else if (payType.Equals("Cheque"))
                    {
                        amountCheque = (decimal)spnChequeAmount.Value;
                        amountChequeForTransaction = (decimal)spnChequeUsedAmount.Value;
                        Cheque c = FindByChequeNo(iSabayaContext, bteChequeNo.Text);
                        if (c == null) // New cheque
                        {
                            payment = new Cheque();
                            Cheque cheque = (Cheque)payment;
                            cheque.Amount      = new Money(amountCheque, iSabayaContext.imSabayaConfig.DefaultCurrency);
                            cheque.PaymentDate = paymentDate.Date.Date;
                            cheque.StatusDate  = paymentDate.Date.Date;
                            cheque.AmountForThisTransaction = amountChequeForTransaction;
                            cheque.Bank            = BankControl1.Organization;
                            cheque.ChequeNo        = bteChequeNo.Text;
                            cheque.ChequeDate      = (DateTime)ChequeDate.Date;
                            cheque.PayableTo       = "";
                            cheque.PrintChequeDate = TimeInterval.MaxDate;
                            //special for bank deposit
                            billPayment.Amount      = cheque.Amount;
                            billPayment.PaymentDate = cheque.PaymentDate;
                            billPayment.DueDate     = cheque.DueDate.Date;
                            billPayment.AmountForThisTransaction = amountChequeForTransaction;
                            //special for bank deposit
                            billPayment.Cheque = cheque;
                        }
                        else // Old cheque
                        {
                            c.AmountForThisTransaction = amountChequeForTransaction;
                            billPayment.Cheque         = c;
                        }
                    }
                    payments.Add(billPayment);
                }

                #endregion BillPayment

                Session["listPayment"] = payments;
            }

            #endregion Add Payment

            gridPaymetod.DataSource = Session["listPayment"];
            gridPaymetod.DataBind();
        }
Пример #36
0
    private void GetExcelData(DataTable dt)
    {
        string         MM      = DateTime.Now.ToString("MM");
        ListCafeEntity entity  = new ListCafeEntity();
        Cash           BllCash = new Cash();

        for (int i = 1; i < dt.Rows.Count; i++)
        {
            if (MM == "01")
            {
                entity.JanPlan  = dt.Rows[i][1].ToString().Trim();
                entity.FebPlan  = dt.Rows[i][2].ToString().Trim();
                entity.MarPlan  = dt.Rows[i][3].ToString().Trim();
                entity.AprPlan  = dt.Rows[i][4].ToString().Trim();
                entity.MayPlan  = dt.Rows[i][5].ToString().Trim();
                entity.JunPlan  = dt.Rows[i][6].ToString().Trim();
                entity.JulPlan  = dt.Rows[i][7].ToString().Trim();
                entity.AugPlan  = dt.Rows[i][8].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][9].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][10].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][11].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][12].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][13].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][14].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][15].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][16].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][17].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][18].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][19].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][20].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][21].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][22].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][23].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][24].ToString().Trim();
            }
            else if (MM == "02")
            {
                entity.JanPlan  = dt.Rows[i][1].ToString().Trim();
                entity.FebPlan  = dt.Rows[i][2].ToString().Trim();
                entity.MarPlan  = dt.Rows[i][3].ToString().Trim();
                entity.AprPlan  = dt.Rows[i][4].ToString().Trim();
                entity.MayPlan  = dt.Rows[i][5].ToString().Trim();
                entity.JunPlan  = dt.Rows[i][6].ToString().Trim();
                entity.JulPlan  = dt.Rows[i][7].ToString().Trim();
                entity.AugPlan  = dt.Rows[i][8].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][9].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][10].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][11].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][12].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][13].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][14].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][15].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][16].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][17].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][18].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][19].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][20].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][21].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][22].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][23].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][24].ToString().Trim();
            }
            else if (MM == "03")
            {
                entity.FebPlan  = dt.Rows[i][1].ToString().Trim();
                entity.MarPlan  = dt.Rows[i][2].ToString().Trim();
                entity.AprPlan  = dt.Rows[i][3].ToString().Trim();
                entity.MayPlan  = dt.Rows[i][4].ToString().Trim();
                entity.JunPlan  = dt.Rows[i][5].ToString().Trim();
                entity.JulPlan  = dt.Rows[i][6].ToString().Trim();
                entity.AugPlan  = dt.Rows[i][7].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][8].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][9].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][10].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][11].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][12].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][13].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][14].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][15].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][16].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][17].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][18].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][19].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][20].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][21].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][22].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][23].ToString().Trim();
            }
            else if (MM == "04")
            {
                entity.MarPlan  = dt.Rows[i][1].ToString().Trim();
                entity.AprPlan  = dt.Rows[i][2].ToString().Trim();
                entity.MayPlan  = dt.Rows[i][3].ToString().Trim();
                entity.JunPlan  = dt.Rows[i][4].ToString().Trim();
                entity.JulPlan  = dt.Rows[i][5].ToString().Trim();
                entity.AugPlan  = dt.Rows[i][6].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][7].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][8].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][9].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][10].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][11].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][12].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][13].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][14].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][15].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][16].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][17].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][18].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][19].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][20].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][21].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][22].ToString().Trim();
            }
            else if (MM == "05")
            {
                entity.AprPlan  = dt.Rows[i][1].ToString().Trim();
                entity.MayPlan  = dt.Rows[i][2].ToString().Trim();
                entity.JunPlan  = dt.Rows[i][3].ToString().Trim();
                entity.JulPlan  = dt.Rows[i][4].ToString().Trim();
                entity.AugPlan  = dt.Rows[i][5].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][6].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][7].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][8].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][9].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][10].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][11].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][12].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][13].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][14].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][15].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][16].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][17].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][18].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][19].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][20].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][21].ToString().Trim();
            }
            else if (MM == "06")
            {
                entity.MayPlan  = dt.Rows[i][1].ToString().Trim();
                entity.JunPlan  = dt.Rows[i][2].ToString().Trim();
                entity.JulPlan  = dt.Rows[i][3].ToString().Trim();
                entity.AugPlan  = dt.Rows[i][4].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][5].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][6].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][7].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][8].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][9].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][10].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][11].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][12].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][13].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][14].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][15].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][16].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][17].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][18].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][19].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][20].ToString().Trim();
            }
            else if (MM == "07")
            {
                entity.JunPlan  = dt.Rows[i][1].ToString().Trim();
                entity.JulPlan  = dt.Rows[i][2].ToString().Trim();
                entity.AugPlan  = dt.Rows[i][3].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][4].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][5].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][6].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][7].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][8].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][9].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][10].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][11].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][12].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][13].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][14].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][15].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][16].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][17].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][18].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][19].ToString().Trim();
            }
            else if (MM == "08")
            {
                entity.JulPlan  = dt.Rows[i][1].ToString().Trim();
                entity.AugPlan  = dt.Rows[i][2].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][3].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][4].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][5].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][6].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][7].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][8].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][9].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][10].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][11].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][12].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][13].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][14].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][15].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][16].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][17].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][18].ToString().Trim();
            }
            else if (MM == "09")
            {
                entity.AugPlan  = dt.Rows[i][1].ToString().Trim();
                entity.SepPlan  = dt.Rows[i][2].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][3].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][4].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][5].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][6].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][7].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][8].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][9].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][10].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][11].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][12].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][13].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][14].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][15].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][16].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][17].ToString().Trim();
            }
            else if (MM == "10")
            {
                entity.SepPlan  = dt.Rows[i][1].ToString().Trim();
                entity.OctPlan  = dt.Rows[i][2].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][3].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][4].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][5].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][6].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][7].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][8].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][9].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][10].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][11].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][12].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][13].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][14].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][15].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][16].ToString().Trim();
            }
            else if (MM == "11")
            {
                entity.OctPlan  = dt.Rows[i][1].ToString().Trim();
                entity.NovPlan  = dt.Rows[i][2].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][3].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][4].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][5].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][6].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][7].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][8].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][9].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][10].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][11].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][12].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][13].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][14].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][15].ToString().Trim();
            }
            else if (MM == "12")
            {
                entity.NovPlan  = dt.Rows[i][1].ToString().Trim();
                entity.DecPlan  = dt.Rows[i][2].ToString().Trim();
                entity.kJanPlan = dt.Rows[i][3].ToString().Trim();
                entity.kFebPlan = dt.Rows[i][4].ToString().Trim();
                entity.kMarPlan = dt.Rows[i][5].ToString().Trim();
                entity.kAprPlan = dt.Rows[i][6].ToString().Trim();
                entity.kMayPlan = dt.Rows[i][7].ToString().Trim();
                entity.kJunPlan = dt.Rows[i][8].ToString().Trim();
                entity.kJulPlan = dt.Rows[i][9].ToString().Trim();
                entity.kAugPlan = dt.Rows[i][10].ToString().Trim();
                entity.kSepPlan = dt.Rows[i][11].ToString().Trim();
                entity.kOctPlan = dt.Rows[i][12].ToString().Trim();
                entity.kNovPlan = dt.Rows[i][13].ToString().Trim();
                entity.kDecPlan = dt.Rows[i][14].ToString().Trim();
            }
            entity.Title     = dt.Rows[i][0].ToString().Trim();
            entity.Operators = this.strOp.Value;
            uploadMsg.Text   = "   正在上传,请勿关闭窗口!!!  ";
            int state = BllCash.ImportCash(entity);
            if (state != 1)
            {
                return;
            }
        }

        uploadMsg.Text = "<script language='javascript'>hiddenDiv('divAdd');</script>";
    }
Пример #37
0
        private static void GenerateInformationForCashByPickingDiffClient(
            Cash cash,
            out IEnumerable <ManualJournalLine> counterpartyTransferJournalLines,
            out SortedList <int, DocumentMatching> linkBetweenJournalLineNumberAndDM,
            out MatchFlag matchFlagCpForMatchedDocument,
            out MatchFlag matchFlagCpForCash,
            CostType fxRealCostType)
        {
            linkBetweenJournalLineNumberAndDM = new SortedList <int, DocumentMatching>();
            var counter            = 1;
            var manualJournalLines = new List <ManualJournalLine>();

            matchFlagCpForMatchedDocument = new MatchFlag()
            {
                CompanyId        = cash.CompanyId,
                CounterPartyCode = cash.CounterPartyCode,
                // Apparently, the only way to get the counterparty of the matched documents is in the document matching
                CounterPartyId      = cash.DocumentMatchings.First().MatchingCounterpartyId,
                CurrencyCode        = cash.CurrencyCode,
                IsPrematch          = true,
                PaymentDocumentDate = cash.DocumentDate,
                DocumentMatchings   = new List <DocumentMatching>(),
            };
            matchFlagCpForCash = new MatchFlag()
            {
                CashIdOfCashByPicking = cash.CashId,
                CompanyId             = cash.CompanyId,
                CounterPartyCode      = cash.CounterPartyCode,
                CounterPartyId        = cash.CounterPartyId,
                CurrencyCode          = cash.CurrencyCode,
                IsPrematch            = true,
                PaymentDocumentDate   = cash.DocumentDate,
                DocumentMatchings     = new List <DocumentMatching>()
            };

            foreach (var documentMatching in cash.DocumentMatchings)
            {
                var cashLine = cash.CashLines.ToList().Find(cl =>
                                                            ((cl.InitiallyMatchedInvoiceId.HasValue && documentMatching.SourceInvoiceId.HasValue) && cl.InitiallyMatchedInvoiceId.Value == documentMatching.SourceInvoiceId.Value) ||
                                                            ((cl.InitiallyMatchedCashLineId.HasValue && documentMatching.SourceCashLineId.HasValue) && cl.InitiallyMatchedCashLineId.Value == documentMatching.SourceCashLineId.Value) ||
                                                            ((cl.InitiallyMatchedJournalLineId.HasValue && documentMatching.SourceJournalLineId.HasValue) && cl.InitiallyMatchedJournalLineId.Value == documentMatching.SourceJournalLineId.Value));

                linkBetweenJournalLineNumberAndDM[counter] = documentMatching;

                // dm for the matched object
                matchFlagCpForMatchedDocument.DocumentMatchings.Add(new DocumentMatching()
                {
                    TransactionDocumentId        = documentMatching.TransactionDocumentId,
                    MatchedAmount                = documentMatching.AmountToBePaid,
                    ValueDate                    = documentMatching.InvoiceGLDate ?? documentMatching.DocumentDate,
                    DepartmentId                 = documentMatching.DepartmentId,
                    TransactionDirectionId       = documentMatching.TransactionDirectionId,
                    AmountInFunctionalCurrency   = documentMatching.AmountInFunctionalCurrency,
                    AmountInStatutoryCurrency    = documentMatching.AmountInStatutoryCurrency,
                    SecondaryDocumentReferenceId = cash.TransactionDocumentId,
                    SourceCashLineId             = documentMatching.SourceCashLineId,
                    SourceInvoiceId              = documentMatching.SourceInvoiceId,
                    SourceJournalLineId          = documentMatching.SourceJournalLineId,
                    MatchedCashLineId            = cashLine?.CashLineId,
                    PaymentDocumentDate          = cash.DocumentDate
                });

                int signForAccountingDocuments = 1; // Depends on the matched document
                switch ((MasterDocumentType)documentMatching.TransactionDocumentTypeId)
                {
                case MasterDocumentType.CP:
                case MasterDocumentType.SI:
                case MasterDocumentType.DN:
                case MasterDocumentType.JL:
                    signForAccountingDocuments = -1;
                    break;

                case MasterDocumentType.CI:
                case MasterDocumentType.PI:
                case MasterDocumentType.CN:
                    signForAccountingDocuments = 1;
                    break;
                }

                // dm for the journal - 'removal' from customer 1
                var jlDM = new DocumentMatching()
                {
                    TransactionDocumentId        = null, // Will be set later, to represent one of the JL lines
                    MatchedAmount                = documentMatching.AmountToBePaid * signForAccountingDocuments,
                    ValueDate                    = documentMatching.InvoiceGLDate ?? documentMatching.DocumentDate,
                    DepartmentId                 = documentMatching.DepartmentId,
                    TransactionDirectionId       = documentMatching.TransactionDirectionId,
                    AmountInFunctionalCurrency   = documentMatching.AmountInFunctionalCurrency * signForAccountingDocuments,
                    AmountInStatutoryCurrency    = documentMatching.AmountInStatutoryCurrency * signForAccountingDocuments,
                    SecondaryDocumentReferenceId = cash.TransactionDocumentId,
                    PaymentDocumentDate          = cash.DocumentDate
                };
                matchFlagCpForMatchedDocument.DocumentMatchings.Add(jlDM);
                linkBetweenJournalLineNumberAndDM[counter] = jlDM;

                // Creation of the manual journal which must have the exact same amounts than the document matching
                var matchedCounterpartyJL = new ManualJournalLine()
                {
                    ClientAccountId     = cash.MatchingCounterpartyId,
                    AssociatedAccountId = cash.MatchingCounterpartyId,
                    AccountLineTypeId   = documentMatching.AccountLineTypeId,
                    Amount       = documentMatching.AmountToBePaid * signForAccountingDocuments,
                    Narrative    = documentMatching.Narrative,
                    DepartmentId = cash.DepartmentId,

                    // On Diff Client, SecondaryDocuementReference should be the reference to the cash
                    SecondaryDocumentReference = cash.DocumentReference,

                    ExternalDocumentReference = documentMatching.ExternalReference,
                    CharterId  = null,
                    SectionId  = null,
                    LineNumber = counter++,
                    CostTypeId = fxRealCostType.CostTypeId
                };

                manualJournalLines.Add(matchedCounterpartyJL);

                // dm of the cash
                decimal?signedAmountForCash = documentMatching.AmountToBePaid * CalculateSignForCashDocumentMatching(
                    (DirectionType)cash.CashTypeId, (MasterDocumentType)documentMatching.TransactionDocumentTypeId);
                matchFlagCpForCash.DocumentMatchings.Add(new DocumentMatching()
                {
                    TransactionDocumentId        = cash.TransactionDocumentId,
                    MatchedAmount                = cashLine.Amount.Value, // The cashline contains the signed value
                    ValueDate                    = cash.DocumentDate,
                    DepartmentId                 = documentMatching.DepartmentId,
                    TransactionDirectionId       = documentMatching.TransactionDirectionId,
                    AmountInFunctionalCurrency   = cashLine?.AmountInFunctionalCurrency, // The cashline contains the signed value
                    AmountInStatutoryCurrency    = cashLine?.AmountInStatutoryCurrency,  // The cashline contains the signed value
                    SecondaryDocumentReferenceId = documentMatching.TransactionDocumentId,
                    SourceCashLineId             = cashLine?.CashLineId,
                    MatchedJournalLineId         = documentMatching.SourceJournalLineId,
                    MatchedCashLineId            = documentMatching.SourceCashLineId,
                    MatchedInvoiceId             = documentMatching.SourceInvoiceId,
                    PaymentDocumentDate          = cash.DocumentDate
                });

                // Second dm for the journal
                jlDM = new DocumentMatching()
                {
                    TransactionDocumentId        = null, // Will be set later, to represent one of the JL lines
                    MatchedAmount                = documentMatching.AmountToBePaid * signForAccountingDocuments * -1,
                    ValueDate                    = cash.DocumentDate,
                    DepartmentId                 = documentMatching.DepartmentId,
                    TransactionDirectionId       = documentMatching.TransactionDirectionId,
                    AmountInFunctionalCurrency   = documentMatching.AmountInFunctionalCurrency * signForAccountingDocuments * -1, // The cashline contains the signed value
                    AmountInStatutoryCurrency    = documentMatching.AmountInStatutoryCurrency * signForAccountingDocuments * -1,  // The cashline contains the signed value
                    SecondaryDocumentReferenceId = documentMatching.TransactionDocumentId,
                    PaymentDocumentDate          = cash.DocumentDate
                };
                matchFlagCpForCash.DocumentMatchings.Add(jlDM);
                linkBetweenJournalLineNumberAndDM[counter] = jlDM;

                var cashCounterpartyJL = new ManualJournalLine()
                {
                    ClientAccountId     = cash.PaymentCounterpartyId,
                    AssociatedAccountId = cash.PaymentCounterpartyId,
                    AccountLineTypeId   = documentMatching.AccountLineTypeId,
                    Amount       = documentMatching.AmountToBePaid * signForAccountingDocuments * -1,
                    Narrative    = documentMatching.Narrative,
                    DepartmentId = cash.DepartmentId,

                    // On Diff Client, SecondaryDocuementReference should be the reference to the cash
                    SecondaryDocumentReference = cash.DocumentReference,

                    ExternalDocumentReference = documentMatching.ExternalReference,
                    CharterId  = null,
                    SectionId  = null,
                    LineNumber = counter++,
                    CostTypeId = fxRealCostType.CostTypeId
                };

                manualJournalLines.Add(cashCounterpartyJL);
            }

            counterpartyTransferJournalLines = manualJournalLines;
        }
Пример #38
0
        public void ConstructorCapitalizedSymbol()
        {
            var cash = new Cash("low", 0, 0);

            Assert.AreEqual("LOW", cash.Symbol);
        }
Пример #39
0
        public void CashHasCorrectCurrencySymbol(string symbol, string currencySymbol)
        {
            var cash = new Cash(symbol, 1, 1);

            Assert.AreEqual(currencySymbol, cash.CurrencySymbol);
        }
Пример #40
0
    protected void AddPayment_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        VOPaymethodGrid vo = new VOPaymethodGrid();

        if (Helper.VoPaymentLines.Count == 0)
        {
            vo.LineNo = 1;
        }
        else
        {
            vo.LineNo = Helper.VoPaymentLines[Helper.VoPaymentLines.Count - 1].LineNo + 1;
        }
        double  amount = Convert.ToDouble((decimal)txtAmount.Value);
        decimal amountForThisTransaction = (decimal)txtAmountForThisTransaction.Value;
        //vo.AmountForThisTransaction = amountForThisTransaction;
        String  payMethod = (String)ComboPayMethod.SelectedItem.Value;
        String  payType   = (String)cboPayType.SelectedItem.Value;
        Party   payee     = iSabayaContext.imSabayaConfig.SystemOwnerOrg;
        Payment payment   = null;

        if (payMethod.Equals("BankAccountDeposit"))
        {
            BankDeposit bankDeposit = new BankDeposit();

            if (payType.Equals("Cash"))
            {
                payment       = new Cash();
                payment.Payee = payee;

                Cash cash = (Cash)payment;
                bankDeposit.Amount = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);

                //bankDeposit.PaymentDate = DateTime.Now.Date;
                bankDeposit.PaymentDate = paymentDate.Date;

                //bankDeposit.DueDate = bankDeposit.Date = dueDate.Date;//Dr.supoj
                //vo.BankDeposit.DestinationBankAccount = DestinationBankAccountTextBoxControl.BankAccount;
                bankDeposit.AmountForThisTransaction = amountForThisTransaction;
            }
            else if (payType.Equals("Cheque"))
            {
                payment       = new Cheque();
                payment.Payee = payee;
                Cheque cheque = (Cheque)payment;
                cheque.Amount = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);
                //cheque.PaymentDate = paymentDate.Date.Date;
                //cheque.DueDate = dueDate.Date;
                cheque.StatusDate = DateTime.Now;//fern
                //cheque.PrintChequeDate = TimeInterval.MaxDate;//fern
                cheque.AmountForThisTransaction = amountForThisTransaction;

                //cheque.Bank = ChequeControl1.Bank;
                //cheque.ChequeNo = ChequeControl1.GetChequeNumber();
                //cheque.ChequeDate = ChequeControl1.GetChequeDate();

                cheque.Bank       = BankControl1.Organization;
                cheque.ChequeNo   = tbChequeNo.Text;
                cheque.ChequeDate = (DateTime)ChequeDate.Date;

                //cheque.PaymentDate = DateTime.Now.Date;
                cheque.PaymentDate = paymentDate.Date;
                //cheque.PaymentDate = paymentDate.Date;
                //cheque.DestinationBankAccount = DestinationBankAccountTextBoxControl.BankAccount;
                cheque.PrintChequeDate = TimeInterval.MaxDate;


                //special for bank deposit
                bankDeposit.Amount = cheque.Amount;
                //bankDeposit.PaymentDate = cheque.PaymentDate;
                bankDeposit.PaymentDate = paymentDate.Date;
                bankDeposit.DueDate     = cheque.DueDate.Date;
                //vo.BankDeposit.DestinationBankAccount = cheque.DestinationBankAccount;
                bankDeposit.AmountForThisTransaction = amountForThisTransaction;
                //special for bank deposit
                bankDeposit.Cheque = cheque;
                //bankDeposit.TransactionNo = txtTransactionNo.Text;
            }

            vo.BankDeposit = bankDeposit;
        }
        else if (payMethod.Equals("Cash"))
        {
            payment       = new Cash();
            payment.Payee = payee;

            Cash cash = (Cash)payment;
            cash.Amount      = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);
            cash.PaymentDate = DateTime.Now.Date;

            //cash.DueDate = dueDate.Date;

            //cash.DestinationBankAccount = DestinationBankAccountTextBoxControl.BankAccount;
            cash.AmountForThisTransaction = amountForThisTransaction;
            vo.Cash = cash;
        }
        else if (payMethod.Equals("Cheque"))
        {
            payment       = new Cheque();
            payment.Payee = payee;
            Cheque cheque = (Cheque)payment;
            cheque.Amount = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);

            cheque.PaymentDate = DateTime.Now.Date;
            //cheque.PaymentDate = paymentDate.Date.Date;
            //cheque.DueDate = dueDate.Date;
            cheque.StatusDate               = DateTime.Now;         //fern
            cheque.PrintChequeDate          = TimeInterval.MinDate; //fern
            cheque.AmountForThisTransaction = amountForThisTransaction;


            //cheque.Bank = ChequeControl1.Bank;
            //cheque.ChequeNo = ChequeControl1.GetChequeNumber();
            //cheque.ChequeDate = ChequeControl1.GetChequeDate();
            cheque.Bank       = BankControl1.Organization;
            cheque.ChequeNo   = tbChequeNo.Text;
            cheque.ChequeDate = (DateTime)ChequeDate.Date;

            cheque.PayableTo = "";
            //cheque.DestinationBankAccount = DestinationBankAccountTextBoxControl.BankAccount;
            cheque.PrintChequeDate = TimeInterval.MaxDate;
            vo.Cheque = cheque;
        }
        else if (payMethod.Equals("BillPayment"))
        {
            //no class
            BillPayment billPayment = new BillPayment();
            if (payType.Equals("Cash"))
            {
                payment       = new Cash();
                payment.Payee = payee;

                Cash cash = (Cash)payment;
                billPayment.Amount      = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);
                billPayment.PaymentDate = paymentDate.Date.Date;
                //bankDeposit.DueDate = bankDeposit.Date = dueDate.Date;//Dr.supoj
                //vo.BankDeposit.DestinationBankAccount = DestinationBankAccountTextBoxControl.BankAccount;
                billPayment.AmountForThisTransaction = amountForThisTransaction;
            }
            else if (payType.Equals("Cheque"))
            {
                payment       = new Cheque();
                payment.Payee = payee;

                Cheque cheque = (Cheque)payment;
                cheque.Amount      = new Money(Convert.ToDecimal(amount.ToString()), iSabayaContext.imSabayaConfig.DefaultCurrency);
                cheque.PaymentDate = paymentDate.Date.Date;
                //cheque.DueDate = dueDate.Date;
                cheque.StatusDate = paymentDate.Date.Date;//fern
                cheque.AmountForThisTransaction = amountForThisTransaction;

                cheque.Bank       = BankControl1.Organization;
                cheque.ChequeNo   = tbChequeNo.Text;
                cheque.ChequeDate = (DateTime)ChequeDate.Date;

                cheque.PayableTo       = "";
                cheque.PrintChequeDate = TimeInterval.MaxDate;
                //special for bank deposit
                billPayment.Amount      = cheque.Amount;
                billPayment.PaymentDate = cheque.PaymentDate;
                billPayment.DueDate     = cheque.DueDate.Date;
                billPayment.AmountForThisTransaction = amountForThisTransaction;
                //special for bank deposit
                billPayment.Cheque = cheque;
            }
            vo.BillPayment = billPayment;
        }
        Helper.VoPaymentLines.Add(vo);
    }
Пример #41
0
 public void ConstructorThrowsOnSymbolTooLong()
 {
     var cash = new Cash("too long", 0, 0);
 }
Пример #42
0
 /// <summary>
 /// Cash in and Cash out operations
 /// </summary>
 /// <param name="operationType">Type of operation</param>
 /// <param name="amount">The sum</param>
 /// <returns>CashInCashOutResponse</returns>
 public CashInCashOutResponse CashInCashOutOperation(Cash operationType, decimal amount)
 {
     return((CashInCashOutResponse)ExecuteCommand(new CashInCashOutCommand((int)operationType, amount)
                                                  , bytes => new CashInCashOutResponse(bytes)));
 }
Пример #43
0
 public void SetLastCash(Cash cash)
 {
     lastCash = cash;
     lastCashArriveTime = DateTime.Now;
 }
Пример #44
0
        public Cash value()
        {
            Period principalPeriod = amortising_ == Loan.Amortising.Bullet ?
                                  new Period(Frequency.Once) :
                                  new Period(frequency_);

             Schedule principalSchedule = new Schedule(startDate_, endDate_, principalPeriod,
                                  calendar_, convention_, convention_, rule_, endOfMonth_);

             Cash c = new Cash(type_, nominal_, principalSchedule, convention_);
             return c;
        }
Пример #45
0
	void Awake() {
		instance = this;
	}
Пример #46
0
 public string BalanceCash()
 {
     return(Cash.ToString());
 }
Пример #47
0
        public async Task <SaleDto> PreCreation(Guid userId, SaleForCreationDto saletForCreationDto)
        {
            try
            {
                Client client = null;
                if (saletForCreationDto.ClientId.HasValue)
                {
                    client = await _clientRepository.GetById(saletForCreationDto.ClientId.Value);

                    if (client == null)
                    {
                        throw new KeyNotFoundException($"Client with id: {saletForCreationDto.ClientId} not found.");
                    }
                }

                var sale = new Sale()
                {
                    ClientId    = saletForCreationDto.ClientId,
                    Client      = client,
                    ClientName  = client != null ? client.Name + " " + client.Lastname : saletForCreationDto.ClientName,
                    Date        = saletForCreationDto.Date.ToLocalTime(),
                    PaymentType = saletForCreationDto.PaymentType,
                    CreatedBy   = userId
                };

                decimal total = 0;
                foreach (var detailFC in saletForCreationDto.Details)
                {
                    var product = await _productRepository.GetById(detailFC.ProductId);

                    if (product == null)
                    {
                        throw new KeyNotFoundException($"Product with id: {detailFC.ProductId} not found.");
                    }

                    var price = (await _priceRepository.GetAll())
                                .OrderByDescending(x => x.DateTime)
                                .FirstOrDefault(
                        x => x.ProductId == detailFC.ProductId &&
                        x.DateTime.ToLocalTime() <= saletForCreationDto.Date.ToLocalTime() &&
                        x.PriceType == ePriceTypes.SalePrice &&
                        !x.IsDeleted
                        );

                    FeeRule feeRule = null;
                    if (sale.PaymentType == ePaymentTypes.OwnFees)
                    {
                        feeRule = (await _feeRuleRepository.Find(x => x.ProductId == detailFC.ProductId))
                                  .OrderByDescending(x => x.Date).ThenBy(x => x.FeesAmountTo)
                                  .FirstOrDefault(x => x.Date <= sale.Date && x.FeesAmountTo >= saletForCreationDto.OwnFees.Quantity);
                        if (feeRule == null)
                        {
                            throw new KeyNotFoundException($"Fee Rule not found.");
                        }

                        decimal percentage = feeRule.Percentage * saletForCreationDto.OwnFees.Quantity / 100;
                        total += price.Value * detailFC.Quantity * (1 + percentage);
                    }
                    else
                    {
                        total += price.Value * detailFC.Quantity;
                    }

                    var detail = new Detail()
                    {
                        SaleId    = sale.Id,
                        ProductId = detailFC.ProductId,
                        Product   = product,
                        Quantity  = detailFC.Quantity,
                        UnitPrice = price.Value,
                        FeeRuleId = feeRule?.Id,
                        CreatedBy = userId
                    };

                    sale.Details.Add(detail);
                }

                Payment payment = null;
                switch (saletForCreationDto.PaymentType)
                {
                case Util.Enums.ePaymentTypes.Cash:
                    var cashDto = (CashForCreationDto)saletForCreationDto.Cash;
                    payment = new Cash(total, cashDto.Discount)
                    {
                        SaleId    = sale.Id,
                        CreatedBy = userId
                    };
                    break;

                case Util.Enums.ePaymentTypes.OwnFees:
                    var ownFeesDto = (OwnFeesForCreationDto)saletForCreationDto.OwnFees;
                    payment = new OwnFees(ownFeesDto.ExpirationDate, total, ownFeesDto.Quantity, userId)
                    {
                        SaleId = sale.Id,
                    };
                    break;

                case Util.Enums.ePaymentTypes.CreditCard:
                    var creditCardDto = (CreditCardForCreationDto)saletForCreationDto.CreditCard;
                    payment = new CreditCard(total, creditCardDto.Discount, creditCardDto.Surcharge)
                    {
                        SaleId    = sale.Id,
                        CardType  = creditCardDto.CardType,
                        Bank      = creditCardDto.Bank,
                        CreatedBy = userId
                    };
                    break;

                case Util.Enums.ePaymentTypes.DebitCard:
                    var debitCardDto = (DebitCardForCreationDto)saletForCreationDto.DebitCard;
                    payment = new DebitCard(total, debitCardDto.Discount, debitCardDto.Surcharge)
                    {
                        SaleId    = sale.Id,
                        CardType  = debitCardDto.CardType,
                        Bank      = debitCardDto.Bank,
                        CreatedBy = userId
                    };
                    break;

                case Util.Enums.ePaymentTypes.Cheques:
                    var chequesDto = (ChequesPaymentForCreationDto)saletForCreationDto.Cheques;

                    if (chequesDto.ListOfCheques.Sum(x => x.Value) != total)
                    {
                        throw new InvalidOperationException("The sum of cheques list is different of amount.");
                    }

                    payment = new ChequesPayment()
                    {
                        SaleId    = sale.Id,
                        Amount    = Math.Ceiling(total * 100) / 100,
                        CreatedBy = userId
                    };

                    foreach (var c in chequesDto.ListOfCheques)
                    {
                        var cheque = new Cheque()
                        {
                            ChequesPaymentId = payment.Id,
                            Bank             = c.Bank,
                            Nro       = c.Nro,
                            Value     = c.Value,
                            CreatedBy = userId
                        };

                        ((ChequesPayment)payment).ListOfCheques.Add(cheque);
                    }
                    break;

                default:
                    break;
                }

                sale.PaymentId = payment.Id;
                sale.Payment   = payment;

                var saleDto = _mapper.Map <Sale, SaleDto>(sale);

                switch (saleDto.PaymentType)
                {
                case Util.Enums.ePaymentTypes.Cash:
                    saleDto.Cash = _mapper.Map <Cash, CashDto>((Cash)payment);
                    break;

                case Util.Enums.ePaymentTypes.OwnFees:
                    OwnFees owF = (OwnFees)payment;
                    saleDto.OwnFees = _mapper.Map <OwnFees, OwnFeesDto>(owF);
                    break;

                case Util.Enums.ePaymentTypes.CreditCard:
                    saleDto.CreditCard = _mapper.Map <CreditCard, CreditCardDto>((CreditCard)payment);
                    break;

                case Util.Enums.ePaymentTypes.DebitCard:
                    saleDto.DebitCard = _mapper.Map <DebitCard, DebitCardDto>((DebitCard)payment);
                    break;

                case Util.Enums.ePaymentTypes.Cheques:
                    saleDto.Cheques = _mapper.Map <ChequesPayment, ChequesPaymentDto>((ChequesPayment)payment);
                    break;

                default:
                    break;
                }

                return(saleDto);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #48
0
        public void NonUsdAccountCurrencyCurrencyDataFeedsGetAdded(string accountCurrency,
                                                                   string quoteCurrency,
                                                                   string baseCurrency,
                                                                   string quoteCurrencySymbol,
                                                                   string baseCurrencySymbol,
                                                                   SecurityType securityType,
                                                                   string market)
        {
            var quoteCash = new Cash(quoteCurrency, 100, 1);
            var baseCash  = new Cash(baseCurrency, 100, 1);
            var cashBook  = new CashBook {
                { quoteCurrency, quoteCash },
                { baseCurrency, baseCash }
            };

            var symbol = Symbol.Create(baseCurrency + quoteCurrency,
                                       securityType,
                                       market);
            var subscriptions = new SubscriptionManager();
            var dataManager   = new DataManagerStub(TimeKeeper);

            subscriptions.SetDataManager(dataManager);
            var securities = new SecurityManager(TimeKeeper)
            {
                {
                    symbol, new Security(
                        SecurityExchangeHours,
                        subscriptions.Add(symbol, Resolution.Minute, TimeZone, TimeZone),
                        new Cash(cashBook.AccountCurrency, 0, 1m),
                        SymbolProperties.GetDefault(cashBook.AccountCurrency),
                        ErrorCurrencyConverter.Instance,
                        RegisteredSecurityDataTypesProvider.Null,
                        new SecurityCache()
                        )
                }
            };

            var configs1 = quoteCash.EnsureCurrencyDataFeed(securities,
                                                            subscriptions,
                                                            MarketMap,
                                                            SecurityChanges.None,
                                                            dataManager.SecurityService,
                                                            accountCurrency);

            Assert.AreEqual(1, configs1.Count);

            var config1 = configs1[0];

            Assert.IsNotNull(config1);
            Assert.AreEqual(quoteCurrencySymbol, config1.Symbol.Value);

            var configs2 = baseCash.EnsureCurrencyDataFeed(securities,
                                                           subscriptions,
                                                           MarketMap,
                                                           SecurityChanges.None,
                                                           dataManager.SecurityService,
                                                           accountCurrency);

            Assert.AreEqual(1, configs2.Count);

            var config2 = configs2[0];

            Assert.IsNotNull(config2);
            Assert.AreEqual(baseCurrencySymbol, config2.Symbol.Value);
        }
Пример #49
0
 /// <summary>
 /// Constructor for the Future security
 /// </summary>
 /// <param name="exchangeHours">Defines the hours this exchange is open</param>
 /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
 /// <param name="config">The subscription configuration for this security</param>
 /// <param name="symbolProperties">The symbol properties for this security</param>
 public Future(SecurityExchangeHours exchangeHours, SubscriptionDataConfig config, Cash quoteCurrency, SymbolProperties symbolProperties)
     : base(config,
            quoteCurrency,
            symbolProperties,
            new FutureExchange(exchangeHours),
            new FutureCache(),
            new SecurityPortfolioModel(),
            new ImmediateFillModel(),
            new InteractiveBrokersFeeModel(),
            new ConstantSlippageModel(0),
            new ImmediateSettlementModel(),
            Securities.VolatilityModel.Null,
            new FutureMarginModel(),
            new SecurityDataFilter(),
            new SecurityPriceVariationModel()
            )
 {
     // for now all futures are cash settled as we don't allow underlying (Live Cattle?) to be posted on the account
     SettlementType    = SettlementType.Cash;
     Holdings          = new FutureHolding(this);
     _symbolProperties = symbolProperties;
     SetFilter(TimeSpan.Zero, TimeSpan.FromDays(35));
 }
Пример #50
0
            public Printer()
            {
                _CashInfo = new Cash();


                callback = new CallbackDef(Result);

                Init();

                GetStatus();


            }
Пример #51
-1
        /// <summary>
        /// Constructor for the forex security
        /// </summary>
        /// <param name="quoteCurrency">The cash object that represent the quote currency</param>
        /// <param name="config">The subscription configuration for this security</param>
        /// <param name="leverage">The leverage used for this security</param>
        public Forex(Cash quoteCurrency, SubscriptionDataConfig config, decimal leverage)
            : this(SecurityExchangeHoursProvider.FromDataFolder().GetExchangeHours(config), quoteCurrency, config, leverage)
        {
            // this constructor is provided for backward compatibility

            // should we even keep this?
        }