/// <summary> /// Initializes a new instance of the <see cref="Portfolio"/> class. /// </summary> /// <param name="clock">The clock.</param> /// <param name="actionscheduler">The actionscheduler.</param> /// <param name="brokerconnection">The brokerconnection.</param> /// <param name="brokermodel">The brokermodel.</param> /// <param name="currency">The currency.</param> /// <param name="eventrunner">The eventrunner.</param> /// <param name="exceptionhandler">The exceptionhandler.</param> /// <param name="orderTicketHandler">The order ticket handler.</param> /// <param name="brokeraccount">The brokeraccount.</param> /// <param name="cashmanager">The cashmanager.</param> /// <param name="runmode">The runmode.</param> /// <param name="datafeed">The datafeed.</param> /// <param name="benchmark">The benchmark.</param> /// <param name="id">The identifier.</param> public Portfolio(WorldClock clock, ActionsScheduler actionscheduler, BrokerConnection brokerconnection, BrokerModel brokermodel, Currency currency, EventRunner eventrunner, ExceptionHandler exceptionhandler, OrderTicketHandler orderTicketHandler, BrokerAccount brokeraccount, CashManager cashmanager, RunMode runmode, DataFeed datafeed, Benchmark benchmark, string id = "") { //Set references ActionsScheduler = actionscheduler; BrokerAccount = brokeraccount; BrokerConnection = brokerconnection; BrokerModel = brokermodel; Clock = clock; Currency = currency; EventRunner = eventrunner; ExceptionHandler = exceptionhandler; CashManager = cashmanager; OrderTicketHandler = orderTicketHandler; _porfolioBenchmark = benchmark; //Set initial items Id = id; IsBacktesting = runmode == RunMode.Backtester; OrderFactory = new OrderFactory(this, BrokerModel); OrderTracker = new OrderTracker(this); Subscription = new DataSubscriptionManager(datafeed, CashManager); Results = new Result(0, _porfolioBenchmark); //Portfolio benchmark is not used benchmark.OnCalc(x => 0); }
public async Task <BrokerAccount> CreateAccount(string playerName) { var Bank = cache.Get <AllBankRecords>(playerName + "_Bank"); if (Bank == null) { throw new System.Exception("Bank account needs to be created first!"); } var Broker = cache.Get <AllBankRecords>(playerName + "_Broker"); if (Broker != null) { throw new System.Exception("Broker account has been already created for this user!"); } BrokerAccount newPlayer = new BrokerAccount() { }; newPlayer.PlayerName = playerName; var allBrokerData = new AllBrokerData() { }; allBrokerData.Accounts = newPlayer; cache.Set(newPlayer.PlayerName + "_Broker", allBrokerData, Constants.cacheTime); return(newPlayer); }
public override void OnStrategyStart() { base.OnStrategyStart(); // 测试用,自定义交易时间,仿真或实盘时可删除 base.TimeHelper = new TimeHelper(new int[] { 0, 2400 }, 2100, 1458); base.TargetPosition = 0; //base.DualPosition.Long.Qty = 0; //base.DualPosition.Long.QtyToday = 0; //base.DualPosition.Short.Qty = 0; //base.DualPosition.Short.QtyToday = 0; if (BrokerInfo == null) { // 使用静态的主要原因是每个实例都来取一次没有必要 BrokerInfo = DataManager.GetBrokerInfo(); } if (BrokerInfo.Accounts.Count > 0) { BrokerAccount brokerAccount = BrokerInfo.Accounts[0]; GetBrokerInfoHelper.Transform(brokerAccount, base.DualPosition); } LoadHistoricalBars(Clock.Now); BarSeries bars1min = GetBars(BarType.Time, BarSize); fastSMA = new SMA(bars1min, fastLength, Color.Red); slowSMA = new SMA(bars1min, slowLength, Color.Green); Draw(fastSMA, 0); Draw(slowSMA, 0); }
/// <summary> /// Settle funds, delayed /// </summary> /// <param name="account">The account.</param> /// <param name="quantfund">The quantfund.</param> /// <param name="security">The security.</param> /// <param name="occureddtutc">The occureddtutc.</param> /// <param name="amount">The amount.</param> public void SettleFunds(BrokerAccount account, Security security, DateTime occureddtutc, decimal amount, IQuantFund quantfund = null) { //Added funds if (amount > 0) { //Get exchangeModel based local time DateTime settlementdate = security.Exchange.LocalTime; //Check for date based on market opened date and time for (int i = 0; i < DelayedDays; i++) { settlementdate = settlementdate.AddDays(i); if (!security.Exchange.IsOpenOnDate(settlementdate)) { i--; } } //Get correct date and time settlementdate = settlementdate.Add(TimeOfDay); //Convert time of day from local exchangeModel timezone to utc based time settlementdate = settlementdate.ConvertTo(security.Exchange.TimeZone, TimeZone.Utc); //Add unsettled funds (to be settled on a later time and date) account.Cash.AddCash(security.BaseCurrency, amount, quantfund, settlementdate); } else //Used funds, settle right away { account.Cash.AddCash(security.BaseCurrency, amount, quantfund); } }
/// <summary> /// Initialize position tracker /// </summary> /// <param name="account"></param> /// <param name="fundid"></param> /// <param name="benchmark"></param> /// <param name="initialcapital"></param> public PositionTracker(BrokerAccount account, string fundid = "", Benchmark benchmark = null, decimal initialcapital = 0m) { Account = account; _fundId = fundid; Result = new Result(initialcapital, benchmark); }
private void H4vuEjxO1C(BinaryWriter obj0, BrokerAccount obj1) { obj0.Write(obj1.Name); obj0.Write(obj1.BuyingPower); BrokerOrder[] orders = obj1.GetOrders(); obj0.Write(orders.Length); foreach (BrokerOrder brokerOrder in orders) { this.RoYu8jI0tu(obj0, brokerOrder); } BrokerPosition[] positions = obj1.GetPositions(); obj0.Write(positions.Length); foreach (BrokerPosition brokerPosition in positions) { this.oR3uofPPWO(obj0, brokerPosition); } BrokerAccountField[] fields = obj1.GetFields(); obj0.Write(fields.Length); foreach (BrokerAccountField brokerAccountField in fields) { obj0.Write(brokerAccountField.Name); obj0.Write(brokerAccountField.Value); obj0.Write(brokerAccountField.Currency); } }
private BrokerAccount cKpu5qjmIn(BinaryReader obj0) { string name1 = obj0.ReadString(); double num1 = obj0.ReadDouble(); BrokerAccount brokerAccount = new BrokerAccount(name1); brokerAccount.BuyingPower = num1; int num2 = obj0.ReadInt32(); for (int index = 0; index < num2; ++index) { brokerAccount.AddOrder(this.vHxhvWlydv(obj0)); } int num3 = obj0.ReadInt32(); for (int index = 0; index < num3; ++index) { brokerAccount.AddPosition(this.lrvuzgJsBI(obj0)); } int num4 = obj0.ReadInt32(); for (int index = 0; index < num4; ++index) { string name2 = obj0.ReadString(); string str = obj0.ReadString(); string currency = obj0.ReadString(); brokerAccount.AddField(name2, currency, str); } return(brokerAccount); }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { tdlog.Info("GetBrokerInfo"); //TraderApi.TD_ReqQryTradingAccount(m_pTdApi); //TraderApi.TD_ReqQryInvestorPosition(m_pTdApi, null); //timerAccount.Enabled = false; //timerAccount.Enabled = true; //timerPonstion.Enabled = false; //timerPonstion.Enabled = true; BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID) { BuyingPower = m_TradingAccount.Available }; Type t = typeof(CThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } DataRow[] rows = _dbInMemInvestorPosition.SelectAll(); foreach (DataRow dr in rows) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = dr[DbInMemInvestorPosition.InstrumentID].ToString() }; int pos = (int)dr[DbInMemInvestorPosition.Position]; TThostFtdcPosiDirectionType PosiDirection = (TThostFtdcPosiDirectionType)dr[DbInMemInvestorPosition.PosiDirection]; if (TThostFtdcPosiDirectionType.Long == PosiDirection) { brokerPosition.LongQty = pos; } else if (TThostFtdcPosiDirectionType.Short == PosiDirection) { brokerPosition.ShortQty = pos; } else { if (pos >= 0)//净NET这个概念是什么情况? brokerPosition.LongQty = pos; else brokerPosition.ShortQty = -pos; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; brokerPosition.AddCustomField(DbInMemInvestorPosition.PosiDirection, PosiDirection.ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.HedgeFlag, ((TThostFtdcHedgeFlagType)dr[DbInMemInvestorPosition.HedgeFlag]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.PositionDate, ((TThostFtdcPositionDateType)dr[DbInMemInvestorPosition.PositionDate]).ToString()); brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return brokerInfo; }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { if (_bTdConnected) { } else { return(brokerInfo); } BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID) { BuyingPower = m_TradingAccount.Available }; Type t = typeof(CThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } foreach (CThostFtdcInvestorPositionField pos in _dictPositions.Values) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = pos.InstrumentID }; if (TThostFtdcPosiDirectionType.Long == pos.PosiDirection) { brokerPosition.LongQty = pos.Position; } else if (TThostFtdcPosiDirectionType.Short == pos.PosiDirection) { brokerPosition.ShortQty = pos.Position; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; Type t2 = typeof(CThostFtdcInvestorPositionField); FieldInfo[] fields2 = t2.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields2) { brokerPosition.AddCustomField(field.Name, field.GetValue(pos).ToString()); } brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return(brokerInfo); }
/// <summary> /// Sends the performance information messages. /// </summary> /// <param name="account"></param> /// <param name="quantfunds">The quantfunds.</param> public void SendPerformanceInfoMessages(BrokerAccount account, IQuantFund[] quantfunds) { if (!IsRunning || !HasSubscribers) { return; } quantfunds.ForEach(x => Enqueue(PerformanceInfoMessage.Create(x.FundId, x.Results, account.DisplayCurrency))); }
public void Start(int barsPause = 0) { this.barsPause = barsPause; if (dataStreamSource is string) { string barDataFile = dataStreamSource as string; BacktestBroker backtestBroker = new BacktestBroker(); brokerAccount = new BrokerAccount(); backtestBroker.LoadAccount(brokerAccount, cacheId); backtestSession = backtestBroker.CreateSession(brokerAccount.AccountId, tickerType, barType, dataStreamSource.ToString(), cacheId); foreach (AnalyticsItem item in registeredAnalytics) { if (item.AnaylticsType == AnalyticsTypeOption.Indicator) { backtestSession.Indicators.Add <IIndicatorCore>(item.Instance as IIndicatorCore); } if (item.AnaylticsType == AnalyticsTypeOption.Signal) { backtestSession.Signals.Add <ISignal>(item.Instance as ISignal); } } barCount = 0; backtestSession.NewBar += OnNewBar; backtestSession.Signals.OpenCache(barType); backtestSession.Start(); backtestSession.Signals.CloseCache(barType); //SignalCacheNavigator signalCacheNavigator = new SignalCacheNavigator("cache", barType, cacheId, registeredAnalytics[0].IdentityCode); //ignalDataFrame signalDataFrame= signalCacheNavigator.GetSignalDataFrame(signalCacheNavigator.StartBarDate, 300); chartControl.Initialize(200, 100, "cache", barType, cacheId, registeredAnalytics[0].IdentityCode); if (barsPause == 0) { //Refresh(); } //double profit= brokerAccount.Orders.GetTotalProfit(SpotForex.EURUSD); //double loss = brokerAccount.Orders.GetTotalLoss(SpotForex.EURUSD); } }
public void OnFundStatusReport(object sender, FundStatusReportEventArgs e) { this.brokerAccount = new BrokerAccount("国信-" + this.fundID); this.brokerAccount.AddField("Balance", e.Balance.ToString()); this.brokerAccount.AddField("AvailableBalance", e.AvailableBalance.ToString()); this.brokerAccount.AddField("TotalAssets", e.TotalAssets.ToString()); this.brokerAccount.AddField("CapitalAssets", e.CapitalAssets.ToString()); this.brokerAccount.AddField("MarketValue", e.MarketValue.ToString()); this.brokerAccount.AddField("BuyFreezed", e.BuyFreezed.ToString()); this.brokerAccount.BuyingPower = e.AvailableBalance; }
/// <summary> /// Settle funds to account right away /// </summary> /// <param name="account">The account.</param> /// <param name="quantfund">The quantfund.</param> /// <param name="security">The security.</param> /// <param name="occureddtutc">The occureddtutc.</param> /// <param name="amount">The amount.</param> /// <exception cref="NullReferenceException">Could not find quant fund for settlement</exception> public void SettleFunds(BrokerAccount account, Security security, DateTime occureddtutc, decimal amount, IQuantFund quantfund = null) { //check if we found agent if (quantfund == null) { throw new NullReferenceException("Could not find quant fund for settlement"); } //Add settled funds account.Cash.AddCash(security.BaseCurrency, amount, quantfund); }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { if (_bTdConnected) { } else { return brokerInfo; } BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID) { BuyingPower = m_TradingAccount.Available }; Type t = typeof(CThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } foreach (CThostFtdcInvestorPositionField pos in _dictPositions.Values) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = pos.InstrumentID }; if (TThostFtdcPosiDirectionType.Long == pos.PosiDirection) { brokerPosition.LongQty = pos.Position; } else if (TThostFtdcPosiDirectionType.Short == pos.PosiDirection) { brokerPosition.ShortQty = pos.Position; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; Type t2 = typeof(CThostFtdcInvestorPositionField); FieldInfo[] fields2 = t2.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields2) { brokerPosition.AddCustomField(field.Name, field.GetValue(pos).ToString()); } brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return brokerInfo; }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (!this.isConnected) { this.EmitError(this.Id, -1, "The TDXTradeProvider is not connected."); return(brokerInfo); } ReportArgs rargs = this.trader.QueryFund(); if (rargs.Succeeded && rargs.Result != null) { FundRecord fundRecord = (FundRecord)rargs.Result; BrokerAccount brokerAccount = new BrokerAccount("通达信-" + this.fundID); brokerAccount.AddField("Balance", fundRecord.Balance.ToString()); brokerAccount.AddField("Available", fundRecord.Available.ToString()); brokerAccount.AddField("TotalAssets", fundRecord.TotalAsserts.ToString()); brokerAccount.AddField("Desirable", fundRecord.Desirable.ToString()); brokerAccount.AddField("MarketValue", fundRecord.MarketValue.ToString()); brokerAccount.AddField("Frozen", fundRecord.Frozen.ToString()); brokerAccount.BuyingPower = fundRecord.Available; brokerInfo.Accounts.Add(brokerAccount); rargs = this.trader.QueryPositions(); if (rargs.Succeeded && rargs.Result != null) { List <PositionRecord> positions = (List <PositionRecord>)rargs.Result; foreach (PositionRecord position in positions) { BrokerPosition brokerPosition = new BrokerPosition(); brokerPosition.SecurityExchange = position.SecurityExchange; brokerPosition.Symbol = position.SecurityExchange + "." + position.SecurityID; brokerPosition.AddCustomField("Available", position.Available.ToString()); brokerPosition.Qty = position.Quantity; brokerPosition.AddCustomField("CostPrice", position.CostPrice.ToString()); brokerPosition.LongQty = position.Quantity; brokerAccount.AddPosition(brokerPosition); } } else { this.EmitError(this.Id, -1, rargs.ErrorInfo); } } else { this.EmitError(this.Id, -1, rargs.ErrorInfo); } return(brokerInfo); }
/// <summary> /// Check if margin calls are applicable and reveive any order tickets associated to this margin call /// </summary> /// <param name="quantFunds"></param> /// <param name="account"></param> /// <param name="marginwarning"></param> /// <returns></returns> public OrderTicket[] CheckMarginCall(IQuantFund[] quantFunds, BrokerAccount account, out bool marginwarning) { //Initials marginwarning = false; List <OrderTicket> toreturn = new List <OrderTicket>(); //Check margin in use if (account.MarginInUse == 0) { return(toreturn.ToArray()); } //Check margin level warning if (account.MarginLevel <= account.MarginCallLevel) { marginwarning = true; } //Generate margin call orders decimal marginneeded = account.Equity * .2M; //No margin left == margin call if (account.FreeMargin <= marginneeded) { //Set level of margin we need to thrive for decimal marginprocessed = Math.Abs(account.FreeMargin - marginneeded); //Go trough all positions foreach (var position in quantFunds.SelectMany(x => x.Positions) .Where(x => !x.IsFlat) .OrderBy(x => x.NetProfit)) { //Check for order var quantfund = quantFunds.First(x => x.Positions[position.Security].Quantity == position.Quantity); var order = GetMarginCallOrder(quantfund.FundId, position, ref marginprocessed); if (order != null && order.Quantity != 0) { toreturn.Add(order); } //Check processed margin if (marginprocessed <= 0) { break; } } } //Return orders return(toreturn.ToArray()); }
public void M2Timeframe() { BacktestBroker backtestBroker = new BacktestBroker(); BrokerAccount brokerAccount = new BrokerAccount(); backtestBroker.LoadAccount(new BrokerAccount(), Guid.Empty); BacktestSession backtestSession = backtestBroker.CreateSession(brokerAccount.AccountId, SpotForex.EURUSD, Timeframes.M1, @"data\EURUSD-M1.bar", Guid.Empty); BollingerBands bollingerBands = new BollingerBands(Timeframes.M2, 21); backtestSession.Indicators.Add(bollingerBands); backtestSession.Start(); }
public void MACDTest() { BacktestBroker backtestBroker = new BacktestBroker(); BrokerAccount brokerAccount = new BrokerAccount(); backtestBroker.LoadAccount(new BrokerAccount(), Guid.Empty); BacktestSession backtestSession = backtestBroker.CreateSession(brokerAccount.AccountId, SpotForex.EURUSD, Timeframes.M1, @"data\EURUSD-M1.bar", Guid.Empty); MACD macd = new MACD(Timeframes.M1, 12, 26, 9); backtestSession.Indicators.Add(macd); backtestSession.Start(); }
public void EMATest() { BacktestBroker backtestBroker = new BacktestBroker(); BrokerAccount brokerAccount = new BrokerAccount(); backtestBroker.LoadAccount(new BrokerAccount(), Guid.Empty); BacktestSession backtestSession = backtestBroker.CreateSession(brokerAccount.AccountId, SpotForex.EURUSD, Timeframes.M1, @"data\EURUSD-M1.bar", Guid.Empty); EMA ema = new EMA(Timeframes.M1, 100); backtestSession.Indicators.Add(ema); backtestSession.Start(); }
public static void Tarnsform(BrokerAccount brokerAccount, string Symbol, out int LongQtyToday, out int LongQtyYd, out int ShortQtyToday, out int ShortQtyYd ) { LongQtyToday = 0; LongQtyYd = 0; ShortQtyToday = 0; ShortQtyYd = 0; foreach (BrokerPosition bp in brokerAccount.Positions) { if (bp.Symbol != Symbol) { continue; } // 会收到很多,得按类别进行设置 // 按日子、多空 // 投机与套保这种不进行区分,因为太复杂了,我也没法测试 if (bp.Fields[PosiDirection].Value == Long) { if (bp.Fields[PositionDate].Value == Today) { LongQtyToday += Convert.ToInt32(bp.Fields[Position].Value); } else { LongQtyYd += Convert.ToInt32(bp.Fields[Position].Value); } } else { if (bp.Fields[PositionDate].Value == Today) { ShortQtyToday += Convert.ToInt32(bp.Fields[Position].Value); } else { ShortQtyYd += Convert.ToInt32(bp.Fields[Position].Value); } } } }
public void LoadBrokerAccounts(ITradeDetailsAutoCalculatorService tradeCalculatorService, string mainDirectoryWithApplicationName) { foreach (var broker in Brokers) { var account = BrokerAccount.LoadAccount(broker, mainDirectoryWithApplicationName); if (account == null) { account = new BrokerAccount { BrokerName = broker.Name }; } AccountsLookup[broker] = account; } }
public BrokerAccount Start(int barsPause = 0) { this.barsPause = barsPause; BrokerAccount brokerAccount = null; if (dataStreamSource is string) { string barDataFile = dataStreamSource as string; BacktestBroker backtestBroker = new BacktestBroker(); brokerAccount = new BrokerAccount(); backtestBroker.LoadAccount(brokerAccount, cacheId); backtestSession = backtestBroker.CreateSession(brokerAccount.AccountId, tickerType, barType, dataStreamSource.ToString(), cacheId); foreach (AnalyticsItem item in registeredAnalytics) { if (item.AnaylticsType == AnalyticsTypeOption.Indicator) { backtestSession.Indicators.Add <IIndicatorCore>(item.Instance as IIndicatorCore); } if (item.AnaylticsType == AnalyticsTypeOption.Signal) { backtestSession.Signals.Add <ISignal>(item.Instance as ISignal); } //if (item.AnaylticsType == AnalyticsTypeOption.Strategy) //{ // backtestSession.Strategies.Add<IStrategy>(item.Instance as IStrategy); //} } barCount = 0; backtestSession.NewBar += OnNewBar; backtestSession.Start(); } return(brokerAccount); }
public static void Transform(BrokerAccount brokerAccount, DualPosition dualPosition) { if (brokerAccount == null || dualPosition == null) { return; } int LongQtyToday = 0; int LongQtyYd = 0; int ShortQtyToday = 0; int ShortQtyYd = 0; Tarnsform(brokerAccount, dualPosition.Symbol, out LongQtyToday, out LongQtyYd, out ShortQtyToday, out ShortQtyYd); dualPosition.Long.QtyToday = LongQtyToday; dualPosition.Long.Qty = LongQtyToday + LongQtyYd; dualPosition.Short.QtyToday = ShortQtyToday; dualPosition.Short.Qty = ShortQtyToday + ShortQtyYd; }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { Console.WriteLine(string.Format("GetBrokerInfo:{0}", Clock.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"))); //TraderApi.TD_ReqQryTradingAccount(m_pTdApi); //TraderApi.TD_ReqQryInvestorPosition(m_pTdApi, null); //timerAccount.Enabled = false; //timerAccount.Enabled = true; //timerPonstion.Enabled = false; //timerPonstion.Enabled = true; BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID); // account fields brokerAccount.BuyingPower = m_TradingAccount.Available; brokerAccount.AddField("Available", m_TradingAccount.Available.ToString()); brokerAccount.AddField("Balance", m_TradingAccount.Balance.ToString()); brokerAccount.AddField("CashIn", m_TradingAccount.CashIn.ToString()); brokerAccount.AddField("CloseProfit", m_TradingAccount.CloseProfit.ToString()); brokerAccount.AddField("Commission", m_TradingAccount.Commission.ToString()); brokerAccount.AddField("Credit", m_TradingAccount.Credit.ToString()); brokerAccount.AddField("CurrMargin", m_TradingAccount.CurrMargin.ToString()); brokerAccount.AddField("DeliveryMargin", m_TradingAccount.DeliveryMargin.ToString()); brokerAccount.AddField("Deposit", m_TradingAccount.Deposit.ToString()); brokerAccount.AddField("ExchangeDeliveryMargin", m_TradingAccount.ExchangeDeliveryMargin.ToString()); brokerAccount.AddField("ExchangeMargin", m_TradingAccount.ExchangeMargin.ToString()); brokerAccount.AddField("FrozenCash", m_TradingAccount.FrozenCash.ToString()); brokerAccount.AddField("FrozenCommission", m_TradingAccount.FrozenCommission.ToString()); brokerAccount.AddField("FrozenMargin", m_TradingAccount.FrozenMargin.ToString()); brokerAccount.AddField("Interest", m_TradingAccount.Interest.ToString()); brokerAccount.AddField("InterestBase", m_TradingAccount.InterestBase.ToString()); brokerAccount.AddField("Mortgage", m_TradingAccount.Mortgage.ToString()); brokerAccount.AddField("PositionProfit", m_TradingAccount.PositionProfit.ToString()); brokerAccount.AddField("PreBalance", m_TradingAccount.PreBalance.ToString()); brokerAccount.AddField("PreCredit", m_TradingAccount.PreCredit.ToString()); brokerAccount.AddField("PreDeposit", m_TradingAccount.PreDeposit.ToString()); brokerAccount.AddField("PreMargin", m_TradingAccount.PreMargin.ToString()); brokerAccount.AddField("PreMortgage", m_TradingAccount.PreMortgage.ToString()); brokerAccount.AddField("Reserve", m_TradingAccount.Reserve.ToString()); brokerAccount.AddField("SettlementID", m_TradingAccount.SettlementID.ToString()); brokerAccount.AddField("Withdraw", m_TradingAccount.Withdraw.ToString()); brokerAccount.AddField("WithdrawQuota", m_TradingAccount.WithdrawQuota.ToString()); DataRow[] rows = _dbInMemInvestorPosition.SelectAll(); foreach (DataRow dr in rows) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = dr[DbInMemInvestorPosition.InstrumentID].ToString() }; int pos = (int)dr[DbInMemInvestorPosition.Position]; TThostFtdcPosiDirectionType PosiDirection = (TThostFtdcPosiDirectionType)dr[DbInMemInvestorPosition.PosiDirection]; if (TThostFtdcPosiDirectionType.Long == PosiDirection) { brokerPosition.LongQty = pos; } else if (TThostFtdcPosiDirectionType.Short == PosiDirection) { brokerPosition.ShortQty = pos; } else { if (pos >= 0)//净NET这个概念是什么情况? brokerPosition.LongQty = pos; else brokerPosition.ShortQty = -pos; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; brokerPosition.AddCustomField(DbInMemInvestorPosition.PosiDirection, PosiDirection.ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.HedgeFlag, ((TThostFtdcHedgeFlagType)dr[DbInMemInvestorPosition.HedgeFlag]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.PositionDate, ((TThostFtdcPositionDateType)dr[DbInMemInvestorPosition.PositionDate]).ToString()); brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return brokerInfo; }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { if (_bTdConnected) { //tdlog.Info("GetBrokerInfo"); } else { //if (nGetBrokerInfoCount < 5) //{ // tdlog.Info("GetBrokerInfo,交易没有连接,查询无效,5次后将不显示"); // ++nGetBrokerInfoCount; //} return(null); } BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID); // account fields brokerAccount.BuyingPower = m_TradingAccount.Available; Type t = typeof(CZQThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } DataRow[] rows = _dbInMemInvestorPosition.SelectAll(); foreach (DataRow dr in rows) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = dr[DbInMemInvestorPosition.InstrumentID].ToString() }; int pos = (int)dr[DbInMemInvestorPosition.Position]; TZQThostFtdcPosiDirectionType PosiDirection = (TZQThostFtdcPosiDirectionType)dr[DbInMemInvestorPosition.PosiDirection]; if (TZQThostFtdcPosiDirectionType.Long == PosiDirection) { brokerPosition.LongQty = pos; } else if (TZQThostFtdcPosiDirectionType.Short == PosiDirection) { brokerPosition.ShortQty = pos; } else { if (pos >= 0)//净NET这个概念是什么情况? { brokerPosition.LongQty = pos; } else { brokerPosition.ShortQty = -pos; } } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; brokerPosition.AddCustomField(DbInMemInvestorPosition.PosiDirection, PosiDirection.ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.HedgeFlag, ((TZQThostFtdcHedgeFlagType)dr[DbInMemInvestorPosition.HedgeFlag]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.PositionDate, ((TZQThostFtdcPositionDateType)dr[DbInMemInvestorPosition.PositionDate]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.LongFrozen, dr[DbInMemInvestorPosition.LongFrozen].ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.ShortFrozen, dr[DbInMemInvestorPosition.ShortFrozen].ToString()); brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return(brokerInfo); }
/// <summary> /// Returns the amount of day trading orders left before day trading flag has been triggered /// http://www.finra.org/investors/day-trading-margin-requirements-know-rules /// </summary> /// <param name="account">The brokerage account</param> /// <param name="historicalfills">The historical fills.</param> /// <returns></returns> public virtual void DayTradingOrdersLeft(BrokerAccount account, Fill[] historicalfills) { account.DayTradingOrdersLeft = int.MaxValue; account.PatternDayTradingHit = false; }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { if (_bTdConnected) { //tdlog.Info("GetBrokerInfo"); } else { //if (nGetBrokerInfoCount < 5) //{ // tdlog.Info("GetBrokerInfo,交易没有连接,查询无效,5次后将不显示"); // ++nGetBrokerInfoCount; //} return null; } BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID); // account fields brokerAccount.BuyingPower = m_TradingAccount.Available; Type t = typeof(CZQThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } DataRow[] rows = _dbInMemInvestorPosition.SelectAll(); foreach (DataRow dr in rows) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = dr[DbInMemInvestorPosition.InstrumentID].ToString() }; int pos = (int)dr[DbInMemInvestorPosition.Position]; TZQThostFtdcPosiDirectionType PosiDirection = (TZQThostFtdcPosiDirectionType)dr[DbInMemInvestorPosition.PosiDirection]; if (TZQThostFtdcPosiDirectionType.Long == PosiDirection) { brokerPosition.LongQty = pos; } else if (TZQThostFtdcPosiDirectionType.Short == PosiDirection) { brokerPosition.ShortQty = pos; } else { if (pos >= 0)//净NET这个概念是什么情况? brokerPosition.LongQty = pos; else brokerPosition.ShortQty = -pos; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; brokerPosition.AddCustomField(DbInMemInvestorPosition.PosiDirection, PosiDirection.ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.HedgeFlag, ((TZQThostFtdcHedgeFlagType)dr[DbInMemInvestorPosition.HedgeFlag]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.PositionDate, ((TZQThostFtdcPositionDateType)dr[DbInMemInvestorPosition.PositionDate]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.LongFrozen, dr[DbInMemInvestorPosition.LongFrozen].ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.ShortFrozen, dr[DbInMemInvestorPosition.ShortFrozen].ToString()); brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return brokerInfo; }
/// <summary> /// Sets the broker account. /// </summary> /// <param name="account">The account.</param> public void SetBrokerAccount(BrokerAccount account) => _brokeraccount = account;
/// <summary> /// Gets the calculated funds. /// </summary> /// <param name="account">The account.</param> /// <returns></returns> public CalculatedFunds GetCalculatedFunds(BrokerAccount account) => new CalculatedFunds(this, account.Positions, _leverage, account.PatternDayTradingHit, account.DayTradingOrdersLeft);
public static List <(DateTime Time, decimal Value)> GetDailyTotalNetMoneyIn(IBroker broker, BrokerAccount account, IBrokersCandlesService candlesService) { var ret = new List <(DateTime Time, decimal Value)>(); /*for (var date = new DateTime(2018, 1, 1); date <= DateTime.UtcNow; date = date.AddDays(1)) * { * var netMoneyIn = 0.0M; * foreach (var depositWithdrawal in account.DepositsWithdrawals.Where(x => x.Time <= date)) * { * netMoneyIn += CryptoValueHelper.GetAssetUsdValue(candlesService, broker, depositWithdrawal.Asset, depositWithdrawal.Time, depositWithdrawal.Amount); * } * * ret.Add((date, netMoneyIn)); * }*/ return(ret); }
public static List <(DateTime Time, decimal Value)> GetDailyTotalValues(IBroker broker, BrokerAccount account, IBrokersCandlesService candlesService) { var ret = new List <(DateTime Time, decimal Value)>(); /*var now = DateTime.UtcNow; * * for (var date = new DateTime(2018, 1, 1); date <= now; date = date.AddDays(1)) * { * var assetBalances = account.GetAssetBalances(broker, candlesService, date); * * if (date == now) * { * } * * // Convert to USDs * var value = 0.0M; * foreach (var assetBalance in assetBalances) * { * value += CryptoValueHelper.GetAssetUsdValue(candlesService, broker, assetBalance.Asset, date, assetBalance.Amount); * } * * ret.Add((date, value)); * }*/ return(ret); }
/// <summary> /// Gets the calculated funds. /// </summary> /// <param name="quantfund">The quantfund.</param> /// <param name="account">Current account object</param> /// <returns></returns> public CalculatedFunds GetCalculatedFunds(IQuantFund quantfund, BrokerAccount account) => new CalculatedFunds(GetUnsettledCash(quantfund), GetCash(quantfund), BaseCurrency, quantfund.Positions, _leverage, account.PatternDayTradingHit, account.DayTradingOrdersLeft);
public void LoadAccount(BrokerAccount brokerAccount) { brokerAccounts.Add(brokerAccount.UserName, brokerAccount); }
/// <summary> /// Sends the position information messages. /// </summary> /// <param name="quantfunds">The quantfunds.</param> /// <param name="cashmanager"></param> /// <param name="brokeraccount"></param> public void SendPositionInformationMessages(IQuantFund[] quantfunds, CashManager cashmanager, BrokerAccount brokeraccount) { if (!IsRunning || !HasSubscribers) { return; } quantfunds.ForEach(x => x.Positions.ForEach(pos => Enqueue(PositionInfoMessage.Create(x.FundId, pos, x.Universe, cashmanager.GetCalculatedFunds(x, brokeraccount))))); }