public Alert EntryAlertCreate(Bar entryBar, double stopOrLimitPrice, string entrySignalName, Direction direction, MarketLimitStop entryMarketLimitStop) { this.checkThrowEntryBarIsValid(entryBar); double priceScriptOrStreaming = stopOrLimitPrice; OrderSpreadSide orderSpreadSide = OrderSpreadSide.Unknown; if (entryMarketLimitStop == MarketLimitStop.Market) { priceScriptOrStreaming = this.getStreamingPriceForMarketOrder(entryMarketLimitStop, direction, out orderSpreadSide); } PositionLongShort longShortFromDirection = MarketConverter.LongShortFromDirection(direction); // ALREADY_ALIGNED_AFTER GetAlignedBidOrAskForTidalOrCrossMarketFromStreaming double entryPriceScript = entryBar.ParentBars.SymbolInfo.RoundAlertPriceToPriceLevel( priceScriptOrStreaming, true, longShortFromDirection, entryMarketLimitStop); double shares = this.executor.PositionSizeCalculate(entryBar, entryPriceScript); Alert alert = new Alert(entryBar, shares, entryPriceScript, entrySignalName, direction, entryMarketLimitStop, orderSpreadSide, //this.executor.Script, this.executor.Strategy); alert.AbsorbFromExecutor(executor); return alert; }
private void checkThrowEntryBarIsValid(Bar entryBar) { // if (entryBar < this.executor.Bars.Count) { // string msg = "use MarketSim for Backtest! MarketRealTime is for entryBars >= this.executor.Bars.Count"; // throw new Exception(msg); // //this.executor.ThrowPopup(new Exception(msg)); // // } // // if (entryBar > this.executor.Bars.Count) { // string msg = "entryBar[" + entryBar + "] > Bars.Count[" + this.executor.Bars.Count + "]" // + " for [" + this.executor.Bars + "]" // + " Bars.StreamingBarSafeClone=[" + this.executor.Bars.StreamingBarCloneReadonly + "]" // + "; can't open any other position but on StreamingBar; positions postponed for tomorrow NYI"; // throw new Exception(msg); // //this.executor.ThrowPopup(new Exception(msg)); // } if (entryBar == null) { string msg = "entryBar == null"; throw new Exception(msg); } if (entryBar.ParentBars == null) { string msg = "entryBar.ParentBars == null"; throw new Exception(msg); } if (entryBar.ParentBars.SymbolInfo == null) { string msg = "entryBar.ParentBars.SymbolInfo == null"; throw new Exception(msg); } }
public Alert ExitAlertCreate(Bar exitBar, Position position, double stopOrLimitPrice, string signalName, Direction direction, MarketLimitStop exitMarketLimitStop) { this.checkThrowEntryBarIsValid(exitBar); this.checkThrowPositionToCloseIsValid(position); double priceScriptOrStreaming = stopOrLimitPrice; OrderSpreadSide orderSpreadSide = OrderSpreadSide.Unknown; if (exitMarketLimitStop == MarketLimitStop.Market) { priceScriptOrStreaming = this.getStreamingPriceForMarketOrder(exitMarketLimitStop, direction, out orderSpreadSide); } PositionLongShort longShortFromDirection = MarketConverter.LongShortFromDirection(direction); double exitPriceScript = exitBar.ParentBars.SymbolInfo.RoundAlertPriceToPriceLevel( priceScriptOrStreaming, true, longShortFromDirection, exitMarketLimitStop); Alert alert = new Alert(exitBar, position.Shares, exitPriceScript, signalName, direction, exitMarketLimitStop, orderSpreadSide, //this.executor.Script, this.executor.Strategy); alert.AbsorbFromExecutor(executor); alert.PositionAffected = position; // moved to CallbackAlertFilled - we can exit by TP or SL - and position has no clue which Alert was filled!!! //position.ExitCopyFromAlert(alert); alert.PositionAffected.ExitAlertAttach(alert); return alert; }
public void WillNotSerializeEvents() { IOExtensions.DeleteDirectory("Data"); try { using (var documentStore = new EmbeddableDocumentStore()) { documentStore.Configuration.DataDirectory = "Data"; documentStore.Conventions.CustomizeJsonSerializer = x => x.TypeNameHandling = TypeNameHandling.Auto; documentStore.Initialize(); var bar = new Bar(); var foo = new Foo(); foo.PropertyChanged += bar.FooChanged; using (var session = documentStore.OpenSession()) { session.Store(foo); session.SaveChanges(); } } } finally { IOExtensions.DeleteDirectory("Data"); } }
void LoadMusicData(string jsonText) { JsonData data = JsonMapper.ToObject(jsonText); JsonData bars = data["bars"]; _bars = new Bar[bars.Count]; for (int i = 0; i < bars.Count; i++) { _bars[i] = new Bar(confidence: (double)(bars[i]["confidence"]), start: (double)(bars[i]["start"]), duration: (double)(bars[i]["duration"])); } JsonData beats = data["beats"]; _beats = new Bar[beats.Count]; for (int i = 0; i < beats.Count; i++) { _beats[i] = new Bar(confidence: (double)(beats[i]["confidence"]), start: (double)(beats[i]["start"]), duration: (double)(beats[i]["duration"])); } JsonData tatums = data["tatums"]; _tatums = new Bar[tatums.Count]; for (int i = 0; i < tatums.Count; i++) { _tatums[i] = new Bar(confidence: (double)(tatums[i]["confidence"]), start: (double)(tatums[i]["start"]), duration: (double)(tatums[i]["duration"])); } JsonData segments = data["segments"]; _segments = new Bar[segments.Count]; for (int i = 0; i < segments.Count; i++) { _segments[i] = new Bar(confidence: (double)(segments[i]["confidence"]), start: (double)(segments[i]["start"]), duration: (double)(segments[i]["duration"])); } }
public void TestBarAsFoo() { Foo foo = new Bar { Value = 1 }; Foo clone = Serializer.DeepClone(foo); Assert.AreEqual(foo.Value, clone.Value); Assert.IsInstanceOfType(typeof(Bar), clone); }
static void RunTest (int expected) { IFoo a = (IFoo) new Bar (); Assert.AreEqual (expected, a.Execute (), "#A1"); Assert.AreEqual (expected, a.Count, "#A2"); Bar b = new Bar (); Assert.AreEqual (expected, b.Execute (), "#B1"); Assert.AreEqual (expected, b.Count, "#B2"); Foo c = new Foo (); Assert.AreEqual (1, c.Execute (), "#C1"); Assert.AreEqual (1, c.Count, "#C2"); Assert.AreEqual (expected, ((IFoo) new Bar ()).Execute (), "#D1"); Assert.AreEqual (expected, ((IFoo) new Bar ()).Count, "#D2"); Assert.AreEqual (1, new Bar ().Execute (), "#E1"); Assert.AreEqual (1, new Bar ().Count, "#E2"); Assert.AreEqual (1, new Foo ().Execute (), "#F1"); Assert.AreEqual (1, new Foo ().Count, "#F2"); Assert.AreEqual (expected, CreateBar ().Execute (), "#G1"); Assert.AreEqual (expected, CreateBar ().Count, "#G2"); }
private void OnBarSelection(Bar bar) { //reset value selectedBarSlider.ValueChanged -= OnValuesSliderValueChanged; selectedBarSlider.Value = bar.Value; selectedBarSlider.ValueChanged += OnValuesSliderValueChanged; }
public void ShouldWork() { using (var store = NewDocumentStore()) { store.Conventions.IdentityTypeConvertors.Add(new UInt32Converter()); using (var session = store.OpenSession()) { var foo = new Foo() { Id = uint.MaxValue }; foo.Related.Add(uint.MaxValue); session.Store(foo); var bar = new Bar { Id = uint.MaxValue }; session.Store(bar); session.SaveChanges(); } using (var session = store.OpenSession()) { var foo = session.Query<Foo>() .Customize(x=>x.WaitForNonStaleResults()) .ToList(); var bar = session.Query<Bar>().ToList(); //This line blows up var foobar = session.Query<Foo>().Include<Foo, Bar>(f => f.Related).ToList(); } } }
public override void OnBar(Bar bar) { // always a good practice to be sure a series contains // a bar for a particular date before you try to use it if (bbl.Contains(bar.DateTime)) { // We are always trying to buy at the lower Bollinger // limit, and sell when the price goes up to the // latest SMA value. So we are constantly // updating both the buy point and the sell point. // if we don't have an open position in this instrument, // update the buy point to the latest lower bbl limit if (!HasPosition) { if (buyOrder != null) buyOrder.Cancel(); buyOrder = BuyLimitOrder(Qty, bbl.Last, "Entry"); buyOrder.Send(); } // else if we already have a position going, update // the sell point to follow the latest SMA value else UpdateExitLimit(); } }
public void Add(Bar bar) { var barsWithInstrumentId = this.bars[bar.InstrumentId] = this.bars[bar.InstrumentId] ?? new IdArray<IdArray<BarSeries>>(8); var barsWithInstrumentIdAndType = barsWithInstrumentId[(int)bar.Type] = barsWithInstrumentId[(int)bar.Type] ?? new IdArray<BarSeries>(); var barsWithInstrumentIdAndTypeAndSize = barsWithInstrumentIdAndType[(int)bar.Size] = barsWithInstrumentIdAndType[(int)bar.Size] ?? new BarSeries("", "", -1, -1); barsWithInstrumentIdAndTypeAndSize.Add(bar); }
static void ProduceSimpleHeapWithLOS () { Console.WriteLine ("running in {0}", AppDomain.CurrentDomain); byte[] a = new byte [4 * 1000 * 1000]; byte[] b = new byte [4 * 1000 * 1000]; byte[] c = new byte [4 * 1000 * 1000]; var lst = new List<object> (); Bar la, lb, lc; la = lb = lc = null; for (int i = 0; i < 1000 * 200; ++i) { var ba = new Bar (); var bb = new Bar (); var bc = new Bar (); ba.a = la; ba.b = bb; ba.c = a; bb.a = bc; ba.b = b; bb.c = lb; bc.a = c; bc.b = lc; bc.c = ba; la = ba; lb = bb; lc = bc; lst.Add (ba); } }
/* 按照股指的时间要求,时间划分是这样的 9:15 9:45 10:15 10:45 11:15-11:30 13:00-13:15 两个15分钟被午休隔开了 13:45 14:15 14:45 15:15 交割日时只到15:00,已经到最后一天了,少15分钟也没什么 */ public override void OnBar(Bar bar) { //只处理15分钟的 if (900 == bar.Size) { if (bars == null) bars = new BarSeries(); bars.Add(bar); //在处理11:15-11:30 13:00-13:15这两个15分钟时会合并成一个 if (bars.Count == 2) // 2 * 15min = 30 min { // get OHLC values for 30min bar double open = bars[0].Open; double high = bars.HighestHigh(); double low = bars.LowestLow(); double close = bars[1].Close; long volume = bars[0].Volume + bars[1].Volume; // todo something Bar b = new Bar(bars[0].DateTime, open, high, low, close, volume, 900 * 2); bars30min.Add(b); Console.WriteLine(b); // reset 15min bar series bars = null; } } }
public override void OnBar(Bar bar) { // we need at least one bar to go by before we do anything if (prevClose != -1) { // if we don't have a position open, increment the count of down days (or reset it to zero) if (!HasPosition) { if (prevClose > bar.Close) count++; else count = 0; // if this is the fourth (consClosesCount is equal to 4 by default) down day, // issue a market order to open a long position tomorrow morning, on day 5 if (count == ConsClosesCount) Buy(Qty, "Entry"); } // else if we have a position open, close it now (today is the day after the trade was // entered), so now is actually end of day 6, and the trade will be executed by the market // on open day 7. else Sell(Qty, "Exit"); } // today's close now becomes the previous close for the down day calculation prevClose = bar.Close; }
/// <summary> /// Creates a new single-precision floating-point variable in a given bar. /// </summary> /// <param name="bar">The bar to create the floating-point variable in.</param> /// <param name="initialValue">The initial value of the variable.</param> /// <param name="def">An optional definition string for the new variable.</param> public FloatVariable(Bar bar, Single initialValue = 0, String def = null) : base(bar, InitFloatVariable, def) { Validating += (s, e) => { e.Valid = (Min <= e.Value) && (e.Value <= Max); }; ValidateAndSet(initialValue); }
public void CanSerializeWithEncryptRootObjectEnabled() { var encryptionMechanism = new Base64EncryptionMechanism(); var configuration = new JsonSerializerConfiguration { EncryptionMechanism = encryptionMechanism, EncryptRootObject = true }; var serializer = new JsonSerializer<Bar>(configuration); var instance = new Bar { Baz = new Baz { Qux = "abc", Garply = true }, Corge = 123.45 }; var json = serializer.Serialize(instance); var expected = @"""" + encryptionMechanism.Encrypt(@"{""Baz"":{""Qux"":""abc"",""Garply"":true},""Corge"":123.45}") + @""""; Assert.That(json, Is.EqualTo(expected)); }
public override void OnBar(Bar bar) { // good practice to check if a series has the date you are interested in before you try // to use it if (b.Contains(bar)) { // if we don't have a position and prices are below the lower band, open a long position if (!HasPosition) { if (b[bar.DateTime] * 100 <= BLevel) { buyOrder = BuyOrder(Qty, "Entry"); buyOrder.Send(); } } else { barsFromEntry++; // if we _have_ reached the exit day (4 days after entry), cancel the profit target // sell order, and issue a new market order to close the position now. if (barsFromEntry == MaxDuration) { barsFromEntry = 0; // cancel existing sell order if there is one if (sellOrder != null) sellOrder.Cancel(); Sell(Qty, "Exit (Max Duration)"); } } } }
public void BindOther() { var foo = new Foo("123"); var bar = new Bar(foo); AssertChange(foo, bar, x => x.FooDependentValue, () => foo.Value = "arbitrary"); }
public void InsertAndSingleSelect() { using (var store = NewRemoteDocumentStore(requestedStorage: "esent")) { var expected = new Bar { Id = "test/bar/1", Foo = "Some value" }; using (new TransactionScope()) { using (var session = store.OpenSession()) { session.Store(expected); session.SaveChanges(); } using (var session = store.OpenSession()) { var actual = session.Load<Bar>(expected.Id); Assert.Equal(expected.Id, actual.Id); Assert.Equal(expected.Foo, actual.Foo); } using (var session = store.OpenSession()) { var actualList = session.Load<Bar>(expected.Id, "i do not exist"); Assert.Equal(2, actualList.Length); Assert.NotNull(actualList[0]); Assert.Null(actualList[1]); Assert.Equal(expected.Id, actualList[0].Id); Assert.Equal(expected.Foo, actualList[0].Foo); } } } }
private void OnNewBar(object sender, BarEventArgs args) { if (NewBar != null) { CThostFtdcDepthMarketDataField DepthMarket; Instrument inst = InstrumentManager.Instruments[args.Instrument.Symbol]; string altSymbol = inst.GetSymbol(Name); Bar bar = args.Bar; if (_dictDepthMarketData.TryGetValue(altSymbol, out DepthMarket)) { bar = new Bar(args.Bar); bar.OpenInt = (long)DepthMarket.OpenInterest; } if (null != MarketDataFilter) { Bar b = MarketDataFilter.FilterBar(bar, args.Instrument.Symbol); if (null != b) { NewBar(this, new BarEventArgs(b, args.Instrument, this)); } } else { NewBar(this, new BarEventArgs(bar, args.Instrument, this)); } } }
public override void OnBarOpen(Bar bar) { // calc quantity to reverse a position double orderQty = 2 * Qty; if (!HasPosition) orderQty = Qty; if (positionInBlock == 0) { if (buyOnNewBlock) { Buy(orderQty, "Reverse to Long"); buyOnNewBlock = false; } if (sellOnNewBlock) { Sell(orderQty, "Reverse to Short"); sellOnNewBlock = false; } } }
/// <summary> /// Creates a new boolean variable in a given bar. /// </summary> /// <param name="bar">The bar to create the boolean variable in.</param> /// <param name="initialValue">The initial value of the variable.</param> /// <param name="def">An optional definition string for the new variable.</param> public BoolVariable(Bar bar, Boolean initialValue = false, String def = null) : base(bar, InitBoolVariable, def) { Validating += (s, e) => { e.Valid = true; }; ValidateAndSet(initialValue); }
public void Foo() { var bar = new Bar { List = new RxList<string>() }; bar.List.Add("foobar"); var json = JsonConvert.SerializeObject(bar); var deserializedBar = JsonConvert.DeserializeObject<Bar>(json); }
/// <summary> /// 构建插件单元 /// </summary> /// <param name="caller">调用者</param> /// <param name="context">上下文,用于存放在构建时需要的组件</param> /// <param name="element">插件单元</param> /// <param name="subItems">被构建的子对象列表</param> /// <returns>构建好的插件单元</returns> public object BuildItem(object caller, WorkItem context, AddInElement element, ArrayList subItems) { if (element.Configuration.Attributes["label"] == null) throw new AddInException(String.Format("没有为类型为 \"{0}\" 的插件单元{1}提供label属性。", element.ClassName, element.Id)); string label = element.Configuration.Attributes["label"]; BarManager barManager = context.Items.Get<BarManager>(UIExtensionSiteNames.Shell_Bar_Manager); if (barManager == null) throw new UniframeworkException("未定义框架外壳的工具条管理器。"); Bar item = new Bar(barManager, label); item.BarName = element.Name; item.DockStyle = BarDockStyle.Top; // 默认停靠在顶部 if (element.Configuration.Attributes["dockstyle"] != null) { string dockStyle = element.Configuration.Attributes["dockstyle"]; item.DockStyle = (BarDockStyle)Enum.Parse(typeof(BarDockStyle), dockStyle); } // 是否让工具栏显示整行 if (element.Configuration.Attributes["wholerow"] != null) item.OptionsBar.UseWholeRow = bool.Parse(element.Configuration.Attributes["wholerow"]); if (element.Configuration.Attributes["allowcustomization"] != null) item.OptionsBar.AllowQuickCustomization = bool.Parse(element.Configuration.Attributes["allowcustomization"]); if (element.Configuration.Attributes["register"] != null) { bool register = bool.Parse(element.Configuration.Attributes["register"]); if (register) context.UIExtensionSites.RegisterSite(BuilderUtility.CombinPath(element.Path, element.Id), item); // 此处可能抛出异常 } return item; }
public void Adapter(Bar barTarget) { m_BarItems = new List<BarItem>(); BandItemLinks2(barTarget.ItemLinks, ref m_BarItems); System.Windows.Forms.Application.Idle += new EventHandler(Application_Idle); }
public Aggregate(Service1 one, Service2 two, Foo foo, Bar bar) { this.one = one; this.two = two; this.foo = foo; this.bar = bar; }
void run() { Bar b = new Bar(); Foo f = b.create(); FooBar fb = new FooBar(); FooBar2 fb2 = new FooBar2(); String s; s = fb.used(); if ( s != ("Foo::pang();Bar::pong();Foo::pong();FooBar::ping();")) throw new Exception("bad FooBar::used" + " - " + s); s = fb2.used(); if ( s != ("FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();")) throw new Exception("bad FooBar2::used"); s = b.pong(); if ( s != ("Bar::pong();Foo::pong();Bar::ping();")) throw new Exception("bad Bar::pong"); s = f.pong(); if ( s != ("Bar::pong();Foo::pong();Bar::ping();")) throw new Exception("bad Foo::pong"); s = fb.pong(); if ( s != ("Bar::pong();Foo::pong();FooBar::ping();")) throw new Exception("bad FooBar::pong"); }
public override void OnBar(Bar bar) { if (bbl.Contains(bar.DateTime)) { if (!HasPosition) { // cancel previos buy limit if (buyLimit != null) buyLimit.Cancel(); // calculate limit price double buyPrice = bbl.Last * (1 - Percent / 100); // place new limit orders buyLimit = BuyLimitOrder(Qty, buyPrice, "Entry"); buyLimit.Send(); } else { barsFromEntry++; // close position at the second bar after entry if (barsFromEntry == 2) { barsFromEntry = 0; sellLimit.Cancel(); Sell(Qty, "Exit (Second Bar After Entry)"); } } } }
public override void OnBar(Bar bar) { // if we don't have a position and we have some bars // in the bollinger series, try to enter a new trade if (!HasPosition) { if (bbl.Count > 0) { // if the current bar is below the lower bollinger band // buy long to close the gap if (Bars.Crosses(bbl, bar) == Cross.Below) { buyOrder = MarketOrder(OrderSide.Buy, Qty, "Entry"); buyOrder.Send(); } } } else { // else if we DO have an existing position, and if // today's bar is above our entry price (profitable), // then close the position with a market order if (entryPrice < bar.Close) { barsFromEntry = 0; Sell(Qty, "Exit (Take Profit)"); } else barsFromEntry++; } }
/// <summary> /// Creates a new string variable in a given bar. /// </summary> /// <param name="bar">The bar to create the string variable in.</param> /// <param name="initialValue">The initial value of the variable.</param> /// <param name="def">An optional definition string for the new variable.</param> public StringVariable(Bar bar, String initialValue = "", String def = null) : base(bar, InitStringVariable, def) { Validating += (s, e) => { e.Valid = (e.Value != null); }; ValidateAndSet(initialValue); }
public override IEnumerable <Bar> Run(DateTime?startTime, DateTime?endTime) { //========== initialization ========== #if USE_BENSDORPS_RANGE // matching range in the book StartTime = SubclassedStartTime ?? DateTime.Parse("01/02/1995", CultureInfo.InvariantCulture); EndTime = SubclassedEndTime ?? DateTime.Parse("11/23/2016", CultureInfo.InvariantCulture); WarmupStartTime = StartTime - TimeSpan.FromDays(365); #else StartTime = startTime ?? Globals.START_TIME; EndTime = endTime ?? Globals.END_TIME; WarmupStartTime = Globals.WARMUP_START_TIME; #endif AddDataSources(UNIVERSE.Constituents); AddDataSource(BENCHMARK); Deposit(Globals.INITIAL_CAPITAL); CommissionPerShare = 0.015; var entryParameters = Enumerable.Empty <Instrument>() .ToDictionary( i => i, i => new { entryDate = default(DateTime), entryPrice = default(double), stopLoss = default(double), profitTarget = default(double), }); //========== simulation loop ========== foreach (var s in SimTimes) { //----- find instruments _benchmark = _benchmark ?? FindInstrument(BENCHMARK); var universe = Instruments .Where(i => i.IsConstituent(UNIVERSE)) #if false // we don't like to have these filter rules here. Instead, // this should be solved by proper universe selection .Where(i => i.Close[0] > 1.00 && i.Volume.ToDouble().SMA(50)[0] > 0.5e6 && i.Close.Multiply(i.Volume.ToDouble()).SMA(50)[0] > 2.5e6) #endif .ToList(); //----- calculate indicators // make sure to calculate indicators for all // known instruments, as they may enter the universe // at any time var indicators = Instruments .ToDictionary( i => i, i => new { sma150 = i.Close.SMA(SMA_DAYS), adx7 = i.ADX(7), atr10 = i.TrueRange().Divide(i.Close).SMA(10), rsi3 = i.Close.RSI(3), }); // filter universe to potential candidates var filtered = ENTRY_DIR > 0 ? (universe .Where(i => // - long - i.Close[0] > indicators[i].sma150[0] && // close above 150-day SMA indicators[i].adx7[0] > MIN_ADX && // 7-day ADX above 45 indicators[i].atr10[0] > MIN_ATR / 10000.0 && // 10-day ATR above 4% indicators[i].rsi3[0] < MINMAX_RSI) // 3-day RSI below 30 .ToList()) : (universe .Where(i => // - short - i.Close[0] > i.Close[1] && i.Close[1] > i.Close[2] && // 2 up-days indicators[i].adx7[0] > MIN_ADX && // 7-day ADX above 50 indicators[i].atr10[0] > MIN_ATR / 10000.0 && // 10-day ATR above 5% indicators[i].rsi3[0] > MINMAX_RSI) // 3-day RSI above 85 .ToList()); //----- manage existing positions int numOpenPositions = Positions.Keys.Count(); foreach (var pos in Positions.Keys) { // time-based exit if (entryParameters[pos].entryDate <= SimTime[MAX_HOLD_DAYS - 1]) { pos.Trade(-pos.Position, OrderType.closeThisBar).Comment = "time exit"; numOpenPositions--; } else if (ENTRY_DIR > 0 ? pos.Close[0] >= entryParameters[pos].profitTarget // long : pos.Close[0] <= entryParameters[pos].profitTarget) // short { pos.Trade(-pos.Position, OrderType.openNextBar) .Comment = "profit target"; numOpenPositions--; } else { pos.Trade(-pos.Position, OrderType.stopNextBar, entryParameters[pos].stopLoss) .Comment = "stop loss"; } } //----- open new positions // sort candidates by RSI to find entries var entries = ENTRY_DIR > 0 ? filtered // long .Where(i => i.Position == 0) .OrderBy(i => indicators[i].rsi3[0]) .Take(MAX_ENTRIES - numOpenPositions) .ToList() : filtered // short .Where(i => i.Position == 0) .OrderByDescending(i => indicators[i].rsi3[0]) .Take(MAX_ENTRIES - numOpenPositions) .ToList(); foreach (var i in entries) { // save our entry parameters, so that we may access // them later to manage exits double entryPrice = ENTRY_DIR > 0 ? i.Close[0] * (1.0 - MIN_ATR / 10000.0) // long : i.Close[0]; // short double stopLoss = ENTRY_DIR > 0 ? entryPrice * (1.0 - STOP_LOSS / 100.0 * indicators[i].atr10[0]) // long : entryPrice * (1.0 + STOP_LOSS / 100.0 * indicators[i].atr10[0]); // short double profitTarget = ENTRY_DIR > 0 ? entryPrice * (1.0 + PROFIT_TARGET / 10000.0) // long : entryPrice * (1.0 - PROFIT_TARGET / 10000.0); // short entryParameters[i] = new { entryDate = NextSimTime, entryPrice, stopLoss, profitTarget, }; // calculate target shares in two ways: // * fixed-fractional risk (with entry - stop-loss = "risk"), and // * fixed percentage of total equity double riskPerShare = ENTRY_DIR > 0 ? Math.Max(0.10, entryPrice - stopLoss) // long : Math.Max(0.10, stopLoss - entryPrice); // short int sharesRiskLimited = (int)Math.Floor(MAX_RISK / 100.0 / MAX_ENTRIES * NetAssetValue[0] / riskPerShare); int sharesCapLimited = (int)Math.Floor(MAX_CAP / 100.0 / MAX_ENTRIES * NetAssetValue[0] / entryParameters[i].entryPrice); int targetShares = (ENTRY_DIR > 0 ? 1 : -1) * Math.Min(sharesRiskLimited, sharesCapLimited); // enter positions with limit order i.Trade(targetShares, OrderType.limitNextBar, entryParameters[i].entryPrice); } //----- output if (!IsOptimizing && TradingDays > 0) { _plotter.AddNavAndBenchmark(this, FindInstrument(BENCHMARK)); //_plotter.AddStrategyHoldings(this, universe); // plot strategy exposure _plotter.SelectChart("Exposure Chart", "Date"); _plotter.SetX(SimTime[0]); _plotter.Plot("Exposure", Instruments.Sum(i => i.Position * i.Close[0]) / NetAssetValue[0]); if (IsDataSource) { var v = 10.0 * NetAssetValue[0] / Globals.INITIAL_CAPITAL; yield return(Bar.NewOHLC( this.GetType().Name, SimTime[0], v, v, v, v, 0)); } } } //========== post processing ========== if (!IsOptimizing) { //_plotter.AddTargetAllocation(_alloc); //_plotter.AddOrderLog(this); //_plotter.AddPositionLog(this); //_plotter.AddPnLHoldTime(this); //_plotter.AddMfeMae(this); _plotter.AddParameters(this); } FitnessValue = this.CalcFitness(); }
public static void Main() { Foo test = new Bar(); Console.WriteLine(test.DoSomething()); }
static void Main() { var tmp = new Bar(); tmp.Method(); }
public static void Main() { // item 159 Bar db = new Bar(); // item 76 Bar.IEmployee john = db.InsertEmployee(0, "John", new DateTime(1978, 1, 1)); Bar.IEmployee mark = db.InsertEmployee(0, "Mark", new DateTime(1978, 1, 1)); Bar.IEmployee john2 = db.InsertEmployee(0, "John", new DateTime(1985, 1, 1)); // item 75 db.InsertDepartment(0, "Marketing"); db.InsertDepartment(0, "Sales"); db.InsertDepartment(0, "Logistics"); Bar.IDepartment marketing = db.FindDepartmentByTitle("Marketing"); Bar.IDepartment sales = db.FindDepartmentByTitle("Sales"); Bar.IDepartment logistics = db.FindDepartmentByTitle("Logistics"); // item 205 Equal(null, john.Department); Equal(null, john2.Department); Equal(null, mark.Department); // item 137 db.SetEmployeeDepartment(john, null); db.SetEmployeeDepartment(john2, null); db.SetEmployeeDepartment(mark, null); // item 136 Equal(null, john.Department); Equal(null, john2.Department); Equal(null, mark.Department); // item 114 var fakeDepartment = new FakeDepartment { Id = 1000, Title = "Fake" }; ExpectException(() => db.SetEmployeeDepartment(john, fakeDepartment) ); // item 138 db.SetEmployeeDepartment(john, marketing); db.SetEmployeeDepartment(john2, sales); db.SetEmployeeDepartment(mark, marketing); // item 139 Equal(marketing, john.Department); Equal(sales, john2.Department); Equal(marketing, mark.Department); // item 141 db.SetEmployeeDepartment(john, marketing); db.SetEmployeeDepartment(john2, logistics); db.SetEmployeeDepartment(mark, null); // item 142 Equal(marketing, john.Department); Equal(logistics, john2.Department); Equal(null, mark.Department); // item 143 db.DeleteDepartment(sales); Equal(null, db.FindDepartmentByTitle("Sales")); // item 144 ExpectException(() => db.DeleteDepartment(marketing)); ExpectException(() => db.DeleteDepartment(logistics)); // item 100 db.DeleteEmployee(john); db.DeleteDepartment(marketing); // item 101 db.SetEmployeeDepartment(john2, null); db.DeleteDepartment(logistics); // item 145 Equal(2, db.EmployeeCount()); Equal(0, db.DepartmentCount()); }
public virtual void DoDelete(Bar db, System.Collections.Generic.HashSet <IDelRecord> deletionList) { db._department_Title.Remove(this); db._department_pk.Remove(_id); }
public virtual void EvaluateSingleObject(ITradingObject tradingObject, Bar bar) { }
public virtual void WarmUp(ITradingObject tradingObject, Bar bar) { // do nothing }
public override void OnNewBar(Bar bar) { }
private void load() { if (hitEvents == null || hitEvents.Count == 0) { return; } int[] bins = new int[total_timing_distribution_bins]; double binSize = Math.Ceiling(hitEvents.Max(e => Math.Abs(e.TimeOffset)) / timing_distribution_bins); // Prevent div-by-0 by enforcing a minimum bin size binSize = Math.Max(1, binSize); foreach (var e in hitEvents) { int binOffset = (int)(e.TimeOffset / binSize); bins[timing_distribution_centre_bin_index + binOffset]++; } int maxCount = bins.Max(); var bars = new Drawable[total_timing_distribution_bins]; for (int i = 0; i < bars.Length; i++) { bars[i] = new Bar { Height = Math.Max(0.05f, (float)bins[i] / maxCount) } } ; Container axisFlow; InternalChild = new GridContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Width = 0.8f, Content = new[] { new Drawable[] { new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { bars } } }, new Drawable[] { axisFlow = new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y } }, }, RowDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.AutoSize), } }; // Our axis will contain one centre element + 5 points on each side, each with a value depending on the number of bins * bin size. double maxValue = timing_distribution_bins * binSize; double axisValueStep = maxValue / axis_points; axisFlow.Add(new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, Text = "0", Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold) }); for (int i = 1; i <= axis_points; i++) { double axisValue = i * axisValueStep; float position = (float)(axisValue / maxValue); float alpha = 1f - position * 0.8f; axisFlow.Add(new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativePositionAxes = Axes.X, X = -position / 2, Alpha = alpha, Text = axisValue.ToString("-0"), Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold) }); axisFlow.Add(new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativePositionAxes = Axes.X, X = position / 2, Alpha = alpha, Text = axisValue.ToString("+0"), Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold) }); } }
public override IEnumerable <Bar> Run(DateTime?startTime, DateTime?endTime) { //========== initialization ========== #if USE_BENSDORPS_RANGE // matching range in the book StartTime = SubclassedStartTime ?? DateTime.Parse("01/02/1995", CultureInfo.InvariantCulture); EndTime = SubclassedEndTime ?? DateTime.Parse("11/23/2016", CultureInfo.InvariantCulture); WarmupStartTime = StartTime - TimeSpan.FromDays(365); #else StartTime = startTime ?? Globals.START_TIME; EndTime = endTime ?? Globals.END_TIME; WarmupStartTime = Globals.WARMUP_START_TIME; #endif Deposit(Globals.INITIAL_CAPITAL); CommissionPerShare = Globals.COMMISSION; AddDataSources(UNIVERSE.Constituents); var spx = AddDataSource(SPX); var benchmark = AddDataSource(BENCHMARK); //========== simulation loop ========== double nn = 0.0; foreach (var s in SimTimes) { var universe = Instruments .Where(i => i.IsConstituent(UNIVERSE)) .ToList(); //----- calculate indicators // calculate indicators for all known instruments, // as they might enter the universe any time var indicators = Instruments .ToDictionary( i => i, i => new { rsi = i.Close.RSI(3), roc = i.Close.Momentum(200), }); if (!HasInstrument(benchmark)) { continue; } var smaBand = spx.Instrument.Close.SMA(200).Multiply(0.98); // 2% below 200-day SMA // open positions on Monday if (NextSimTime.DayOfWeek < SimTime[0].DayOfWeek) // open positions on Monday { // we are not entirely sure how Bensdorp wants this strategy to work. // we see three alternatives #if false // solution A // create one list of 10 stocks, none of which are overbought, // ranked by momentum // good: new entries are guaranteed to be on keep-list on day 1 // also, we always hold 10 stocks // bad: we might exit stocks with top momentum, as soon as they become overbought // => this strategy seems to never hold stocks longer than 60 days, // conflicting with the statements made in the book var nextHoldings = universe .Where(i => spx.Instrument.Close[0] > smaBand[0]) .Where(i => indicators[i].rsi[0] < MAX_RSI) .OrderByDescending(i => indicators[i].roc[0]) .Take(MAX_ENTRIES) .ToList(); #endif #if false // solution B // create separate list for new entries and for keepers // good: this makes sure that we almost always hold 10 stocks // bad: a new stock entered might not meet the hold requirements, // as it might not have top-10 momentum. this adds somewhat of // a mean-reversion component to the strategy // => this strategy seems to work very well over the book's backtesting period. // overall, higher return and higher drawdown than C, worse Sharpe ratio var keep = universe .Where(i => spx.Instrument.Close[0] > smaBand[0]) .OrderByDescending(i => indicators[i].roc[0]) .Take(MAX_ENTRIES) .Where(i => i.Position != 0) .ToList(); var enter = universe .Where(i => spx.Instrument.Close[0] > smaBand[0]) .Where(i => i.Position == 0 && indicators[i].rsi[0] < MAX_RSI) .OrderByDescending(i => indicators[i].roc[0]) .Take(MAX_ENTRIES - keep.Count) .ToList(); var nextHoldings = keep .Concat(enter) .ToList(); #endif #if true // solution C // draw new entries and keeps both from top-10 ranked stocks // good: new entries are guaranteed to be on the keep list on day 1 // bad: the enter list might be empty, if all top-10 stocks are overbought // driving down our exposure and therewith return var top10 = universe .Where(i => spx.Instrument.Close[0] > smaBand[0]) .OrderByDescending(i => indicators[i].roc[0]) .Take(MAX_ENTRIES) .ToList(); var keep = top10 .Where(i => i.Position != 0) .ToList(); var enter = top10 .Where(i => i.Position == 0 && indicators[i].rsi[0] < MAX_RSI) .ToList(); var nextHoldings = keep .Concat(enter) .ToList(); #endif Alloc.Allocation.Clear(); foreach (var i in Instruments) { double targetPercentage = nextHoldings.Contains(i) ? 1.0 / MAX_ENTRIES : 0.0; int targetShares = (int)Math.Floor(NetAssetValue[0] * targetPercentage / i.Close[0]); if (targetPercentage != 0.0) { Alloc.Allocation[i] = targetPercentage; } i.Trade(targetShares - i.Position); } nn = nextHoldings.Count / 10.0; } //----- output if (!IsOptimizing && TradingDays > 0) { _plotter.AddNavAndBenchmark(this, FindInstrument(BENCHMARK)); //_plotter.AddStrategyHoldings(this, universe); // plot strategy exposure _plotter.SelectChart("Exposure Chart", "Date"); _plotter.SetX(SimTime[0]); _plotter.Plot("Exposure", Instruments.Sum(i => i.Position * i.Close[0]) / NetAssetValue[0]); //_plotter.Plot("Choices", nn); if (Alloc.LastUpdate == SimTime[0]) { _plotter.AddTargetAllocationRow(Alloc); } if (IsDataSource) { var v = 10.0 * NetAssetValue[0] / Globals.INITIAL_CAPITAL; yield return(Bar.NewOHLC( this.GetType().Name, SimTime[0], v, v, v, v, 0)); } } } //========== post processing ========== if (!IsOptimizing) { _plotter.AddTargetAllocation(Alloc); _plotter.AddOrderLog(this); _plotter.AddPositionLog(this); _plotter.AddPnLHoldTime(this); _plotter.AddMfeMae(this); _plotter.AddParameters(this); } FitnessValue = this.CalcFitness(); }
public async Task CreateComment_whenAlreadyCommented() { var testBarName = "TestBarName"; var testUserName = "******"; var options = Utils.GetOptions(nameof(CreateComment_whenAlreadyCommented)); var testUser = new User() { Id = Utils.MySampleGuid(), UserName = testUserName, }; var testBar = new Bar() { Id = Utils.MySampleGuid3(), Name = testBarName, }; var testComment = new BarUserComment() { UserId = testUser.Id, User = testUser, BarId = testBar.Id, Bar = testBar, Text = "Comment text here.", }; var dto = new BarUserCommentDTO() { UserId = testUser.Id, BarId = testBar.Id, Text = "New comment text here.", }; var mockMapper = new Mock <IBarUserCommentMapper>(); mockMapper.Setup(x => x.MapDTOToEntity(It.IsAny <BarUserCommentDTO>())) .Returns((BarUserCommentDTO x) => new BarUserComment() { BarId = x.BarId, UserId = x.UserId, Text = x.Text }); mockMapper.Setup(x => x.MapEntityToDTO(It.IsAny <BarUserComment>())) .Returns((BarUserComment x) => new BarUserCommentDTO() { BarId = x.BarId, BarName = x.Bar.Name, UserId = x.UserId, UserName = x.User.UserName, Text = x.Text }); using (var arrangeContext = new BCcontext(options)) { await arrangeContext.Users.AddAsync(testUser); await arrangeContext.Bars.AddAsync(testBar); await arrangeContext.BarComments.AddAsync(testComment); await arrangeContext.SaveChangesAsync(); } using (var context = new BCcontext(options)) { var sut = new BarUserCommentsService(context, mockMapper.Object); //Act var result = await sut.CreateAsync(dto); //Assert Assert.AreNotEqual(testBar.Id, result.BarId); Assert.IsNull(result.BarName); Assert.AreNotEqual(testUser.Id, result.UserId); Assert.IsNull(result.UserName); Assert.IsNull(result.Text); Assert.AreEqual(1, context.BarComments.Count()); var bar = await context.Bars .Include(x => x.Comments) .FirstOrDefaultAsync(x => x.Name == testBarName); var comment = bar.Comments.FirstOrDefault(); Assert.IsNotNull(comment); Assert.AreNotEqual(dto.Text, comment.Text); } }
public static JObject InsertNewRatingToDB(Rate rate) { JObject rateToReturn = new JObject(); bool insertSucceeded = true, firstRate; ArrayList barByIds; List <SqlParameter> barIds = new List <SqlParameter>(); List <SqlParameter> barParameters = new List <SqlParameter>(); barIds.Add(new SqlParameter("@barId", rate.BarId)); string challengeWin = ""; barByIds = DBController.ExecuteStoredProcedure_Select("sp_get_bar_by_barId", barIds); if (barByIds.Count == 0) { barParameters.Add(new SqlParameter("@barId", rate.BarId)); barParameters.Add(new SqlParameter("@barGoogleId", rate.BarGoogleId)); barParameters.Add(new SqlParameter("@barName", rate.BarName)); barParameters.Add(new SqlParameter("@photoUrl", rate.photoURL)); barParameters.Add(new SqlParameter("@Address", rate.address)); insertSucceeded = DBController.ExecuteStoredProcedure_InsertOrUpdateOrDelete("sp_insert_new_bar", barParameters); } if (insertSucceeded == true) { ArrayList rating_of_user_and_bar; List <SqlParameter> parameters = new List <SqlParameter>(); parameters.Add(new SqlParameter("userName", rate.UserName)); parameters.Add(new SqlParameter("barId", rate.BarId)); parameters.Add(new SqlParameter("barGoogleId", rate.BarGoogleId)); parameters.Add(new SqlParameter("@barName", rate.BarName)); parameters.Add(new SqlParameter("date", rate.date)); parameters.Add(new SqlParameter("age", (int)rate.Age)); parameters.Add(new SqlParameter("service", (int)rate.Service)); parameters.Add(new SqlParameter("price", (int)rate.Price)); parameters.Add(new SqlParameter("burgers", rate.Food.Burger)); parameters.Add(new SqlParameter("pizza", rate.Food.Pizza)); parameters.Add(new SqlParameter("sushi", rate.Food.Sushi)); parameters.Add(new SqlParameter("snacks", rate.Food.Snacks)); parameters.Add(new SqlParameter("vegan", rate.Food.Vegan)); parameters.Add(new SqlParameter("kosher", rate.Food.Kosher)); parameters.Add(new SqlParameter("beer", rate.Drinks.Beer)); parameters.Add(new SqlParameter("wine", rate.Drinks.Wine)); parameters.Add(new SqlParameter("cocktail", rate.Drinks.Cocktail)); parameters.Add(new SqlParameter("beveragePackages", rate.Drinks.BeveragePackages)); parameters.Add(new SqlParameter("Jin", rate.Drinks.Jin)); parameters.Add(new SqlParameter("whiskey", rate.Drinks.Whiskey)); parameters.Add(new SqlParameter("wideRangeOfBeverages", rate.Drinks.WideRangeOfBeverages)); parameters.Add(new SqlParameter("irish", rate.Atmosphere.Irish)); parameters.Add(new SqlParameter("chill", rate.Atmosphere.Chill)); parameters.Add(new SqlParameter("dance", rate.Atmosphere.Dance)); parameters.Add(new SqlParameter("sport", rate.Atmosphere.Sport)); parameters.Add(new SqlParameter("shisha", rate.Atmosphere.Shisha)); parameters.Add(new SqlParameter("party", rate.Atmosphere.Party)); parameters.Add(new SqlParameter("smokingFree", rate.SmokingFree)); parameters.Add(new SqlParameter("dating", rate.Company.Dating)); parameters.Add(new SqlParameter("friends", rate.Company.Friends)); parameters.Add(new SqlParameter("kidsFriendly", rate.Company.KidsFriendly)); parameters.Add(new SqlParameter("petsFriendly", rate.Company.PetsFriendly)); parameters.Add(new SqlParameter("colleagues", rate.Company.Colleagues)); parameters.Add(new SqlParameter("pop", rate.Music.Pop)); parameters.Add(new SqlParameter("jazz", rate.Music.Jazz)); parameters.Add(new SqlParameter("mizrahit", rate.Music.Mizrahit)); parameters.Add(new SqlParameter("greek", rate.Music.Greek)); parameters.Add(new SqlParameter("trance", rate.Music.Trance)); parameters.Add(new SqlParameter("mainstream", rate.Music.Mainstream)); parameters.Add(new SqlParameter("israeli", rate.Music.Israeli)); parameters.Add(new SqlParameter("liveMusic", rate.Music.LiveMusic)); parameters.Add(new SqlParameter("reggaeton", rate.Music.Reggaeton)); parameters.Add(new SqlParameter("openMic", rate.Music.OpenMic)); parameters.Add(new SqlParameter("standup", rate.Music.StandUp)); List <SqlParameter> parameters1 = new List <SqlParameter>(); parameters1.Add(new SqlParameter("userName", rate.UserName)); parameters1.Add(new SqlParameter("barId", rate.BarId)); rating_of_user_and_bar = DBController.ExecuteStoredProcedure_Select("sp_get_rating_of_user_and_bar", parameters1); if (rating_of_user_and_bar.Count == 0) { firstRate = true; insertSucceeded = DBController.ExecuteStoredProcedure_InsertOrUpdateOrDelete("sp_insert_new_rating", parameters); } else { firstRate = false; insertSucceeded = DBController.ExecuteStoredProcedure_InsertOrUpdateOrDelete("sp_update_rating", parameters); } Bar bar = Engine.GetBarByBarID(rate.BarId); //Engine.updatePhotoUrlInDB(); bar.UpdateBarByRate(); Engine.InsertUpdateBarCharacteristicToDB(bar); User user = Engine.GetUserByUserName(rate.UserName); user.UpdateUserByRate(rate); if (firstRate) { Engine.GetChallengeUserByUserName(user); user.UpdateScoreAfterRating(bar); if (user.IsDeservedAJerusalemBadge(bar)) { challengeWin = "ירושלים"; } if (user.IsDeservedATLVBadge(bar)) { challengeWin = "תל אביב"; } if (user.IsDeservedAWorldBadge(bar)) { challengeWin = "עולמי"; } } Engine.InsertUpdateUserCountersToDB(user); if (insertSucceeded) { HttpContext.Current.Session["needUpdate"] = "1"; } } rateToReturn["insertSucceeded"] = insertSucceeded.ToString(); rateToReturn["challengeWin"] = challengeWin; return(rateToReturn); }
public void TestHello() { var hello = new Hello(); hello.PrintHello("Hello world"); Assert.That(hello.Add(1, 1), Is.EqualTo(2)); Assert.That(hello.Add(5, 5), Is.EqualTo(10)); Assert.IsTrue(hello.Test1(3, 3.0f)); Assert.IsFalse(hello.Test1(2, 3.0f)); var foo = new Foo { A = 4, B = 7 }; Assert.That(hello.AddFoo(foo), Is.EqualTo(11)); Assert.That(hello.AddFooPtr(foo), Is.EqualTo(11)); Assert.That(hello.AddFooPtr(foo), Is.EqualTo(11)); Assert.That(hello.AddFooRef(foo), Is.EqualTo(11)); unsafe { var pointer = foo.SomePointer; var pointerPointer = foo.SomePointerPointer; for (int i = 0; i < 4; i++) { Assert.AreEqual(i, pointer[i]); Assert.AreEqual(i, (*pointerPointer)[i]); } } var bar = new Bar { A = 4, B = 7 }; Assert.That(hello.AddBar(bar), Is.EqualTo(11)); Assert.That(bar.RetItem1(), Is.EqualTo(Bar.Item.Item1)); var retFoo = hello.RetFoo(7, 2.0f); Assert.That(retFoo.A, Is.EqualTo(7)); Assert.That(retFoo.B, Is.EqualTo(2.0)); var foo2 = new Foo2 { A = 4, B = 2, C = 3 }; Assert.That(hello.AddFoo(foo2), Is.EqualTo(6)); Assert.That(hello.AddFoo2(foo2), Is.EqualTo(9)); var bar2 = new Bar2 { A = 4, B = 7, C = 3 }; Assert.That(hello.AddBar2(bar2), Is.EqualTo(14)); Assert.That(hello.RetEnum(Enum.A), Is.EqualTo(0)); Assert.That(hello.RetEnum(Enum.B), Is.EqualTo(2)); Assert.That(hello.RetEnum(Enum.C), Is.EqualTo(5)); //Assert.That(hello.RetEnum(Enum.D), Is.EqualTo(-2147483648)); Assert.That(hello.RetEnum(Enum.E), Is.EqualTo(1)); Assert.That(hello.RetEnum(Enum.F), Is.EqualTo(-9)); }
/// <summary> /// Populate values from the base palette. /// </summary> public void PopulateFromBase() { Bar.PopulateFromBase(); }
public void historicalDataUpdate(int reqId, Bar bar) { }
public async Task ReturnCount_WhenSearchByMultipleParameters() { var barFactoryMock = new Mock <IBarFactory>(); var barCocktailFactoryMock = new Mock <IBarCocktailFactory>(); var imagaUrlTest = "https://www.google.com/"; var bar1TestName = "abC"; var bar2TestName = "Def"; var bar3TestName = "Bci"; var bar4TestName = "jkl"; var city1Name = "Sofia"; var city2Name = "Varna"; var options = TestUtilities.GetOptions(nameof(ReturnCount_WhenSearchByMultipleParameters)); using (var arrangeContext = new CocktailMagicianDb(options)) { arrangeContext.Cities.AddRange(new List <City> { new City { Name = city1Name }, new City { Name = city2Name } }); await arrangeContext.SaveChangesAsync(); var city1Id = await arrangeContext.Cities.Where(c => c.Name == city1Name).Select(c => c.Id).FirstAsync(); var city2Id = await arrangeContext.Cities.Where(c => c.Name == city2Name).Select(c => c.Id).FirstAsync(); var address1Test = new Address { Name = "Address1Test", CityId = city1Id, Latitude = 1.1, Longitude = 1.1 }; var address2Test = new Address { Name = "Address2Test", CityId = city2Id, Latitude = 1.1, Longitude = 1.1 }; var bar1 = new Bar { Name = bar1TestName, ImagePath = imagaUrlTest, Address = address1Test, BarReviews = new List <BarReview> { new BarReview { Rating = 3 } } }; var bar2 = new Bar { Name = bar2TestName, ImagePath = imagaUrlTest, Address = address2Test, BarReviews = new List <BarReview> { new BarReview { Rating = 4 } } }; var bar3 = new Bar { Name = bar3TestName, ImagePath = imagaUrlTest, Address = address1Test, BarReviews = new List <BarReview> { new BarReview { Rating = 4 } } }; var bar4 = new Bar { Name = bar4TestName, ImagePath = imagaUrlTest, Address = address1Test, BarReviews = new List <BarReview> { new BarReview { Rating = 5 } } }; arrangeContext.Bars.AddRange(new List <Bar> { bar1, bar2, bar3, bar4 }); await arrangeContext.SaveChangesAsync(); } using (var assertContext = new CocktailMagicianDb(options)) { var substringToSearch = "Bc"; var cityIdToSearch = await assertContext.Cities.Where(c => c.Name == city1Name).Select(c => c.Id).FirstAsync(); var minRatingToSearch = 4; var dtoTest = new BarSearchDTO { CityId = cityIdToSearch, MinRating = minRatingToSearch, NameKey = substringToSearch }; var sut = new BarServices(assertContext, barFactoryMock.Object, barCocktailFactoryMock.Object); var resultCount = await sut.SerchResultCountAsync(dtoTest); Assert.AreEqual(1, resultCount); } }
void blt_GotNewBar(string symbol, int interval) { int idx = _active.getindex(symbol); Tick tOther = _kt[symbol]; // calculate the SMA using closign prices for so many bars back decimal SMA = decimal.MinValue; BarList _myBars = _blt[symbol, interval]; // make sure the lastBar is full Bar _lastBar = _myBars[_myBars.Count - 2]; if (UseSMAFromATSGlobalIndicator) { _SMAFromATSGlobalIndicator.UpdateValue(_lastBar.Close); SMA = _SMAFromATSGlobalIndicator.GetSignal(); } else { SMA = Calc.Avg(Calc.EndSlice(_blt[symbol].Open(), _barsback)); } // wait until we have an SMA if (SMA == 0) { return; } //ensure we aren't waiting for previous order to fill if (!_wait[symbol]) { // if we're flat and not waiting if (_pt[symbol].isFlat) { // if our current price is above SMA, buy if (_blt[symbol].RecentBar.Close > SMA) { D("crosses above MA, buy"); //sendorder(new BuyMarket(symbol, EntrySize)); _side = true; _adj = (_side ? -1 : +1) * _quasiMarketOrderAdjSize; Int64 _orderidLocal = _idtLocal.AssignId; LimitOrder lOrder = new LimitOrder(symbol, _side, EntrySize, tOther.trade - _adj, _orderidLocal); sendorder(lOrder); // wait for fill _wait[symbol] = true; } // otherwise if it's less than SMA, sell if (_blt[symbol].RecentBar.Close < SMA) { D("crosses below MA, sell"); //sendorder(new SellMarket(symbol, EntrySize)); _side = false; _adj = (_side ? -1 : +1) * _quasiMarketOrderAdjSize; Int64 _orderidLocal = _idtLocal.AssignId; LimitOrder lOrder = new LimitOrder(symbol, _side, EntrySize, tOther.trade - _adj, _orderidLocal); sendorder(lOrder); // wait for fill _wait[symbol] = true; } } else if ((_pt[symbol].isLong && (_blt[symbol].RecentBar.Close < SMA)) || (_pt[symbol].isShort && (_blt[symbol].RecentBar.Close > SMA))) { D("counter trend, exit."); //sendorder(new MarketOrderFlat(pt[symbol])); _side = !_pt[symbol].isLong; _adj = (_side ? -1 : +1) * _quasiMarketOrderAdjSize; Int64 _orderidLocal = _idtLocal.AssignId; LimitOrder lOrder = new LimitOrder(symbol, _side, EntrySize, tOther.trade - _adj, _orderidLocal); sendorder(lOrder); // wait for fill _wait[symbol] = true; } } // this way we can debug our indicators during development // indicators are sent in the same order as they are named above sendindicators(new string[] { _time.ToString(), SMA.ToString("F5", System.Globalization.CultureInfo.InvariantCulture), _lastBar.Close.ToString("F5", System.Globalization.CultureInfo.InvariantCulture) }); }
public Foo(Bar bar) { }
public async Task ReturnsMostRatedInOrderOfRating() { var options = Utils.GetOptions(nameof(ReturnsMostRatedInOrderOfRating)); var barList = new List <Bar>(); for (int i = 1; i <= 3; i++) { var bar = new Bar() { Name = "BestBar" + i, Rating = 3, TimesRated = i, ImageSrc = null, IsDeleted = false, Address = "Street " + i, Country = "България", District = "District " + i, Email = "*****@*****.**", Phone = "+ " + i + "8888888", Town = "София", LocationId = null, }; barList.Add(bar); } using (var context = new BCcontext(options)) { await context.Bars.AddRangeAsync(barList); await context.SaveChangesAsync(); } var mockMapper = new Mock <IBarMapper>(); mockMapper.Setup((x) => x.MapEntityToDTO(It.IsAny <Bar>())) .Returns((Bar b) => new BarDTO() { Id = b.Id, Name = b.Name, Rating = b.Rating, TimesRated = b.TimesRated, ImageSrc = b.ImageSrc, IsDeleted = b.IsDeleted, Address = b.Address, Country = b.Country, District = b.District, Email = b.Email, LocationId = b.LocationId, Phone = b.Phone, Town = b.Town }); var http = new Mock <IHttpClientFactory>(); var coctailMapper = new Mock <ICocktailMapper>(); //Act & Assert using (var context = new BCcontext(options)) { var sut = new BarsService(context, mockMapper.Object, http.Object, coctailMapper.Object); var result = await sut.GetBestBarsAsync(); var ordered = result.OrderBy(o => o.TimesRated).ThenByDescending(o => o.Rating).ToList(); Assert.AreEqual(result.Count(), 3); CollectionAssert.AreEqual(result.ToList(), ordered); } }
public void historicalData(int reqId, Bar bar) { }
public override IEnumerable <Bar> Run(DateTime?startTime, DateTime?endTime) { //========== initialization ========== #if USE_CLENOWS_RANGE // matching Clenow's charts StartTime = DateTime.Parse("01/01/1999", CultureInfo.InvariantCulture); WarmupStartTime = StartTime - TimeSpan.FromDays(180); EndTime = DateTime.Parse("12/31/2014", CultureInfo.InvariantCulture); #else WarmupStartTime = Globals.WARMUP_START_TIME; StartTime = Globals.START_TIME; EndTime = Globals.END_TIME; #endif Deposit(IsChildAlgorithm ? 0.0 : Globals.INITIAL_CAPITAL); CommissionPerShare = Globals.COMMISSION; // Clenow is not considering commissions var all = AddDataSources(UNIVERSE.Constituents); var sp500 = AddDataSource(SP500); var benchmark = AddDataSource(BENCHMARK); //========== simulation loop ========== double?sp500Initial = null; // loop through all bars foreach (DateTime simTime in SimTimes) { if (!HasInstrument(benchmark)) { continue; } sp500Initial = sp500Initial ?? sp500.Instrument.Open[0]; // calculate indicators exactly once per bar // we are doing this on all available instruments, // as we don't know when they will become S&P500 constituents var indicators = Instruments .ToDictionary( i => i, i => new { regression = i.Close.LogRegression(MOM_PERIOD), maxMove = i.Close.SimpleMomentum(1).AbsValue().Highest(MOM_PERIOD), avg100 = i.Close.SMA(INSTR_TREND), atr20 = i.AverageTrueRange(ATR_PERIOD), });; // index filter: only buy any shares, while S&P-500 is trading above its 200-day moving average // NOTE: the 10-day SMA on the benchmark is _not_ mentioned in // the book. We added it here, to compensate for the // simplified re-balancing schedule. bool allowNewEntries = sp500.Instrument.Close.SMA(INDEX_FLT)[0] > sp500.Instrument.Close.SMA(INDEX_TREND)[0]; // determine current S&P 500 constituents var constituents = Instruments .Where(i => i.IsConstituent(UNIVERSE)) .ToList(); // trade once per week // this is a slight simplification from Clenow's suggestion to adjust positions // every week, and adjust position sizes only every other week if (IsTradingDay) { // rank by volatility-adjusted momentum and pick top 20% (top-100) var topRankedInstruments = constituents // FIXME: how exactly are we multiplying the regression slope with R2? .OrderByDescending(i => (Math.Exp(252.0 * indicators[i].regression.Slope[0]) - 1.0) * indicators[i].regression.R2[0]) //.OrderByDescending(i => indicators[i].regression.Slope[0] * indicators[i].regression.R2[0]) .Take((int)Math.Round(TOP_PCNT / 100.0 * constituents.Count)) .ToList(); // disqualify // - trading below 100-day moving average // - maximum move > 15% // FIXME: is maxMove > 1.0??? var availableInstruments = topRankedInstruments .Where(i => i.Close[0] > indicators[i].avg100[0] && indicators[i].maxMove[0] < MAX_MOVE / 100.0) .ToList(); // allocate capital until we run out of cash var weights = Instruments .ToDictionary( i => i, i => 0.0); double availableCapital = 1.0; int portfolioRisk = 0; foreach (var i in availableInstruments) { // Clenow does not limit the total portfolio risk if (portfolioRisk > RISK_TOTAL) { continue; } var currentWeight = NetAssetValue[0] > 0 ? i.Position * i.Close[0] / NetAssetValue[0] : 0.0; var newWeight = Math.Min(Math.Min(availableCapital, MAX_PER_STOCK / 100.0), RISK_PER_STOCK * 0.0001 / indicators[i].atr20[0] * i.Close[0]); var w = allowNewEntries ? newWeight : Math.Min(currentWeight, newWeight); weights[i] = w; availableCapital -= w; portfolioRisk += RISK_PER_STOCK; } // perform customized money-management ManageWeights(weights); // submit trades Alloc.LastUpdate = SimTime[0]; Alloc.Allocation.Clear(); foreach (var i in Instruments) { if (weights[i] > 0.005) { Alloc.Allocation[i] = weights[i]; } var targetShares = (int)Math.Round(NetAssetValue[0] * weights[i] / i.Close[0]); i.Trade(targetShares - i.Position, OrderType.openNextBar); } if (!IsOptimizing && (EndTime - SimTime[0]).TotalDays < 30) { string message = constituents .Where(i => weights[i] != 0.0) .Aggregate(string.Format("{0:MM/dd/yyyy}: ", SimTime[0]), (prev, i) => prev + string.Format("{0}={1:P2} ", i.Symbol, weights[i])); Output.WriteLine(message); } } // create charts if (!IsOptimizing && TradingDays > 0) { _plotter.AddNavAndBenchmark(this, benchmark.Instrument); //_plotter.AddStrategyHoldings(this, universeConstituents); // plot strategy exposure _plotter.SelectChart("Strategy Exposure", "Date"); _plotter.SetX(SimTime[0]); _plotter.Plot("Stock Exposure", constituents.Sum(i => i.Position * i.Close[0]) / NetAssetValue[0]); _plotter.Plot("Number of Stocks", constituents.Where(i => i.Position != 0).Count()); if (Alloc.LastUpdate == SimTime[0]) { _plotter.AddTargetAllocationRow(Alloc); } #if true _plotter.SelectChart("Clenow-style Chart", "Date"); _plotter.SetX(SimTime[0]); _plotter.Plot(Name, NetAssetValue[0] / Globals.INITIAL_CAPITAL); _plotter.Plot(sp500.Instrument.Name, sp500.Instrument.Close[0] / sp500Initial); _plotter.Plot(sp500.Instrument.Name + " 200-day moving average", sp500.Instrument.Close.SMA(200)[0] / sp500Initial); _plotter.Plot("Cash", Cash / NetAssetValue[0]); #endif } if (IsDataSource) { var v = 10.0 * NetAssetValue[0] / Globals.INITIAL_CAPITAL; yield return(Bar.NewOHLC( this.GetType().Name, SimTime[0], v, v, v, v, 0)); } } //========== post processing ========== if (!IsOptimizing) { _plotter.AddTargetAllocation(Alloc); _plotter.AddOrderLog(this); _plotter.AddPositionLog(this); _plotter.AddPnLHoldTime(this); _plotter.AddMfeMae(this); _plotter.AddParameters(this); } FitnessValue = this.CalcFitness(); }
private async Task CreateCommunity() { UserInfo1 = await CreateTestUser(); UserInfo2 = await CreateTestUser(); UserInfo3 = await CreateTestUser(); var community1Id = Guid.NewGuid().ToString(); var community2Id = Guid.NewGuid().ToString(); var community3Id = Guid.NewGuid().ToString(); var bar1 = new Bar() { Id = Guid.NewGuid().ToString(), CommunityId = community1Id }; await Database.Save(bar1); Community1 = new Community() { Id = community1Id, Name = "Test Community", DefaultBarId = bar1.Id }; await Database.Save(Community1); var bar2 = new Bar() { Id = Guid.NewGuid().ToString(), CommunityId = community2Id }; await Database.Save(bar2); Community2 = new Community() { Id = community2Id, Name = "Test Community 2", DefaultBarId = bar2.Id }; await Database.Save(Community2); var bar3 = new Bar() { Id = Guid.NewGuid().ToString(), CommunityId = community3Id }; await Database.Save(bar3); Community3 = new Community() { Id = community3Id, Name = "Test Community 3", DefaultBarId = bar3.Id }; await Database.Save(Community3); var member = new Member() { Id = Guid.NewGuid().ToString(), CommunityId = Community1.Id, UserId = UserInfo1.Id, State = MemberState.Active, Role = MemberRole.Manager }; await Database.Save(member); member = new Member() { Id = Guid.NewGuid().ToString(), CommunityId = Community2.Id, UserId = UserInfo1.Id, State = MemberState.Invited, Role = MemberRole.Member }; await Database.Save(member); member = new Member() { Id = Guid.NewGuid().ToString(), CommunityId = Community3.Id, UserId = UserInfo1.Id, State = MemberState.Active, Role = MemberRole.Member }; await Database.Save(member); member = new Member() { Id = Guid.NewGuid().ToString(), CommunityId = Community1.Id, UserId = UserInfo2.Id, State = MemberState.Active, Role = MemberRole.Member }; await Database.Save(member); member = new Member() { Id = Guid.NewGuid().ToString(), CommunityId = Community2.Id, UserId = UserInfo2.Id, State = MemberState.Uninvited, Role = MemberRole.Member }; await Database.Save(member); }
public void Add(string series, Bar bar) { DataManager.Add(this, series, bar); }
public async Task ReturnsOnlyUndeletedRecords() { var options = Utils.GetOptions(nameof(ReturnsOnlyUndeletedRecords)); var barList = new List <Bar>(); for (int i = 1; i <= 3; i++) { var bar = new Bar() { Name = "BestBar" + i, Rating = 4, TimesRated = 1, ImageSrc = null, IsDeleted = false, Address = "Street " + i, Country = "България", District = "District " + i, Email = "*****@*****.**", Phone = "+ " + i + "8888888", Town = "София", LocationId = null, }; if (i % 2 != 0) { bar.IsDeleted = true; } barList.Add(bar); } using (var context = new BCcontext(options)) { await context.Bars.AddRangeAsync(barList); await context.SaveChangesAsync(); } var mockMapper = new Mock <IBarMapper>(); mockMapper.Setup((x) => x.MapEntityToDTO(It.IsAny <Bar>())) .Returns((Bar b) => new BarDTO() { Id = b.Id, Name = b.Name, Rating = b.Rating, TimesRated = b.TimesRated, ImageSrc = b.ImageSrc, IsDeleted = b.IsDeleted, Address = b.Address, Country = b.Country, District = b.District, Email = b.Email, LocationId = b.LocationId, Phone = b.Phone, Town = b.Town }); var http = new Mock <IHttpClientFactory>(); var coctailMapper = new Mock <ICocktailMapper>(); //Act & Assert using (var context = new BCcontext(options)) { var sut = new BarsService(context, mockMapper.Object, http.Object, coctailMapper.Object); var result = await sut.GetBestBarsAsync(); Assert.AreEqual(result.Count(), 1); Assert.AreEqual(result.Any(b => b.IsDeleted == true), false); } }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ProjectExplorer)); this.barManager1 = new DevExpress.XtraBars.BarManager(); this.bar1 = new DevExpress.XtraBars.Bar(); this.barStaticItem1 = new DevExpress.XtraBars.BarStaticItem(); this.barFileView = new DevExpress.XtraBars.BarCheckItem(); this.barObjectView = new DevExpress.XtraBars.BarCheckItem(); this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem2 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem3 = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.barButtonItem4 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem5 = new DevExpress.XtraBars.BarButtonItem(); this.tagTree = new Prometheus.Controls.MultiSyncTreeView(); this.tagContainerPopup = new DevExpress.XtraBars.PopupMenu(); this.tagObjectPopup = new DevExpress.XtraBars.PopupMenu(); this.baseTagPopup = new DevExpress.XtraBars.PopupMenu(); this.barButtonItem6 = new DevExpress.XtraBars.BarButtonItem(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tagContainerPopup)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tagObjectPopup)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.baseTagPopup)).BeginInit(); this.SuspendLayout(); // // barManager1 // this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar1 }); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.barStaticItem1, this.barFileView, this.barObjectView, this.barButtonItem1, this.barButtonItem2, this.barButtonItem3, this.barButtonItem4, this.barButtonItem5, this.barButtonItem6 }); this.barManager1.MaxItemId = 12; // // bar1 // this.bar1.BarName = "Custom 1"; this.bar1.DockCol = 0; this.bar1.DockRow = 1; this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barStaticItem1), new DevExpress.XtraBars.LinkPersistInfo(this.barFileView), new DevExpress.XtraBars.LinkPersistInfo(this.barObjectView), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1, true), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem2), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem3) }); this.bar1.OptionsBar.AllowQuickCustomization = false; this.bar1.OptionsBar.DisableClose = true; this.bar1.OptionsBar.DisableCustomization = true; this.bar1.OptionsBar.DrawDragBorder = false; this.bar1.OptionsBar.UseWholeRow = true; this.bar1.Text = "Custom 1"; // // barStaticItem1 // this.barStaticItem1.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; this.barStaticItem1.Caption = "View: "; this.barStaticItem1.Id = 0; this.barStaticItem1.Name = "barStaticItem1"; this.barStaticItem1.TextAlignment = System.Drawing.StringAlignment.Near; // // barFileView // this.barFileView.Caption = "File View"; this.barFileView.Checked = true; this.barFileView.Glyph = ((System.Drawing.Image)(resources.GetObject("barFileView.Glyph"))); this.barFileView.GroupIndex = 1; this.barFileView.Id = 1; this.barFileView.Name = "barFileView"; // // barObjectView // this.barObjectView.Caption = "Object View"; this.barObjectView.Glyph = ((System.Drawing.Image)(resources.GetObject("barObjectView.Glyph"))); this.barObjectView.GroupIndex = 1; this.barObjectView.Id = 2; this.barObjectView.Name = "barObjectView"; // // barButtonItem1 // this.barButtonItem1.Caption = "barButtonItem1"; this.barButtonItem1.Glyph = ((System.Drawing.Image)(resources.GetObject("barButtonItem1.Glyph"))); this.barButtonItem1.Id = 6; this.barButtonItem1.Name = "barButtonItem1"; // // barButtonItem2 // this.barButtonItem2.Caption = "barButtonItem2"; this.barButtonItem2.Glyph = ((System.Drawing.Image)(resources.GetObject("barButtonItem2.Glyph"))); this.barButtonItem2.Id = 7; this.barButtonItem2.Name = "barButtonItem2"; // // barButtonItem3 // this.barButtonItem3.Caption = "barButtonItem3"; this.barButtonItem3.Glyph = ((System.Drawing.Image)(resources.GetObject("barButtonItem3.Glyph"))); this.barButtonItem3.Id = 8; this.barButtonItem3.Name = "barButtonItem3"; // // barButtonItem4 // this.barButtonItem4.Caption = "Container Test Item"; this.barButtonItem4.Id = 9; this.barButtonItem4.Name = "barButtonItem4"; // // barButtonItem5 // this.barButtonItem5.Caption = "Object Test Item"; this.barButtonItem5.Id = 10; this.barButtonItem5.Name = "barButtonItem5"; // // tagTree // this.tagTree.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tagTree.ImageIndex = -1; this.tagTree.Location = new System.Drawing.Point(8, 32); this.tagTree.Name = "tagTree"; this.tagTree.SelectedImageIndex = -1; this.tagTree.ShowFiles = true; this.tagTree.Size = new System.Drawing.Size(168, 328); this.tagTree.TabIndex = 4; // // tagContainerPopup // this.tagContainerPopup.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem4) }); this.tagContainerPopup.Manager = this.barManager1; this.tagContainerPopup.Name = "tagContainerPopup"; // // tagObjectPopup // this.tagObjectPopup.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem5) }); this.tagObjectPopup.Manager = this.barManager1; this.tagObjectPopup.Name = "tagObjectPopup"; // // baseTagPopup // this.baseTagPopup.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem6) }); this.baseTagPopup.Manager = this.barManager1; this.baseTagPopup.Name = "baseTagPopup"; // // barButtonItem6 // this.barButtonItem6.Caption = "This is definately a base tag!"; this.barButtonItem6.Glyph = ((System.Drawing.Image)(resources.GetObject("barButtonItem6.Glyph"))); this.barButtonItem6.Id = 11; this.barButtonItem6.Name = "barButtonItem6"; // // ProjectExplorer // this.Controls.Add(this.tagTree); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "ProjectExplorer"; this.Size = new System.Drawing.Size(184, 368); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tagContainerPopup)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tagObjectPopup)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.baseTagPopup)).EndInit(); this.ResumeLayout(false); }
public void Add(Bar bar) { DataManager.Add(this, bar); }
public Foo() { StaticBar = new Bar(); }
protected override sealed TNotNamed NumbersTest<T>(ref Foo foo, out Bar @class, params ArrayOfSomething[] somethings) where T : event, IDisposable, IFoo {
/// <summary> /// refer: https://www.cnblogs.com/kulong995/p/5237796.html /// </summary> /// <returns></returns> public static string TemperatureBar() { ChartOption option = new ChartOption(); option.Title().Text("温度计式图表").Subtext("Form ExcelHome"). Sublink("http://e.weibo.com/1341556070/AizJXrAEa"); option.ToolTip().Trigger(TriggerType.axis) // 原作者嘅 code,好似有 bug,暫時取消 //.Formatter(new JRaw(@"function (params){ // return params[0].name + '<br/>' // + params[0].seriesName + ' : ' + params[0].value + '<br/>' // + params[1].seriesName + ' : ' + (params[1].value + params[0].value); // }")) .AxisPointer().Type(AxisPointType.shadow); option.Legend().Data("Acutal", "Forecast"); Feature feature = new Feature(); feature.Mark().Show(true); feature.DataView().Show(true).ReadOnly(false); feature.Restore().Show(true); feature.SaveAsImage().Show(true); option.ToolBox().Show(true).SetFeature(feature); option.Grid().Y(80).Y2(30); CategoryAxis x = new CategoryAxis(); x.Data("Cosco", "CMA", "APL", "OOCL", "Wanhai", "Zim"); option.XAxis(x); ValueAxis y = new ValueAxis(); y.BoundaryGap(new List <double>() { 0, 0.1 }); option.YAxis(y); var tomatoStyle = new ItemStyle(); tomatoStyle.Normal().Color("tomato").BarBorderRadius(0) .BarBorderColor("tomato").BarBorderWidth(6) .Label().Show(true).Position(StyleLabelType.insideTop); Bar b1 = new Bar("Acutal"); b1.Stack("sum"); b1.SetItemStyle(tomatoStyle); b1.Data(260, 200, 220, 120, 100, 80); var forecastStyle = new ItemStyle(); var pattern = @"(""(?:[^""\\]|\\.)*"")|\s+"; // remove space and CRLF var raw = @"function (params) {for (var i = 0, l = option.xAxis[0].data.length; i < l; i++) {if (option.xAxis[0].data[i] == params.name) {return option.series[0].data[i] + params.value;}}}"; var formatter = string.Format(@"eval(""{0}"")", raw); var tmp = new JRaw(raw); //! HACK: Formatter 去到 EChartsBox.html script 會出 JSON.parse error forecastStyle.Normal().Color("#fff").BarBorderRadius(0) .BarBorderColor("tomato").BarBorderWidth(6) .Label().Show(true).Position(StyleLabelType.top) .Formatter(new JRaw(@"function (params) { for (var i = 0, l = option.xAxis[0].data.length; i < l; i++) { if (option.xAxis[0].data[i] == params.name) { return option.series[0].data[i] + params.value; } } }")) //.Formatter(new JRaw(formatter)) .TextStyle().Color("tomato"); Bar b2 = new Bar("Forecast"); b2.Stack("sum"); b2.SetItemStyle(forecastStyle); b2.Data(40, 80, 50, 80, 80, 70); option.Series(b1, b2); var result = JsonHelper.ObjectToJson2(option); return(result); }
public unsafe void TestCodeGeneration() { #pragma warning disable 0168 // warning CS0168: The variable `foo' is declared but never used #pragma warning disable 0219 // warning CS0219: The variable `foo' is assigned but its value is never used using (var changedAccessOfInheritedProperty = new ChangedAccessOfInheritedProperty()) { Assert.That(changedAccessOfInheritedProperty.Property, Is.EqualTo(2)); } Foo.NestedAbstract a; var renamedEmptyEnum = Foo.RenamedEmptyEnum.EmptyEnum1; using (var foo = new Foo()) { Bar bar = foo; Assert.IsTrue(Bar.Item.Item1 == bar); using (var hasOverloadsWithDifferentPointerKindsToSameType = new HasOverloadsWithDifferentPointerKindsToSameType()) { hasOverloadsWithDifferentPointerKindsToSameType.Overload(foo, 0); using (var foo2 = new Foo2()) hasOverloadsWithDifferentPointerKindsToSameType.Overload(foo2, 0); } } using (var overridesNonDirectVirtual = new OverridesNonDirectVirtual()) { using (var foo = new Foo()) { Assert.That(overridesNonDirectVirtual.RetInt(foo), Is.EqualTo(3)); Assert.That(foo.FooPtr, Is.EqualTo(1)); } } using (var derivedFromTemplateInstantiationWithVirtual = new DerivedFromTemplateInstantiationWithVirtual()) { } using (var hasProtectedEnum = new HasProtectedEnum()) { } using (var hasPropertyNamedAsParent = new HasPropertyNamedAsParent()) { hasPropertyNamedAsParent.hasPropertyNamedAsParent.GetHashCode(); } EnumWithUnderscores e = EnumWithUnderscores.lOWER_BEFORE_CAPITAL; e = EnumWithUnderscores.UnderscoreAtEnd; e = EnumWithUnderscores.CAPITALS_More; e = EnumWithUnderscores.UsesDigits1_0; e.GetHashCode(); ItemsDifferByCase itemsDifferByCase = ItemsDifferByCase.Case_a; itemsDifferByCase = ItemsDifferByCase.CaseA; itemsDifferByCase.GetHashCode(); new AmbiguousParamNames(0, 0).Dispose(); Common.SMallFollowedByCapital(); Common.IntegerOverload(0); Common.IntegerOverload((uint)0); Common.TakeVoidStarStar(null); Common.OverloadPointer(IntPtr.Zero, 1); using (new DerivedFromSecondaryBaseWithIgnoredVirtualMethod()) { } #pragma warning restore 0168 #pragma warning restore 0219 }