internal InstrumentsHistoryStockDividend(IInstrument instrument, DateTime changeDate, short basisNominator, short basisDenominator) : base(instrument, changeDate) { this.basisNominator = basisNominator; this.basisNominator = basisDenominator; }
public string SignUpPerformer(string[] args) { try { List <string> arguments = args.ToList(); string performerName = arguments[0]; int performerAge = int.Parse(arguments[1]); arguments.RemoveAt(0); arguments.RemoveAt(0); List <IInstrument> performerInstruments = new List <IInstrument>(); IPerformer newPerformer = this.performerFactory.CreatePerformer(performerName, performerAge); for (int i = 0; i < arguments.Count; i++) { IInstrument newInstrument = this.instrumentFactory.CreateInstrument(arguments[i]); newPerformer.AddInstrument(newInstrument); } this.stage.AddPerformer(newPerformer); return($"Registered performer {performerName}"); } catch { // not by definition return("ERROR signign performer"); } }
public static void TrackInstrument(IInstrument instrument) { lock (SyncRoot) { Instruments.Add(new TrackedInstrument(instrument)); } }
public InstrumentProcessor(ITaskDispatcher taskDispatcher, IInstrument instrument) { _taskDispatcher = taskDispatcher; _instrument = instrument; _instrument.Finished += (sender, eventArgs) => _taskDispatcher.FinishedTask(((InstrumentEventArgs)eventArgs).Task); }
/// <summary> /// Constructor for creating a test FeeClient object /// </summary> /// <param name="account"></param> /// <param name="instrument"></param> /// <param name="side"></param> /// <param name="actiontype"></param> /// <param name="transactionDate"></param> /// <param name="issizebased"></param> /// <param name="orderValue"></param> /// <param name="amount"></param> /// <param name="price"></param> /// <param name="ordercurrency"></param> /// <param name="isValueInclComm"></param> public CommClient(IAccountTypeInternal account,IInstrument instrument, Side side, OrderActionTypes actiontype, DateTime transactionDate, bool issizebased, InstrumentSize orderValue, Money amount, Price price, ICurrency ordercurrency, bool isValueInclComm) { if (account == null) throw new ApplicationException("It is not possible to calculate the commission when the account is unknown."); if (instrument == null) throw new ApplicationException("It is not possible to calculate the commission when the instrument value is unknown."); this.account = account; this.instrument = instrument; this.Side = side; this.ActionType = actiontype; this.TransactionDate = transactionDate; this.IsSizeBased = issizebased; this.OriginalOrderType = issizebased ? BaseOrderTypes.SizeBased : BaseOrderTypes.AmountBased; this.Value = orderValue; this.amount = amount; this.Price = price; this.OrderCurrency = ordercurrency; this.IsValueInclComm = isValueInclComm; type = CommClientType.Test; }
public static Quote3Message CreateQuote3MessageByXML(string xml, IInstrument instr) { XmlDocument doc = new XmlDocument(); try { doc.LoadXml(xml); var bankRate = CreateBankRateByXml(doc); var orders = CreateOrdersByXML(doc.GetElementsByTagName(WMEXCHANGERQUERYS)[0].ChildNodes, instr); if (bankRate == BankRate.Empty || orders.Count == 0) { return(null); } Quote3Message mess = new Quote3Message(bankRate.Direction, bankRate, orders) { QuoteSource = QuoteSource.XML.ToString() }; return(mess); } catch (Exception) { return(null); } }
public string SignUpPerformer(string[] args) { string performerName = args[0]; int performerAge = int.Parse(args[1]); List <string> stringInstruments = args.Skip(2).ToList(); List <IInstrument> performerInstrumentsToAdd = new List <IInstrument>(); foreach (var instrument in stringInstruments) { IInstrument currentInstrumentToAdd = this.instrumentFactory.CreateInstrument(instrument); performerInstrumentsToAdd.Add(currentInstrumentToAdd); } IPerformer performer = this.performerFactory.CreatePerformer(performerName, performerAge); foreach (var addInstrument in performerInstrumentsToAdd) { performer.AddInstrument(addInstrument); } this.stage.AddPerformer(performer); return(string.Format(Constants.SignUpPerformerSuccessMessage, performerName)); }
public void PrepareCache(IInstrument instrument, DateTime startTime, DateTime endTime, MarketDataGrade grade) { var cl = Cache.FirstOrDefault(v => v.Ticker == instrument.Ticker && v.StartTime <= startTime && v.EndTime >= endTime); if (cl != null) { return; } else { if (Cache.Count >= CacheSize) { Cache.RemoveAt(0); } var start = startTime; var end = endTime; if (CacheStartTime != null) { start = CacheStartTime.Value; } if (CacheEndTime != null) { end = CacheEndTime.Value; } var l = GetSourceDataList(instrument, start, end); Cache.Add(new MarketDataCacke() { DataList = l, StartTime = start, EndTime = end, Ticker = instrument.Ticker }); } }
public Tone(double pFrom, double pTo, int pKeyNumber, IInstrument pInstrument) { FromTime = pFrom; ToTime = pTo; KeyNumber = pKeyNumber; Instrument = pInstrument; }
/// <summary> /// Creates the device register set (typed registers). /// Note that the BAR and offset can be specified by the caller so the same RegisterSet /// class can be used to define multiple unique RegisterSet instances (different offset /// and or BAR). /// </summary> /// <param name="manager">the IRegManager instance to add this RegisterSet to</param> /// <param name="instrument">the IInstrument instance these registers are for</param> /// <param name="groupName">the group name used to access this RegisterSet from IRegManager</param> /// <param name="registerSetOffset">an offset added to all register offsets</param> /// <param name="barIndex">the BAR to use</param> public SoftwareLatchesRegisterSet(IRegManager manager, IInstrument module, string groupName, int registerSetOffset, int barIndex) { // Create the factory RegFactory regFactory = new RegFactory(registerSetOffset, module, SimulatedReg.ConstructReg); // Determine which IRegDriver (determines default BAR) IRegDriver regDriver = (barIndex >= module.RegDrivers.Length) ? null : module.RegDrivers[barIndex]; if (regDriver == null) { throw new InternalApplicationException("SoftwareLatchesRegisterSet requires RegDriver for BAR" + barIndex); } // Create the register definitions Registers = regFactory.CreateRegArray( mRegisterDefinitions, typeof(SoftwareLatchesRegister), regDriver, module.Name); regFactory.CreateBitFields(mBitFieldDefinitions, Registers, module.Name, string.Empty); if (manager != null) { // Adding as a group creates an IDirtyBit and attaches to each register manager.AddGroup(groupName, this); } LatchOne = new Reg64T <LatchOneBF>((SimulatedReg)Registers[(Int32)SoftwareLatchesRegister.LatchOne]); TxSwLatch1 = new Reg64T <TxSwLatch1BF>((SimulatedReg)Registers[(Int32)SoftwareLatchesRegister.TxSwLatch1]); RxSwLatch1 = new Reg64T <RxSwLatch1BF>((SimulatedReg)Registers[(Int32)SoftwareLatchesRegister.RxSwLatch1]); }
private void RefreshInstruments(IInstrument selectedInstrument = null, ITuning selectedTuning = null) { Instruments = AppVM.GetInstruments(); SelectedInstrument = null; if (null != selectedInstrument && null != Instruments) { foreach (ObservableInstrument oi in Instruments) { if (oi.Instrument == selectedInstrument) { SelectedInstrument = oi; break; } } } if (null != SelectedInstrument) { Tunings = SelectedInstrument.GetTunings(); SelectedTuning = null; if (null != selectedTuning && null != Tunings) { foreach (ObservableTuning ot in Tunings) { if (ot.Tuning == selectedTuning) { SelectedTuning = ot; break; } } } } }
public InstrumentProcessor(ITaskDispatcher taskDispatcher, IInstrument instrument) { this.taskDispatcher = taskDispatcher; this.instrument = instrument; instrument.Error += InstrumentOnError; instrument.Finished += InstrumentOnFinished; }
/// <summary> /// Creates the device register set (typed registers). /// Note that the BAR and offset can be specified by the caller so the same RegisterSet /// class can be used to define multiple unique RegisterSet instances (different offset /// and or BAR). /// </summary> /// <param name="manager">the IRegManager instance to add this RegisterSet to</param> /// <param name="instrument">the IInstrument instance these registers are for</param> /// <param name="groupName">the group name used to access this RegisterSet from IRegManager</param> /// <param name="registerSetOffset">an offset added to all register offsets</param> /// <param name="barIndex">the BAR to use</param> public ReceiverRegisterSet(IRegManager manager, IInstrument module, string groupName, int registerSetOffset, int barIndex) { // Create the factory RegFactory regFactory = new RegFactory(registerSetOffset, module, Reg32.ConstructReg); // Determine which IRegDriver (determines default BAR) IRegDriver regDriver = (barIndex >= module.RegDrivers.Length) ? null : module.RegDrivers[barIndex]; if (regDriver == null) { throw new InternalApplicationException("ReceiverRegisterSet requires RegDriver for BAR" + barIndex); } // Create the register definitions Registers = regFactory.CreateRegArray( mRegisterDefinitions, typeof(ReceiverRegister), regDriver, module.Name); regFactory.CreateBitFields(mBitFieldDefinitions, Registers, module.Name, string.Empty); if (manager != null) { // Adding as a group creates an IDirtyBit and attaches to each register manager.AddGroup(groupName, this); } SoftwareFpgaReset = new Reg32T <SoftwareFpgaResetBF>((Reg32)Registers[(Int32)ReceiverRegister.SoftwareFpgaReset]); RfStatus = new Reg32T <RfStatusBF>((Reg32)Registers[(Int32)ReceiverRegister.RfStatus]); FpgaVersion = new Reg32T <FpgaVersionBF>((Reg32)Registers[(Int32)ReceiverRegister.FpgaVersion]); Reserved = new Reg32T <ReservedBF>((Reg32)Registers[(Int32)ReceiverRegister.Reserved]); RfControl1 = new Reg32T <RfControl1BF>((Reg32)Registers[(Int32)ReceiverRegister.RfControl1]); RfControl2 = new Reg32T <RfControl2BF>((Reg32)Registers[(Int32)ReceiverRegister.RfControl2]); RfControl3 = new Reg32T <RfControl3BF>((Reg32)Registers[(Int32)ReceiverRegister.RfControl3]); }
/// <summary> /// Adds a new instrument to the catalogue. /// If the instrument - uniquely identified by its Symbol property - already exists in the collection, /// an exception will be thrown. /// </summary> /// <param name="instrument">Reference to instrument implementing IInstrumentDefinition</param> /// <returns></returns> public static void Add(IInstrument instrument) { lock (_catalogue) { _catalogue.Add(instrument.Symbol, instrument); // Can throw } }
public void Craft(IPresent present, IDwarf dwarf) { IInstrument instrument = null; while (dwarf.Energy > 0 && dwarf.Instruments.Any(x => x.Power > 0)) { instrument = dwarf.Instruments.FirstOrDefault(x => x.Power > 0); while (!present.IsDone() && dwarf.Energy > 0 && !instrument.IsBroken()) { dwarf.Work(); instrument.Use(); present.GetCrafted(); } if (instrument.IsBroken()) { dwarf.Instruments.Remove(instrument); } if (present.IsDone()) { break; } } }
public void AddInstrument(IInstrument instrument) { if (instrument != null) { _instruments[instrument.InstrumentName] = instrument; } }
public List <IMarketData> GetDataList(IInstrument instrument, DateTime startTime, DateTime endTime, MarketDataGrade grade) { var cl = Cache.FirstOrDefault(v => v.Ticker == instrument.Ticker && v.StartTime <= startTime && v.EndTime >= endTime); if (cl != null) { return(MarketData.SummaryMarketDataList(cl.DataList.Where(v => v.Time > startTime && v.Time <= endTime).ToList(), grade)); } else { if (Cache.Count >= CacheSize) { Cache.RemoveAt(0); } var start = startTime; var end = endTime; if (CacheStartTime != null) { start = CacheStartTime.Value; } if (CacheEndTime != null) { end = CacheEndTime.Value; } var l = GetSourceDataList(instrument, start, end); Cache.Add(new MarketDataCacke() { DataList = l, StartTime = start, EndTime = end, Ticker = instrument.Ticker }); return(MarketData.SummaryMarketDataList(l.Where(v => v.Time > startTime && v.Time <= endTime).ToList(), grade)); } }
public void Craft(IPresent present, IDwarf dwarf) { while (dwarf.Energy > 0 && dwarf.Instruments.Any()) // итерираме между инструментите { IInstrument currInstrument = dwarf.Instruments.First(); while (!present.IsDone() && dwarf.Energy > 0 && !currInstrument.IsBroken()) // правим подаръка { dwarf.Work(); // намаляме енергията present.GetCrafted(); // намаляме необходимото за правенето на подаръка currInstrument.Use(); // намаляме здравето на инструмента } if (currInstrument.IsBroken()) //ако заедно с направата на подарък се е счупил и инструмента !!!! { dwarf.Instruments.Remove(currInstrument); } if (present.IsDone()) //подаръка е готов и излизаме { break; } } }
public ShortTickStream(IInstrument instrument) { _tickSize = instrument.MinPriceIncrement; _minQtyIncrement = instrument.MinQtyIncrement; _sequence = new Sequence <byte>(ArrayPool <byte> .Shared); Instrument = instrument; }
/// <summary> /// I'm aware that by default, new threads are created as foreground threads, and that this thread _could_ /// have been set to be a background thread (in which case, it'd be stopped as soon as the main thread stopped.) /// I've intentionally left it as a foreground thread, to force me to programatically shut it down. /// /// </summary> public static void Run() { // This thread randomly changes instrument prices over time. // Each time there is a change, we need to notify attached clients too. var rand = new Random(); do { // Random delay between 100ms and 500ms int delay = rand.Next(100, 500); Thread.Sleep(delay); // Followed by change of price of some instrument int instrumentIndex = rand.Next(0, InstrumentCatalogue.Count); string key = InstrumentCatalogue.SymbolFromIndex(instrumentIndex); // We'll do a change between 0.05% and 0.005% decimal delta = rand.Next(5, 50) / 10000.0m; IInstrument inst = InstrumentCatalogue.Find(key); bool increase = rand.Next(1000) >= 500; decimal ask = increase ? inst.CurrentAskPrice * (1.0m + delta) : inst.CurrentAskPrice * (1.0m - delta); decimal bid = increase ? inst.CurrentBidPrice * (1.0m + delta) : inst.CurrentBidPrice * (1.0m - delta); Debug.WriteLine("Price update for {0}, Ask: {1}, Bid: {2}", key, ask, bid); inst.UpdatePricing(bid, ask, DateTime.Now); } while (_keepGoing); _waitHandle.Set(); }
private static List <Order> CreateOrdersByXMLPage(IInstrument instr, string xmlPage) { if (instr == null || string.IsNullOrEmpty(xmlPage)) { return(null); } xmlPage = xmlPage.Trim(); var tempBankRate = xmlPage.Split(BankRateSeparators, StringSplitOptions.RemoveEmptyEntries); var stringBankRate = tempBankRate[1].Split(BankRatePointSeparators, StringSplitOptions.RemoveEmptyEntries)[1]; double.TryParse(stringBankRate, out double bankRate); instr.BankRate = bankRate; var orderLines = xmlPage.Split(OrderXMLSepatators, StringSplitOptions.RemoveEmptyEntries); var orders = new List <Order>(); for (int i = 1; i < orderLines.Length; i++) { var order = CreateOrderByXMLLine(instr, orderLines[i]); if (order == null) { continue; } orders.Add(order); } return(orders); }
public string SignUpPerformer(string[] args) { var name = args[0]; var age = int.Parse(args[1]); var performer = this.performerFactory.CreatePerformer(name, age); IInstrument[] instruments = new IInstrument[args.Length - 2]; if (args.Length > 2) { var instrumentTypes = args.Skip(2).ToArray(); instruments = instrumentTypes .Select(i => this.instrumentFactory.CreateInstrument(i)) .ToArray(); } foreach (var instrument in instruments) { performer.AddInstrument(instrument); } this.stage.AddPerformer(performer); return($"Registered performer {performer.Name}"); }
public SettlementSession(IInstrument instrument, DateStamp sessionDate) { if (instrument is null) { throw new ArgumentNullException(nameof(instrument)); } if (instrument.SettlementTime.TimeOfDay.TotalHours <= 0) { throw new ArgumentException("Settlement time of day with zero or negative time is not supported."); } if (instrument.SettlementTime.TimeOfDay.TotalHours > 24) { throw new ArgumentException("Settlement time of day in early morning of following day is not yet supported."); } if (!instrument.IsTradingDay(sessionDate)) { throw new ArgumentException($"Unexpected sessionDate '{sessionDate}'. It should not be a valid trading day."); } Instrument = instrument; SessionDate = sessionDate; SessionEnd = new TimeStamp(SessionDate, instrument.SettlementTime.TimeOfDay, TimeZone); var sessionStartDate = Instrument.ThisOrPreviousTradingDay(SessionDate.AddDays(-1)); SessionStart = new TimeStamp(sessionStartDate, instrument.SettlementTime.TimeOfDay, TimeZone); }
public IInstrument CreateInstrument(string type) { Type typeOfInstrument = Assembly.GetCallingAssembly().GetTypes().First(t => t.Name == type); IInstrument instrument = (IInstrument)Activator.CreateInstance(typeOfInstrument); return(instrument); }
public List <Order> GetLevel2Async(IInstrument instrument, int sourceType = 0) { if (sourceType < 0 || sourceType > 2) { return(null); } string webPage; string XMLPage; switch ((SourceType)sourceType) { case SourceType.Web: webPage = _webmoneyClient.GetLevel2Page(instrument, PageType.Web).Result; return(WebmoneyHelper.CreateOrdersByPage(instrument, webPage, PageType.Web)); case SourceType.XML: XMLPage = _webmoneyClient.GetLevel2Page(instrument, PageType.XML).Result; return(WebmoneyHelper.CreateOrdersByPage(instrument, XMLPage, PageType.XML)); case SourceType.Mix: webPage = _webmoneyClient.GetLevel2Page(instrument, PageType.Web).Result; XMLPage = _webmoneyClient.GetLevel2Page(instrument, PageType.XML).Result; var webOrders = WebmoneyHelper.CreateOrdersByPage(instrument, webPage, PageType.Web); var XMLOrders = WebmoneyHelper.CreateOrdersByPage(instrument, XMLPage, PageType.XML); return(WebmoneyHelper.CombineOrders(instrument, webOrders, XMLOrders)); } return(null); }
public bool Delete(IInstrument entity) { return(mapperHelper.Delete(entity, (cmd, ins) => DeleteParameters(cmd, ins), "delete from Instrument where isin=@id" )); }
internal ICollection <IDailyReg> LoadDailyRegs(IInstrument i) { List <IDailyReg> lst = new List <IDailyReg>(); DailyRegMapper drm = new DailyRegMapper(mapperHelper.context); List <IDataParameter> parameters = new List <IDataParameter>(); parameters.Add(new SqlParameter("@id", i.isin)); using (IDataReader rd = mapperHelper.ExecuteReader("select isin,minval ,openingval, maxval,closingval, dailydate from DailyReg where isin=@id", parameters)) { while (rd.Read()) { DailyReg dr = new DailyReg { isin = rd.IsDBNull(0) ? default : rd.GetString(0), minval = rd.IsDBNull(1) ? default : rd.GetDecimal(1), openingval = rd.IsDBNull(2) ? default : rd.GetDecimal(2), maxval = rd.IsDBNull(3) ? default : rd.GetDecimal(3), closingval = rd.IsDBNull(4) ? default : rd.GetDecimal(4), dailydate = rd.IsDBNull(5) ? default : rd.GetDateTime(5), instrument = i }; lst.Add(dr); } } return(lst); }
/// <summary> /// Initializes a new instance of the <see cref="T:B4F.TotalGiro.Instruments.Price">Price</see> class. /// </summary> /// <param name="money">This is the amount that one particular instrument to which the price belongs would cost</param> /// <param name="instrument">The instrument to which the price belongs</param> public Price(Money money, IInstrument instrument) { this.quantity = money.Quantity; this.underlying = (ICurrency)money.Underlying; this.instrument = instrument; this.XRate = money.XRate; }
public bool Update(IInstrument entity) { return(mapperHelper.Update(entity, (cmd, ins) => UpdateParameters(cmd, ins), "update Instrument set description = @desc, mrktcode = @code where isin=@id" )); }
public static void TrackInstrument(IInstrument instrument) { lock(SyncRoot) { Instruments.Add(new TrackedInstrument(instrument)); } }
/// <summary> /// Initializes a new instance of the <see cref="T:B4F.TotalGiro.Instruments.Price">Price</see> class. /// </summary> /// <param name="quantity">The quantity (just a number) of the price</param> /// <param name="underlying">The currency the price is in</param> /// <param name="instrument">The instrument to which the price belongs</param> /// <param name="xRate">The xRate involved</param> public Price(Decimal quantity, ICurrency underlying, IInstrument instrument, decimal xRate) { this.quantity = quantity; this.underlying = underlying; this.instrument = instrument; this.xRate = xRate; }
public IInstrument GetInstrument() { string name = Settings[Prefix + "instrument"]; string level = InstrumentTuningLevel; if (null != _cachedInstrument) { if (_cachedInstrument.Name == name && _cachedInstrument.Level == level) { return(_cachedInstrument); } _cachedInstrument = null; _cachedTuning = null; } InstrumentSet instruments = _configFile.Instruments; while (null != instruments) { if (instruments.Level == level) { if (instruments.TryGet(name, out Instrument i)) { _cachedInstrument = i; break; } } instruments = instruments.Parent; } return(_cachedInstrument); }
public override void GenerateResult(IInstrument instruemnt, DateTime startTime, DateTime endTime, MarketDataGrade?grade) { var source = GetInstrumentList(); if (IsSelectBetterThanAverage) { average = source.Where(v => v.PE > 0).Average(v => v.PE); if (instruemnt.PE > average) { AddSignal(instruemnt, endTime, instruemnt.PE, instruemnt.CurrentPrice); } } else { if (instruemnt.PE < PELimit && instruemnt.PB < PBLimit) { if (IsSelectBetterPE) { AddSignal(instruemnt, endTime, instruemnt.PE, instruemnt.CurrentPrice); } else { AddSignal(instruemnt, endTime, instruemnt.PB, instruemnt.CurrentPrice); } } } }
public string SignUpPerformer(string[] args) { string performerName = args[0]; int performerAge = int.Parse(args[1]); string[] instumentNames = args.Skip(2).ToArray(); IList <IInstrument> instruments = new List <IInstrument>(); if (instumentNames.Length > 0) { foreach (var instumentName in instumentNames) { IInstrument instrument = this.instrumentFactory.CreateInstrument(instumentName); instruments.Add(instrument); } } IPerformer performer = new Performer(performerName, performerAge); foreach (var instr in instruments) { performer.AddInstrument(instr); } this.stage.AddPerformer(performer); return($"Registered performer {performerName}"); }
public void InstrumentsWearTest() { ISet set = new Short("Set1"); this.stage.AddSet(set); ISong song = new Song("Song1", new System.TimeSpan(0, 5, 0)); this.stage.AddSong(song); set.AddSong(song); IPerformer performer = new Performer("Gosho", 20); performer.AddInstrument(new Guitar()); this.stage.AddPerformer(performer); set.AddPerformer(performer); this.setController.PerformSets(); FieldInfo instrumentsInfo = typeof(Performer).GetFields(BindingFlags.NonPublic | BindingFlags.Instance) .First(f => f.FieldType == typeof(List <IInstrument>)); List <IInstrument> instruments = ((List <IInstrument>)instrumentsInfo.GetValue(performer)).Take(1).ToList(); IInstrument instrument = instruments[0]; Assert.That(instrument.Wear, Is.EqualTo(40)); }
public PortfolioComponentView(IInstrument instrument, decimal modelAllocation, PortfolioComponentView parent) : this(parent) { PortfolioComponentType = PortfolioComponentType.Instrument; ComponentKey = instrument.Key; ComponentName = instrument.DisplayName; ModelAllocation = modelAllocation; }
/// <summary> /// Get InstrumentHistory object by ID /// </summary> /// <param name="session">Data access object</param> /// <param name="oldInstrument">The instrument that has been changed</param> /// <returns>InstrumentHistory object</returns> public static IInstrumentHistory GetInstrumentHistory(IDalSession session, IInstrument instrument) { IList list = GetInstrumentHistoryList(session, instrument); if (list != null && list.Count == 1) return (IInstrumentHistory)list[0]; else return null; }
public static List<IFundPosition> GetPositions(IDalSession session, IInstrument instrument, PositionsView view) { List<ICriterion> expressions = new List<ICriterion>(); expressions.Add(Expression.Eq("Size.Underlying.Key", instrument.Key)); addPositionsViewCriterion(expressions, view); LoginMapper.GetSecurityInfo(session, expressions, SecurityInfoOptions.NoFilter); return session.GetTypedList<FundPosition, IFundPosition>(expressions); }
/// <summary> /// Initializes a new instance of the <see cref="T:B4F.TotalGiro.Instruments.InstrumentSize">InstrumentSize</see> class based upon a size and an instrument. /// </summary> /// <param name="quantity">The quantity of the instrument</param> /// <param name="underlying">The instrument involved</param> public InstrumentSize(Decimal quantity, IInstrument underlying) { if (underlying == null) throw new ApplicationException("Underlying can not be null when creating an instrumentsize object"); this.quantity = Math.Round(quantity, underlying.DecimalPlaces); this.underlying = underlying; }
public static void RemoveInstrument(IInstrument instrument) { lock(SyncRoot) { var trackedInstrument = Instruments.Single(a => a.Instrument == instrument); Instruments.Remove(trackedInstrument); } }
public AverageValuation(IValuation valuation, int period) { this.instrument = valuation.Instrument; this.avgMarketValue = valuation.MarketValue; this.avgBaseMarketValue = valuation.BaseMarketValue; this.period = period; weight = 1; }
private static ExtPosition findPos(IList positions, IInstrument instrument) { foreach (ExtPosition pos in positions) { if (pos.Size.Underlying.Equals(instrument)) return pos; } return null; }
/// <summary> /// Constructor /// </summary> /// <param name="account">User account</param> /// <param name="value">Initial value</param> /// <param name="tradedInstrument">Traded instrument</param> /// <param name="isValueInclComm">Is in the value the commission included?</param> /// <param name="feeFactory">Fee factory to use for calculating transaction costs</param> /// <param name="doNotChargeCommission">parameter that decides whether commission should be charged</param> /// <param name="actionType">The action type that created this order.</param> public OrderAmountBased(IAccountTypeInternal account, Money value, IInstrument tradedInstrument, bool isValueInclComm, IFeeFactory feeFactory, bool doNotChargeCommission, OrderActionTypes actionType) : base(account, value, (ITradeableInstrument)tradedInstrument, doNotChargeCommission) { this.ActionType = actionType; this.IsValueInclComm = isValueInclComm; checkInitialValues(); setCommission(feeFactory); // If same currency -> ExRate = 1 exRate = ((ICurrency)Value.Underlying).GetExRate(TradedInstrument.CurrencyNominal, this.Side); }
/// <summary> /// Initializes a new instance of the <see cref="T:B4F.TotalGiro.Instruments.InstrumentSize">InstrumentSize</see> class /// </summary> /// <param name="quantity">The quantity of the instrument</param> /// <param name="underlying">The instrument involved</param> /// <param name="noRounding">This argument takes care that the quantity is not rounded to the instrument's default number of decimal places</param> internal InstrumentSize(Decimal quantity, IInstrument underlying, bool noRounding) { if (underlying == null) throw new ApplicationException("Underlying can not be null when creating an instrumentsize object"); this.noRounding = noRounding; if (NoRounding) this.quantity = quantity; else this.quantity = Math.Round(quantity, underlying.DecimalPlaces); this.underlying = underlying; }
/// <summary> /// Gets the Position for the ExtCustodian and instrument for the specified date /// </summary> /// <param name="session">Data session object</param> /// <param name="custodian">The specified ExtCustodians</param> /// <param name="instrument">The specified Instrument</param> /// <param name="balanceDate">The specified date</param> /// <returns>An ExtCustodian Position</returns> public static ExtPosition GetExtCustodianPosition(IDalSession session, ExtCustodian custodian, IInstrument instrument, DateTime balanceDate) { ExtPosition pos = null; List<NHibernate.Criterion.ICriterion> expressions = new List<NHibernate.Criterion.ICriterion>(); expressions.Add(NHibernate.Criterion.Expression.Eq("Custodian.Key", custodian.Key)); expressions.Add(NHibernate.Criterion.Expression.Eq("Size.Underlying.Key", instrument.Key)); expressions.Add(NHibernate.Criterion.Expression.Eq("BalanceDate", balanceDate)); IList list = session.GetList(typeof(ExtPosition), expressions); if (list != null && list.Count == 1) pos = (ExtPosition)list[0]; return pos; }
public InstrumentProcessor(IInstrument instrument, ITaskDispatcher taskDispatcher, IConsole console) { this.instrument = instrument; this.taskDispatcher = taskDispatcher; this.console = console; this.instrument.Finished += (sender, args) => { this.taskDispatcher.FinishedTask(currentTasks.Dequeue()); }; this.instrument.Error += (sender, args) => { this.console.WriteLine(currentTasks.Dequeue()); }; }
/// <summary> /// Uses specified logging function /// Please ensure your logging function appends new lines /// </summary> /// <param name="baseInstrument">Base instrument to decorate</param> /// <param name="loggingFunction">The logging function</param> public LoggingInstrument(IInstrument baseInstrument, Action<string> loggingFunction) { if (baseInstrument == null) { throw new ArgumentNullException("baseInstrument"); } if (loggingFunction == null) { throw new ArgumentNullException("loggingFunction"); } _BaseInstrument = baseInstrument; _LoggingFunction = loggingFunction; this._ID = _Counter; _Counter++; }
/// <summary> /// Net position amount /// </summary> public decimal GetTotalAmount(Account account, IInstrument instrument) { //here should be something like SQL request to database, I simulated it by LINQ request. //Keeping Position objects is more efficient solution, but I avoided it for simplicity lock (Fills) { //find the average price of all transactions and multiply that by the sum of all orders var selectedOrders = FilledOrders.Where(order => order.Account == account && order.Instrument == instrument).ToList(); if (selectedOrders.Count == 0) return 0; //this monster code finds all trades by order and calculates average price. //it doesn't effectice, just an example, for the test project return selectedOrders.Average(order => Fills.Where(f => f.Initiator == order).Sum(f => f.Gross) / Fills.Where(f => f.Initiator == order).Sum(f => (decimal)f.Amount)) * selectedOrders.Sum(order => (decimal)(order.Side == Operation.Buy ? order.Amount : -order.Amount)); } }
public static InstrumentSize Sum(this IEnumerable<InstrumentSize> source, IInstrument defaultInstrument) { if (source.Count() == 1 && source.FirstOrDefault() == null) return null; else if (source.Count() > 0 && source.FirstOrDefault() != null) { //var instruments = from values in source group values by values.Underlying.Key into g select g.Key; var instruments = source. GroupBy(x => x.Underlying.Key) .Select(g => g.FirstOrDefault().Underlying); if (instruments.Count() == 1) return new InstrumentSize(source.Sum(m => m.Quantity), (IInstrument)instruments.ElementAt(0)); else throw new ApplicationException("Cannot sum more than one Instrument."); } else return new InstrumentSize(0m, defaultInstrument); }
public CommRuleSpecific(OrderActionTypes actionType, bool applyToAllAccounts, IAccountType accountType, IModel modelPortfolio, IAccount account, IInstrument instrument, ISecCategory ruleSecCategory, IExchange exchange, string commRuleName, FeeTypes feeType, CommRuleOpenClose openClose, CommRuleBuySell buySell, Fees.Calculations.CommCalc commCalculation) : base(commRuleName, feeType, commCalculation) { this.actionType = actionType; this.ApplyToAllAccounts = applyToAllAccounts; this.AccountType = accountType; this.ModelPortfolio = modelPortfolio; this.Account = account; this.Instrument = instrument; this.RuleSecCategory = ruleSecCategory; this.Exchange = exchange; this.OpenClose = openClose; this.BuySell = buySell; }
public InstrumentsHistoryConversion(IInstrument oldInstrument, IInstrument newInstrument, DateTime changeDate, decimal oldChildRatio, byte newParentRatio, bool isSpinOff) : base(oldInstrument, changeDate) { if (oldInstrument.ParentInstrument != null) throw new ApplicationException(string.Format("This instrument {0} already has a parent: {1}", oldInstrument.DisplayNameWithIsin, oldInstrument.ParentInstrument.DisplayIsinWithName)); if (newInstrument == null) throw new ApplicationException("newInstrument can not be null"); if (oldChildRatio <= 0 || newParentRatio <= 0) throw new ApplicationException("Both ratios have to be greater than zero"); NewInstrument = newInstrument; OldChildRatio = oldChildRatio; NewParentRatio = newParentRatio; IsSpinOff = isSpinOff; }
protected override void StartCalc() { Data2 = BarsOfData(2); 當沖出場時間 = 132955; 前次PositionSide = EMarketPositionSide.Flat; // 啟用當沖時,若停單時間比 13:30 晚,就提前至 13:30 if (濾網_啟用當沖 == 1) { 濾網_停單時間 = Math.Min(濾網_停單時間, 當沖出場時間); } // 建立結算日資料集合,結算當日強制於當沖出場時間平倉 string 結算日檔案路徑 = 設定_資料檔目錄 + "ExpireDate.TW.csv"; 結算日集合.Clear(); if (File.Exists(結算日檔案路徑)) { string[] 結算日陣列 = File.ReadAllLines(結算日檔案路徑); for (int i = 0; i < 結算日陣列.Length; i++) { 結算日集合.Add(DateTime.ParseExact(結算日陣列[i], "yyyy/MM/dd", CultureInfo.InvariantCulture), true); } } // 建立順勢/逆勢進場週間日集合,只有允許週間日才能進場 順勢進場週間日集合.Clear(); 逆勢進場週間日集合.Clear(); string[] 順勢進場週間日陣列 = 順勢進場週間日.Split(new char[] { ',' }); string[] 逆勢進場週間日陣列 = 逆勢進場週間日.Split(new char[] { ',' }); for (int i = 0; i <= 6; i++) { bool 啟用 = 順勢進場週間日陣列.Count(x => x == i.ToString()) > 0; 順勢進場週間日集合.Add((DayOfWeek)i, 啟用); 啟用 = 逆勢進場週間日陣列.Count(x => x == i.ToString()) > 0; 逆勢進場週間日集合.Add((DayOfWeek)i, 啟用); } // 建立結算隔日進場集合,只有允許月份才能進場 結算隔日進場月份集合.Clear(); string[] 結算隔日進場月份陣列 = 結算隔日進場月份.Split(new char[] { ',' }); for (int i = 1; i <= 12; i++) { bool 啟用 = 結算隔日進場月份陣列.Count(x => x == i.ToString()) > 0; 結算隔日進場月份集合.Add(i, 啟用); } // 計算停損金額在不同商品間換算出的停損點數,如 $3,000 在台指期的停損點數為 15 點 double 每跳動點價值 = Bars.Info.MinMove / Bars.Info.PriceScale * Bars.Info.BigPointValue; if (加減碼_停損金額 > 0) { 停損點數 = 加減碼_停損金額 / 每跳動點價值; } if (加減碼_停損金額 == -1) { //預設15點 停損點數 = 15; // 固定15點 加減碼_停損金額 = (int)(停損點數 * 每跳動點價值); } 設定_輸出集合 = null; 重算日期 = 0; }
private IList<IFundPosition> getPositionsConvertedInstrument(IInstrument instrument, IFundPortfolio portfolio) { IList<IFundPosition> positions = null; if (portfolio != null) { foreach (IFundPosition pos in portfolio) { if (pos.InstrumentOfPosition.ParentInstrument != null && pos.InstrumentOfPosition.ParentInstrument.Equals(instrument)) { if (positions == null) positions = new List<IFundPosition>(); positions.Add(pos); } } } return positions; }
private Price findRelevantPrice(ref IList prices, IInstrument instrument, DateTime date) { foreach (IPriceDetail histPrice in prices) { if (histPrice.Date.Equals(date) && histPrice.Price.Instrument.Equals(instrument)) return histPrice.Price; } // Nothing found -> return zero price for Tradeable instrument // return 1 for currencies if (instrument.IsTradeable) return new Price(0M, ((ITradeableInstrument)instrument).CurrencyNominal, instrument); else return new Price(1M, (ICurrency)instrument, instrument); }
private ICurrency getCurrencyFromInstrument(IInstrument instrument) { if (instrument.IsCash) return instrument.ToCurrency; else return ((ITradeableInstrument)instrument).CurrencyNominal; }
private PositionComparer getPos(IInstrument instrument) { PositionComparer pc = null; pc = this[instrument.Key]; if (pc == null) { pc = new PositionComparer(instrument); positions.Add(instrument.Key, pc); } return pc; }
private PositionComparer findPos(IInstrument instrument) { return this[instrument.Key]; }
public TrackedInstrument(IInstrument instrument) { Instrument = instrument; InstrumentID = _instrumentId++; }
public ThreadSafeComms(IInstrument instrument) { _Instrument = instrument; Retries = 2; }
public InstrumentSymbol(IExternalInterface externalInterface, string externalSymbol, IInstrument instrument) : base(externalInterface, externalSymbol) { this.Instrument = instrument; }