Esempio n. 1
0
 public SlaveAccountModel(TraderModel masterModel, TradingAccount tradingAccountModel)
     : this()
 {
     //Dimok: Use WeakReference
     this.MasterModel         = masterModel;
     this.TradingAccountModel = tradingAccountModel;
 }
Esempio n. 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Token"] == null)
            {
                if (HttpContext.Current.Request.QueryString["code"] != null)
                {
                    var code        = HttpContext.Current.Request.QueryString["code"];
                    var redirectUri = Session["Url"].ToString();
                    var token       = AccessToken.GetAccessToken(_connectUrl, code, redirectUri, _clientId, _clientSecret);
                    var tokenString = token.Token;
                    if (tokenString != null)
                    {
                        tcMainContainer.Enabled = true;
                        var profile  = Profile.GetProfile(_apiUrl, tokenString);
                        var accounts = TradingAccount.GetTradingAccounts(_apiUrl, tokenString);
                        ddlTradingAccounts.DataSource = accounts;
                        ddlTradingAccounts.DataBind();
                        Session["Token"]        = tokenString;
                        Session["RefreshToken"] = token.RefreshToken;
                    }
                }
                else
                {
                    Session["Url"] = HttpContext.Current.Request.Url.AbsoluteUri;
                    Response.Redirect(_connectUrl + "apps/auth?&client_id=" + _clientId + "&redirect_uri=" + HttpContext.Current.Request.Url.AbsoluteUri + "&scope=trading");
                }
            }

            _tcpClient = new TcpClient(_apiHost, _apiPort);;
            _apiSocket = new SslStream(_tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            _apiSocket.AuthenticateAsClient(_apiHost);
        }
Esempio n. 3
0
        // 成交通知
        public override bool OnTrade(TradeInfo trade)
        {
            QryTradingAccount qryTA = new QryTradingAccount();
            TradingAccount    taRet = new TradingAccount();

            GetTradingAccount(qryTA, ref taRet);

            QryPosition         qryPiso = new QryPosition();
            List <PositionInfo> lstPosi = new List <PositionInfo>();

            GetPositions(qryPiso, ref lstPosi);

            InputOrder req = new InputOrder();

            req.InstrumentID = trade.InstrumentID;
            req.Qty          = trade.Volume;
            req.Price        = trade.Price + (trade.Direction == '0' ? -1.0 : 1.0);
            req.Hedge        = '1';
            req.IsMarket     = false;
            req.Direction    = trade.Direction == '0' ? '1' : '0';
            req.OpenClose    = '1';

            ReqOrderInsert(req);

            return(true);
        }
        public void Reconcile(int tradingAccountId = 0, DateTime?snapshotDate = null)
        {
            using (var unitOfWork = this.UnitOfWorkManager.Begin())
            {
                this._sqlExecuter.Execute("DELETE FROM [PerformanceCycles] WHERE TradingAccountId = {0}", this._repository.GetAllIncluding(x => x.Trades).First(x => tradingAccountId == 0 ? x.Active : x.Id == tradingAccountId).Id);
                unitOfWork.Complete();
            }

            using (var unitOfWork = this.UnitOfWorkManager.Begin())
            {
                TradingAccount tradingAccount = this._repository.GetAllIncluding(x => x.Trades).First(x => tradingAccountId == 0 ? x.Active : x.Id == tradingAccountId);
                List <Trade>   closedTrades   = this._tradeRepository.GetAll().Where(x => x.TradingAccountId == tradingAccount.Id).ToList();

                #region Old Guard
                tradingAccount.ProfitLoss     = closedTrades.Sum(x => x.ProfitLoss);
                tradingAccount.Commissions    = closedTrades.Sum(x => x.Commissions);
                tradingAccount.CurrentCapital = tradingAccount.InitialCapital + tradingAccount.ProfitLoss - tradingAccount.Commissions;
                tradingAccount.AdjProfitLoss  = tradingAccount.ProfitLoss - tradingAccount.Commissions;

                tradingAccount.TotalReturn = (tradingAccount.CurrentCapital - tradingAccount.InitialCapital) / tradingAccount.InitialCapital;
                tradingAccount.CAGR        = (Decimal)(Math.Pow((Double)(tradingAccount.CurrentCapital) / (Double)tradingAccount.InitialCapital, (1.0 / ((Double)(DateTime.Now - tradingAccount.InceptionDate).Days / 365.0))) - 1.0);
                #endregion

                #region PerformanceCycles
                tradingAccount.PerformanceCycles.AddRange(PerformanceCycle.BuildLists(tradingAccount));
                #endregion

                unitOfWork.Complete();
            }
        }
        public QuickFix.FIX44.Message CreateFillReport(OrderMatchReport report)
        {
            var execId          = string.Format("{0}{1}", report.Asset.Symbol, DIContainer.ResolveByName <IdGenerator>("ExecIdGenerator").GenerateId());
            var symbol          = new Symbol(report.Asset.Symbol);
            var executionReport = new ExecutionReport(
                new OrderID(report.OrderId.ToString(CultureInfo.InvariantCulture)),
                new ExecID(execId),
                new ExecType(report.MatchType == OrderMatchType.Filled
                                 ? ExecType.FILL
                                 : ExecType.PARTIAL_FILL),
                new OrdStatus(report.MatchType == OrderMatchType.Filled
                                  ? OrdStatus.FILLED
                                  : OrdStatus.PARTIALLY_FILLED),
                symbol,
                FixFieldsConverter.Convert(report.OrderSide),
                new LeavesQty(report.RemainingQuantity),
                new CumQty(report.OriginalOrderQuantity - report.RemainingQuantity),
                new AvgPx(report.Price))
            {
                ClOrdID  = new ClOrdID(report.ClOrdId),
                Symbol   = symbol,
                OrderQty = new OrderQty(report.OriginalOrderQuantity),
                LastQty  = new LastQty(report.MatchedQuantity),
                LastPx   = new LastPx(report.Price)
            };

            if (TradingAccount.IsSet(report.Account))
            {
                executionReport.SetField(new Account(report.Account.Name));
            }

            return(executionReport);
        }
Esempio n. 6
0
        /// <summary>
        ///     Adds an order for the given contract and market side with the given properties
        /// </summary>
        /// <returns>The added order</returns>
        public IOrder AddOrder(long orderID,
                               Contract contract,
                               OrderType orderType,
                               MarketSide marketSide,
                               decimal price,
                               decimal quantity,
                               string clOrdID,
                               TradingAccount account)
        {
            var order = new Order(orderID,
                                  orderType,
                                  contract,
                                  marketSide,
                                  price,
                                  quantity,
                                  clOrdID,
                                  account);

            var stack = _market.GetOrCreate(
                contract,
                () =>
            {
                var os            = OrderStackFactory.CreateStandardSortedStack(_orderMatcher);
                os.OrdersMatched += OnOrdersMatched;
                return(os);
            });

            stack.AddOrder(order);
            return(order);
        }
Esempio n. 7
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,Balance,Name,UnitSize,ExpectedPriceChange,RiskFreeInterestRate")] TradingAccount tradingAccount)
        {
            if (id != tradingAccount.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(tradingAccount);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TradingAccountExists(tradingAccount.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index"));
            }
            return(View(tradingAccount));
        }
Esempio n. 8
0
        private void GetStockPosition()
        {
            if (this.xiadan == null)
            {
                return;
            }

            lvStockPosition.Items.Clear();
            TradingAccount account = (TradingAccount)this.xiadan.GetCashInfo().Result;

            if (account == null)
            {
                return;
            }
            foreach (StockHolderInfo shi in account.StockHolders)
            {
                ListViewItem lvi = new ListViewItem(new string[] { shi.StockCode,
                                                                   shi.StockName,
                                                                   shi.CurrentAmount.ToString(),
                                                                   "0",
                                                                   shi.EnableAmount.ToString(),
                                                                   shi.CostPrice.ToString(),
                                                                   shi.KeepCostPrice.ToString(),
                                                                   shi.LastPrice.ToString(),
                                                                   "0",
                                                                   shi.IncomeAmount.ToString(),
                                                                   shi.MarketValue.ToString(),
                                                                   shi.ExchangeName,
                                                                   shi.StockAccount });
                lvStockPosition.Items.Add(lvi);
            }
        }
Esempio n. 9
0
        public Message CreateNewOrderExecutionReport(IOrder o, string execID)
        {
            var exReport = new ExecutionReport(
                new OrderID(o.ID.ToString(CultureInfo.InvariantCulture)),
                new ExecID(execID),
                new ExecTransType(ExecType.NEW),
                new ExecType(ExecType.NEW),
                new OrdStatus(OrdStatus.NEW),
                new Symbol(o.Contract.Symbol),
                TranslateFixFields.Translate(o.MarketSide),
                new LeavesQty(o.Quantity),
                new CumQty(0m),
                new AvgPx(o.Price))
            {
                ClOrdID    = new ClOrdID(o.ClOrdID),
                OrderQty   = new OrderQty(o.Quantity),
                LastShares = new LastShares(0m)
            };

            //exReport.Set(new LastPx(o.Price));

            if (TradingAccount.IsSet(o.Account))
            {
                exReport.SetField(new Account(o.Account.Name));
            }

            return(exReport);
        }
Esempio n. 10
0
        // From fixprotocol.org:
        // CumQty: Currently executed shares for chain of orders.
        // LeavesQty: Amount of shares open for further execution. If the OrdStatus is Canceled,
        //            DoneForTheDay, Expired, Calculated, or Rejected (in which case the order
        //            is no longer active) then LeavesQty could be 0,
        //            otherwise LeavesQty = OrderQty - CumQty.
        // LastShares: Quantity of shares bought/sold on this (last) fill.
        //
        // Also see http://www.onixs.biz/fix-dictionary/4.2/msgType_8_8.html
        // The general rule is: OrderQty <38> = CumQty <14> + LeavesQty <151>.

        public Message CreateFillReport(OrderMatch match, string execID)
        {
            var exReport = new ExecutionReport(
                new OrderID(match.OrderID.ToString(CultureInfo.InvariantCulture)),
                new ExecID(execID),
                new ExecTransType(ExecTransType.NEW),
                new ExecType(match.MatchType == MatchType.Full
                                 ? ExecType.FILL
                                 : ExecType.PARTIAL_FILL),
                new OrdStatus(match.MatchType == MatchType.Full
                                  ? OrdStatus.FILLED
                                  : OrdStatus.PARTIALLY_FILLED),
                new Symbol(match.Contract.Symbol),
                TranslateFixFields.Translate(match.MarketSide),
                new LeavesQty(match.RemainingQuantity),
                new CumQty(match.OriginalOrderQuantity - match.RemainingQuantity),
                new AvgPx(match.Price))
            {
                ClOrdID    = new ClOrdID(match.ClOrdID),
                OrderQty   = new OrderQty(match.OriginalOrderQuantity),
                LastShares = new LastShares(match.MatchedQuantity),
                LastPx     = new LastPx(match.Price)
            };

            if (TradingAccount.IsSet(match.Account))
            {
                exReport.SetField(new Account(match.Account.Name));
            }

            return(exReport);
        }
Esempio n. 11
0
        public Message CreateNewOrderSingleMessage(string symbol,
                                                   MarketSide marketSide,
                                                   string clOrdID,
                                                   TradingAccount account,
                                                   decimal price,
                                                   decimal quantity,
                                                   OrderType orderType,
                                                   string execID)
        {
            var fOrdType      = TranslateFixFields.Translate(orderType);
            var fSide         = TranslateFixFields.Translate(marketSide);
            var fSymbol       = new Symbol(symbol);
            var fTransactTime = new TransactTime(DateTime.Now);
            var fClOrdID      = new ClOrdID(clOrdID);

            var nos = new NewOrderSingle(fClOrdID,
                                         fSymbol,
                                         fSide,
                                         fTransactTime,
                                         fOrdType)
            {
                OrderQty    = new OrderQty(quantity),
                TimeInForce = new TimeInForce(TimeInForce.GOOD_TILL_CANCEL)
            };

            if (orderType == OrderType.Limit)
            {
                nos.Price = new Price(price);
            }

            return(nos);
        }
Esempio n. 12
0
        public async Task <IActionResult> UpdateOptions([Bind("Expiry,UnderlyingPrice")] UpdateOptionsModel updateOptionsModel)
        {
            if (ModelState.IsValid)
            {
                TradingAccount tradingAccount = _context.TradingAccounts.First();
                Decimal        spread;

                foreach (Option option in await _context.Options.ToListAsync())
                {
                    option.Expiry            = updateOptionsModel.Expiry;
                    option.UnderlyingPrice   = updateOptionsModel.UnderlyingPrice;
                    option.BlackScholesPrice = option.CalculateBlackScholesPrice(tradingAccount, updateOptionsModel.UnderlyingPrice);

                    spread     = option.Spread;
                    option.Bid = option.BlackScholesPrice - (spread / 2m);
                    option.Ask = option.BlackScholesPrice + (spread / 2m);
                    option.FillCalculatedFields(tradingAccount);
                }

                _context.SaveChanges();

                return(RedirectToAction("Index", "Home"));
            }
            return(View(updateOptionsModel));
        }
Esempio n. 13
0
        public void Reconcile()
        {
            TradingAccount tradingAccount = this._repository.GetAllIncluding(x => x.Trades).First(x => x.Active);
            List <Trade>   closedTrades   = this._tradeRepository.GetAll().Where(x => x.TradingAccountId == tradingAccount.Id && x.ExitReason != TradeExitReasons.None).ToList();

            tradingAccount.ProfitLoss     = closedTrades.Sum(x => x.ProfitLoss);
            tradingAccount.CurrentCapital = tradingAccount.InitialCapital + tradingAccount.ProfitLoss;
            tradingAccount.Commissions    = closedTrades.Sum(x => x.Commissions);
        }
Esempio n. 14
0
        // 请求查询交易员资金帐号
        public bool GetTradingAccount(QryTradingAccount qry, ref TradingAccount refTradingAccount)
        {
            DebugOut("Call CStrategy Function GetTradingAccount from MainForm Successfully");

            if (this.orderServer == null)
            {
                return(false);
            }
            return(this.orderServer.GetTradingAccount(qry, ref refTradingAccount));
        }
Esempio n. 15
0
        public async Task <IActionResult> Upload([Bind("Contents")] CsvUpload csvUpload)
        {
            if (ModelState.IsValid)
            {
                _context.Options.Clear();

                TradingAccount tradingAccount = _context.TradingAccounts.FirstOrDefault();

                String[] split           = csvUpload.Contents.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                Decimal  underlyingPrice = Decimal.Parse(split[0]);

                using (TextReader tr = new StringReader(String.Join(Environment.NewLine, split.Skip(1)).Replace(",,", String.Empty).Replace("%", String.Empty)))
                {
                    var csv = new CsvReader(tr, new CsvConfiguration()
                    {
                        HasHeaderRecord = true
                    });
                    while (csv.Read())
                    {
                        Option callOption = new Option();
                        callOption.OptionType        = OptionTypes.Call;
                        callOption.Delta             = csv.GetField <Decimal>(0);
                        callOption.ImpliedVolatility = csv.GetField <Decimal>(1) / 100m;
                        callOption.Bid             = csv.GetField <Decimal>(2);
                        callOption.Ask             = csv.GetField <Decimal>(5);
                        callOption.Expiry          = csv.GetField <DateTime>(7);
                        callOption.Strike          = csv.GetField <Decimal>(8);
                        callOption.UnderlyingPrice = underlyingPrice;

                        callOption.FillCalculatedFields(tradingAccount);

                        _context.Options.Add(callOption);

                        Option putOption = new Option();
                        putOption.OptionType        = OptionTypes.Put;
                        putOption.Delta             = Math.Abs(csv.GetField <Decimal>(13));
                        putOption.ImpliedVolatility = csv.GetField <Decimal>(14) / 100m;
                        putOption.Bid             = csv.GetField <Decimal>(9);
                        putOption.Ask             = csv.GetField <Decimal>(11);
                        putOption.Expiry          = csv.GetField <DateTime>(7);
                        putOption.Strike          = csv.GetField <Decimal>(8);
                        putOption.UnderlyingPrice = underlyingPrice;

                        putOption.FillCalculatedFields(tradingAccount);

                        _context.Options.Add(putOption);
                    }

                    await _context.SaveChangesAsync();
                }

                return(RedirectToAction("Index", "Home"));
            }
            return(View(csvUpload));
        }
Esempio n. 16
0
        public async Task <IActionResult> Create([Bind("ID,Balance,Name,UnitSize,ExpectedPriceChange,RiskFreeInterestRate")] TradingAccount tradingAccount)
        {
            if (ModelState.IsValid)
            {
                _context.Add(tradingAccount);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(tradingAccount));
        }
Esempio n. 17
0
 private static List <Property> GenerateInfo(TradingAccount tradingAccount)
 {
     return(new List <Property>()
     {
         new Property("BrokerID", tradingAccount.BrokerID),
         new Property("AccountID", tradingAccount.AccountID),
         new Property("PreMortgage", tradingAccount.PreMortgage),
         new Property("PreCredit", tradingAccount.PreCredit),
         new Property("PreDeposit", tradingAccount.PreDeposit),
         new Property("PreBalance", tradingAccount.PreBalance),
         new Property("PreMargin", tradingAccount.PreMargin),
         new Property("InterestBase", tradingAccount.InterestBase),
         new Property("Interest", tradingAccount.Interest),
         new Property("Deposit", tradingAccount.Deposit),
         new Property("Withdraw", tradingAccount.Withdraw),
         new Property("FrozenMargin", tradingAccount.FrozenMargin),
         new Property("FrozenCash", tradingAccount.FrozenCash),
         new Property("FrozenCommission", tradingAccount.FrozenCommission),
         new Property("CurrMargin", tradingAccount.CurrMargin),
         new Property("CashIn", tradingAccount.CashIn),
         new Property("Commission", tradingAccount.Commission),
         new Property("CloseProfit", tradingAccount.CloseProfit),
         new Property("PositionProfit", tradingAccount.PositionProfit),
         new Property("Balance", tradingAccount.Balance),
         new Property("Available", tradingAccount.Available),
         new Property("WithdrawQuota", tradingAccount.WithdrawQuota),
         new Property("Reserve", tradingAccount.Reserve),
         new Property("TradingDay", tradingAccount.TradingDay),
         new Property("SettlementID", tradingAccount.SettlementID),
         new Property("Credit", tradingAccount.Credit),
         new Property("Mortgage", tradingAccount.Mortgage),
         new Property("ExchangeMargin", tradingAccount.ExchangeMargin),
         new Property("DeliveryMargin", tradingAccount.DeliveryMargin),
         new Property("ExchangeDeliveryMargin", tradingAccount.ExchangeDeliveryMargin),
         new Property("ReserveBalance", tradingAccount.ReserveBalance),
         new Property("CurrencyID", tradingAccount.CurrencyID),
         new Property("PreFundMortgageIn", tradingAccount.PreFundMortgageIn),
         new Property("PreFundMortgageOut", tradingAccount.PreFundMortgageOut),
         new Property("FundMortgageIn", tradingAccount.FundMortgageIn),
         new Property("FundMortgageOut", tradingAccount.FundMortgageOut),
         new Property("FundMortgageAvailable", tradingAccount.FundMortgageAvailable),
         new Property("MortgageableFund", tradingAccount.MortgageableFund),
         new Property("SpecProductMargin", tradingAccount.SpecProductMargin),
         new Property("SpecProductFrozenMargin", tradingAccount.SpecProductFrozenMargin),
         new Property("SpecProductCommission", tradingAccount.SpecProductCommission),
         new Property("SpecProductFrozenCommission", tradingAccount.SpecProductFrozenCommission),
         new Property("SpecProductPositionProfit", tradingAccount.SpecProductPositionProfit),
         new Property("SpecProductCloseProfit", tradingAccount.SpecProductCloseProfit),
         new Property("SpecProductPositionProfitByAlg", tradingAccount.SpecProductPositionProfitByAlg),
         new Property("SpecProductExchangeMargin", tradingAccount.SpecProductExchangeMargin)
     });
 }
Esempio n. 18
0
        protected override TraderResult internalGetTradingAccountInfo()
        {
            List <TradingAccount.StockHolderInfo> shis = GetStocks();
            TradingAccount account = new TradingAccount();

            account.AddStockHolder(shis);

            TraderResult result = new TraderResult();

            result.Code   = TraderResultEnum.SUCCESS;
            result.Result = account;

            return(result);
        }
Esempio n. 19
0
        // 成交通知
        public override bool OnTrade(TradeInfo trade)
        {
            QryTradingAccount qryTA = new QryTradingAccount();
            TradingAccount    taRet = new TradingAccount();

            GetTradingAccount(qryTA, ref taRet);

            QryPosition         qryPiso = new QryPosition();
            List <PositionInfo> lstPosi = new List <PositionInfo>();

            GetPositions(qryPiso, ref lstPosi);

            return(true);
        }
Esempio n. 20
0
        public static void Initialize(OptionsAnalyzerContext context)
        {
            context.Database.EnsureCreated();

            if (context.TradingAccounts.Count() == 0)
            {
                TradingAccount paperMoney = new TradingAccount {
                    Name = "paperMoney", Balance = 69957.25m, UnitSize = .5m, RoundTripCommission = 1.5m, ExpectedPriceChange = .4m
                };

                context.TradingAccounts.Add(paperMoney);

                context.SaveChanges();
            }
        }
Esempio n. 21
0
        public void Save(TradingAccountDto dto)
        {
            if (dto.IsNew)
            {
                TradingAccount tradingAccount = dto.MapTo <TradingAccount>();
                this._repository.Insert(tradingAccount);
            }
            else
            {
                TradingAccount tradingAccount = this._repository.Get(dto.Id);
                dto.MapTo(tradingAccount);
            }

            if (dto.Active)
            {
                this.SetActive(dto.Id);
            }
        }
        public void GetUpdateOptions(DateTime newExpiry, Decimal newUnderlyingPrice)
        {
            TradingAccount tradingAccount = _context.TradingAccounts.First();
            Decimal        spread;

            foreach (Option option in _context.Options.ToList())
            {
                option.Expiry            = newExpiry;
                option.UnderlyingPrice   = newUnderlyingPrice;
                option.BlackScholesPrice = option.CalculateBlackScholesPrice(tradingAccount, newUnderlyingPrice);

                spread     = option.Spread;
                option.Bid = option.BlackScholesPrice - (spread / 2m);
                option.Ask = option.BlackScholesPrice + (spread / 2m);
                option.FillCalculatedFields(tradingAccount);
            }

            _context.SaveChanges();
        }
Esempio n. 23
0
 private void GetStocks(TradingAccount account, String[] ps)
 {
     for (int i = 1; i < ps.Length; i++)
     {
         String[]        stocks = ps[i].Split(new string[] { "\t" }, StringSplitOptions.None);
         StockHolderInfo shi    = new StockHolderInfo
         {
             StockCode     = stocks[0],
             StockName     = stocks[1],
             CurrentAmount = int.Parse(stocks[2]),
             EnableAmount  = int.Parse(stocks[3]),
             IncomeAmount  = int.Parse(stocks[4]),
             CostPrice     = float.Parse(stocks[5]),
             KeepCostPrice = float.Parse(stocks[6]),
             LastPrice     = float.Parse(stocks[7]),
             MarketValue   = float.Parse(stocks[10]),
             ExchangeName  = stocks[11],
             StockAccount  = stocks[12]
         };
         account.AddStockHolder(shi);
     }
 }
Esempio n. 24
0
        public async Task <IActionResult> Index(String sortProperty, String sortDirection, Decimal?expectedPriceChange)
        {
            OptionsLayout optionsLayout = new OptionsLayout();

            TradingAccount tradingAccount = await _context.TradingAccounts.FirstOrDefaultAsync();

            if (expectedPriceChange.HasValue)
            {
                tradingAccount.ExpectedPriceChange = expectedPriceChange.Value;

                foreach (Option option in await _context.Options.ToListAsync())
                {
                    option.FillCalculatedFields(tradingAccount);
                }

                await _context.SaveChangesAsync();
            }

            optionsLayout.TradingAccount = tradingAccount;

            if (String.IsNullOrEmpty(sortProperty))
            {
                sortProperty = "BlackScholesPLPercent";
            }

            if (String.IsNullOrEmpty(sortDirection))
            {
                sortDirection = "desc";
            }

            ViewData["sortProperty"]  = sortProperty;
            ViewData["sortDirection"] = sortDirection;

            optionsLayout.Puts  = _context.Options.Where(x => x.OptionType == OptionTypes.Put && x.BlackScholesPLPercent > 0).OrderBy(sortProperty, sortDirection).ToList();
            optionsLayout.Calls = _context.Options.Where(x => x.OptionType == OptionTypes.Call && x.BlackScholesPLPercent > 0).OrderBy(sortProperty, sortDirection).ToList();

            return(View(optionsLayout));
        }
Esempio n. 25
0
        public Message CreateRejectNewOrderExecutionReport(string symbol,
                                                           MarketSide marketSide,
                                                           string clOrdID,
                                                           decimal orderQuantity,
                                                           TradingAccount account,
                                                           string execID,
                                                           string rejectionReason,
                                                           int?rejectionCode = null)
        {
            var exReport = new ExecutionReport(
                new OrderID("unknown orderID"),
                new ExecID(execID),
                new ExecTransType(ExecTransType.NEW),
                new ExecType(ExecType.REJECTED),
                new OrdStatus(OrdStatus.REJECTED),
                new Symbol(symbol),
                TranslateFixFields.Translate(marketSide),
                new LeavesQty(0m),
                new CumQty(0m),
                new AvgPx(0m))
            {
                ClOrdID  = new ClOrdID(clOrdID),
                OrderQty = new OrderQty(orderQuantity)
            };

            if (rejectionCode.HasValue)
            {
                exReport.OrdRejReason = new OrdRejReason(rejectionCode.Value);
            }

            if (TradingAccount.IsSet(account))
            {
                exReport.Account = new Account(account.Name);
            }

            return(exReport);
        }
Esempio n. 26
0
 public static bool IsSet(TradingAccount account)
 {
     return !ReferenceEquals(account, None);
 }
Esempio n. 27
0
 private void GetStocks(TradingAccount account, String[] ps)
 {
     for (int i = 1; i < ps.Length; i++)
     {
         String[] stocks = ps[i].Split(new string[] { "\t" }, StringSplitOptions.None);
         StockHolderInfo shi = new StockHolderInfo
         {
            StockCode = stocks[0],
            StockName = stocks[1],
            CurrentAmount = int.Parse(stocks[2]),
            EnableAmount = int.Parse(stocks[3]),
            IncomeAmount = int.Parse(stocks[4]),
            CostPrice = float.Parse(stocks[5]),
            KeepCostPrice = float.Parse(stocks[6]),
            LastPrice = float.Parse(stocks[7]),
            MarketValue = float.Parse(stocks[10]),
            ExchangeName = stocks[11],
            StockAccount = stocks[12]
         };
         account.AddStockHolder(shi);
     }
 }
Esempio n. 28
0
 static TradingAccount()
 {
     None = new TradingAccount(NotSpecifiedString);
 }
Esempio n. 29
0
        public static ConnectAPI GetConnectAPI(AppIdentityDbContext identitycontext, AppDbContext context, string userName, int?acId)
        {
            ConnectAPI connectAPI   = new ConnectAPI();
            var        useraccounts = identitycontext.AspNetUserForexAccount.Where(u => u.AppIdentityUser.UserName == userName).ToList();
            var        frxaccounts  = new List <FrxAccount>();

            if (useraccounts.Count != 0)
            {
                frxaccounts = context.FrxAccount.Where(x => useraccounts.SingleOrDefault(s => s.AccountNumber == x.AccountNumber && s.Password == x.Password) != null).ToList();
            }
            if (frxaccounts.Count == 0)
            {
                connectAPI.AccountId = 0;
                return(connectAPI);
            }
            var frxaccount = new FrxAccount();

            if (acId == null)
            {
                var tempac1 = new AspNetUserForexAccount();
                var tempac2 = useraccounts.SingleOrDefault(x => x.Alive == true);
                if (tempac2 == null)
                {
                    tempac1 = useraccounts[0];
                }
                else
                {
                    tempac1 = tempac2;
                }
                frxaccount = frxaccounts.SingleOrDefault(x => x.AccountNumber == tempac1.AccountNumber);
            }
            else
            {
                frxaccount = frxaccounts.SingleOrDefault(x => x.AccountId == acId);
            }
            var account = TradingAccount.GetTradingAccounts(frxaccount.ApiUrl, frxaccount.AccessToken).SingleOrDefault(x => x.AccountId == frxaccount.AccountId);

            if (account != null)
            {
                frxaccount.Balance = account.Balance / 100;
            }
            else
            {
                connectAPI.AccountId = 0;
                return(connectAPI);
            }
            connectAPI.UserId                      = useraccounts[0].AppIdentityUserId;
            connectAPI.AccountId                   = frxaccount.AccountId;
            connectAPI.Balance                     = frxaccount.Balance;
            connectAPI.PreciseLeverage             = frxaccount.PreciseLeverage;
            connectAPI.ClientId                    = frxaccount.ClientId;
            connectAPI.ClientSecret                = frxaccount.ClientSecret;
            connectAPI.AccessToken                 = frxaccount.AccessToken;
            connectAPI.RefreshToken                = frxaccount.RefreshToken;
            connectAPI.ConnectUrl                  = frxaccount.ConnectUrl;
            connectAPI.ApiUrl                      = frxaccount.ApiUrl;
            connectAPI.ApiHost                     = frxaccount.ApiHost;
            connectAPI.ApiPort                     = frxaccount.ApiPort;
            connectAPI.TraderRegistrationTimestamp = frxaccount.TraderRegistrationTimestamp;
            return(connectAPI);
        }
Esempio n. 30
0
        public override void OnRspQryTradingAccount(ThostFtdcTradingAccountField pTradingAccount, ThostFtdcRspInfoField pRspInfo, int nRequestID, bool bIsLast)
        {
            if (pRspInfo != null && pRspInfo.ErrorID != 0)
            {
                LogCenter.Error("请求查询资金账户错误:" + pRspInfo.ErrorMsg);
                return;
            }
            if (pTradingAccount == null)
            {
                LogCenter.Error("请求查询资金账户错误,返回值为空");
                return;
            }
            var tradingAccount = new TradingAccount
            {
                BrokerID                       = pTradingAccount.BrokerID,
                AccountID                      = pTradingAccount.AccountID,
                PreMortgage                    = pTradingAccount.PreMortgage,
                PreCredit                      = pTradingAccount.PreCredit,
                PreDeposit                     = pTradingAccount.PreDeposit,
                PreBalance                     = pTradingAccount.PreBalance,
                PreMargin                      = pTradingAccount.PreMargin,
                InterestBase                   = pTradingAccount.InterestBase,
                Interest                       = pTradingAccount.Interest,
                Deposit                        = pTradingAccount.Deposit,
                Withdraw                       = pTradingAccount.Withdraw,
                FrozenMargin                   = pTradingAccount.FrozenMargin,
                FrozenCash                     = pTradingAccount.FrozenCash,
                FrozenCommission               = pTradingAccount.FrozenCommission,
                CurrMargin                     = pTradingAccount.CurrMargin,
                CashIn                         = pTradingAccount.CashIn,
                Commission                     = pTradingAccount.Commission,
                CloseProfit                    = pTradingAccount.CloseProfit,
                PositionProfit                 = pTradingAccount.PositionProfit,
                Balance                        = pTradingAccount.Balance,
                Available                      = pTradingAccount.Available,
                WithdrawQuota                  = pTradingAccount.WithdrawQuota,
                Reserve                        = pTradingAccount.Reserve,
                TradingDay                     = pTradingAccount.TradingDay,
                SettlementID                   = pTradingAccount.SettlementID,
                Credit                         = pTradingAccount.Credit,
                Mortgage                       = pTradingAccount.Mortgage,
                ExchangeMargin                 = pTradingAccount.ExchangeMargin,
                DeliveryMargin                 = pTradingAccount.DeliveryMargin,
                ExchangeDeliveryMargin         = pTradingAccount.ExchangeDeliveryMargin,
                ReserveBalance                 = pTradingAccount.ReserveBalance,
                CurrencyID                     = pTradingAccount.CurrencyID,
                PreFundMortgageIn              = pTradingAccount.PreFundMortgageIn,
                PreFundMortgageOut             = pTradingAccount.PreFundMortgageOut,
                FundMortgageIn                 = pTradingAccount.FundMortgageIn,
                FundMortgageOut                = pTradingAccount.FundMortgageOut,
                FundMortgageAvailable          = pTradingAccount.FundMortgageAvailable,
                MortgageableFund               = pTradingAccount.MortgageableFund,
                SpecProductMargin              = pTradingAccount.SpecProductMargin,
                SpecProductFrozenMargin        = pTradingAccount.SpecProductFrozenMargin,
                SpecProductCommission          = pTradingAccount.SpecProductCommission,
                SpecProductFrozenCommission    = pTradingAccount.SpecProductFrozenCommission,
                SpecProductPositionProfit      = pTradingAccount.SpecProductPositionProfit,
                SpecProductCloseProfit         = pTradingAccount.SpecProductCloseProfit,
                SpecProductPositionProfitByAlg = pTradingAccount.SpecProductPositionProfitByAlg,
                SpecProductExchangeMargin      = pTradingAccount.SpecProductExchangeMargin,
            };

            TradingAccountViewModel.Instance.Update(tradingAccount);
        }
Esempio n. 31
0
        //将xml字符串转换成资金TradingAccount结构
        public void Transfer(string strXml, ref TradingAccount tradingAccount)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(strXml);

            //取得节点名为Fund的XmlNode集合
            XmlNodeList xxList = doc.GetElementsByTagName("Fund");

            foreach (XmlNode xxNode in xxList)
            {
                XmlNodeList childList = xxNode.ChildNodes;
                //取得InstrumentID下的子节点集合
                foreach (XmlNode xxxxNode in xxList)
                {
                    ///经纪公司代码
                    tradingAccount.BrokerID = xxxxNode.Attributes["BrokerID"].Value;
                    ///投资者帐号
                    tradingAccount.AccountID = xxxxNode.Attributes["AccountID"].Value;
                    ///入金金额
                    tradingAccount.Deposit = double.Parse(xxxxNode.Attributes["Deposit"].Value);
                    ///出金金额
                    tradingAccount.Withdraw = double.Parse(xxxxNode.Attributes["Withdraw"].Value);
                    ///冻结的保证金
                    tradingAccount.FrozenMargin = double.Parse(xxxxNode.Attributes["FrozenMargin"].Value);
                    ///冻结的资金
                    tradingAccount.FrozenCash = double.Parse(xxxxNode.Attributes["FrozenCash"].Value);
                    ///冻结的手续费
                    tradingAccount.FrozenCommission = double.Parse(xxxxNode.Attributes["FrozenCommission"].Value);
                    ///当前保证金总额
                    tradingAccount.CurrMargin = double.Parse(xxxxNode.Attributes["CurrMargin"].Value);
                    ///资金差额
                    tradingAccount.CashIn = double.Parse(xxxxNode.Attributes["CashIn"].Value);
                    ///手续费
                    tradingAccount.Commission = double.Parse(xxxxNode.Attributes["Commission"].Value);
                    ///平仓盈亏
                    tradingAccount.CloseProfit = double.Parse(xxxxNode.Attributes["CloseProfit"].Value);
                    ///持仓盈亏
                    tradingAccount.PositionProfit = double.Parse(xxxxNode.Attributes["PositionProfit"].Value);
                    ///期货结算准备金
                    tradingAccount.Balance = double.Parse(xxxxNode.Attributes["Balance"].Value);
                    ///可用资金
                    tradingAccount.Available = double.Parse(xxxxNode.Attributes["Available"].Value);
                    ///可取资金
                    tradingAccount.WithdrawQuota = double.Parse(xxxxNode.Attributes["WithdrawQuota"].Value);
                    ///基本准备金
                    tradingAccount.Reserve = double.Parse(xxxxNode.Attributes["Reserve"].Value);
                    ///交易日
                    tradingAccount.TradingDay = xxxxNode.Attributes["TradingDay"].Value;
                    ///信用额度
                    tradingAccount.Credit = double.Parse(xxxxNode.Attributes["Credit"].Value);
                    ///质押金额
                    tradingAccount.Mortgage = double.Parse(xxxxNode.Attributes["Mortgage"].Value);
                    ///交易所保证金
                    tradingAccount.ExchangeMargin = double.Parse(xxxxNode.Attributes["ExchangeMargin"].Value);
                    ///投资者交割保证金
                    tradingAccount.DeliveryMargin = double.Parse(xxxxNode.Attributes["DeliveryMargin"].Value);
                    ///交易所交割保证金
                    tradingAccount.ExchangeDeliveryMargin = double.Parse(xxxxNode.Attributes["ExchangeDeliveryMargin"].Value);
                    ///静态权益
                    tradingAccount.StaticProfit = double.Parse(xxxxNode.Attributes["StaticProfit"].Value);
                    ///动态权益
                    tradingAccount.DynamicProfit = double.Parse(xxxxNode.Attributes["DynamicProfit"].Value);
                    ///风险度
                    tradingAccount.RiskDegree = double.Parse(xxxxNode.Attributes["RiskDegree"].Value);
                }
            }
        }
Esempio n. 32
0
 public static bool IsSet(TradingAccount account)
 {
     return(!ReferenceEquals(account, None));
 }
Esempio n. 33
0
 static TradingAccount()
 {
     None = new TradingAccount(NotSpecifiedString);
 }