public Trade[] GetAllTrades(QueryRule query, IList<string> filterOutTrades) { var allTrades = TradeRepository.GetAllTrades(query); if (allTrades != null && allTrades.Length > 0 && filterOutTrades != null && filterOutTrades.Count > 0) { var tempMapper = new Dictionary<string, Trade>(); foreach(var item in allTrades) { tempMapper[item.Id] = item; } foreach(var item in filterOutTrades) { tempMapper.Remove(item); } var values = tempMapper.Values; allTrades = new Trade[values.Count]; values.CopyTo(allTrades, 0); } return allTrades; }
protected string GetClearingID(Trade trade, string name) { // find which allocation number we are var allocNo = GetAllocationNo(trade); // there are number of entries for each allocation, need to find the one with clearing ID int entryNo = 1; bool found = true; do { var eventProperty = String.Format("{0}:{1}:{2}", sConfirmRegReportingEvent, allocNo, entryNo); var typeProperty = String.Format("{0}:{1}:{2}", sConfirmRegReportingType, allocNo, entryNo); if(!trade.Properties.ContainsKey(eventProperty) || !trade.Properties.ContainsKey(typeProperty)) { found = false; } else { var eventValue = trade.GetProperty(eventProperty); var typeValue = trade.GetProperty(typeProperty); if(eventValue == "2" && typeValue == "0") { // this is it, Event = Clearing, Type = Current var propertyToRetrieve = String.Format("{0}:{1}:{2}", name, allocNo, entryNo); return trade.GetProperty(propertyToRetrieve); } } entryNo++; } while (found); return String.Empty; }
public override void GotFill(Trade fill) { // make sure fills are tracked as positions pt.Adjust(fill); // send profit order for this new position sendoffset(fill.symbol); }
/* * Copied from Orchestrade TradeBlotterData.cs * Changed signatures, etc. slightly to fit into this class * Required because Orchestrade did not want us to use the TradeBlotter API directly for exports * */ public static String GetPayerReceiver(Trade trade) { if (trade.Product == null) return null; if (trade.Product is Swap) return ((Swap)trade.Product).PayLeg.IsFixedRate ? "Payer" : "Receiver"; if (trade.Product is InflationSwap) return ((InflationSwap)trade.Product).IsPay ? "Payer" : "Receiver"; if (trade.Product is Swaption) { var sw = trade.Product as Swaption; return sw.OptionType == OptionType.Call ? "Receiver" : "Payer"; } if (trade.Product is CapFloor) { var cf = trade.Product as CapFloor; return cf.Leg.IsPay ? "Payer" : "Receiver"; } if (trade.Product is FRA) { var cf = trade.Product as FRA; return cf.IsPay ? "Payer" : "Receiver"; } if (trade.Product is VarSwap) { var cf = trade.Product as VarSwap; return cf.IsBuy ? "Payer" : "Receiver"; } return null; }
public void GotFill(Trade fill) { D("fill: "+fill.ToString()); pt.Adjust(fill); decimal openpl = Calc.OpenPL(pairs.Aprice, pt[pairs.Asym]) + Calc.OpenPL(pairs.Bprice, pt[pairs.Bsym]); if ((openpl > 200) || (openpl< -100)) shutdown(); }
// these are for calculating closed pl // they do not adjust positions themselves /// <summary> /// Gets the closed PL on a per-share basis, ignoring how many shares are held. /// </summary> /// <param name="existing">The existing position.</param> /// <param name="closing">The portion of the position that's being closed/changed.</param> /// <returns></returns> public static decimal ClosePT(Position existing, Trade adjust) { if (!existing.isValid || !adjust.isValid) throw new Exception("Invalid position provided. (existing:" + existing.ToString() + " adjustment:" + adjust.ToString()); if (existing.isFlat) return 0; // nothing to close if (existing.isLong == adjust.side) return 0; // if we're adding, nothing to close return existing.isLong ? adjust.xprice- existing.AvgPrice: existing.AvgPrice- adjust.xprice; }
public void TestMinimumAmounts() { Trade sale = new Trade(sunshine, 10.0f, 100, 60); Transaction t1 = new Transaction(p1, sale); // Quantity // Cost // Volume }
/// <summary> /// pass fills through here /// </summary> /// <param name="t"></param> public void GotFill(Trade t) { if (SendLatency == null) return; // see if we know this message long start = 0; if (!_otime.TryGetValue(t.id, out start)) return; double lat = new System.DateTime(gettime()).Subtract(new System.DateTime(start)).TotalMilliseconds; report(MessageTypes.EXECUTENOTIFY, t.id, lat); }
public void TestFixtureSetUp() { sunshine = new ItemType(1, "Sunshine", 1.0f); cheap = new Trade(sunshine, 1.0f, 1000); expensive = new Trade(sunshine, 1000.0f, 1000); oneCheap = new Trade(sunshine, 1.0f, 1); oneExpensive = new Trade(sunshine, 1000.0f, 1); zero = new Trade(null, 0.0f, 0); }
public void TestConstructor() { Trade trade = new Trade(sunshine, 100.0f, 100); TransactionItem t1 = new TransactionItem(trade); TransactionItem t2 = new TransactionItem(trade, 50); TransactionItem t3 = new TransactionItem(trade, 150); Assert.AreEqual(100, t1.Quantity); Assert.AreEqual(50, t2.Quantity); Assert.AreEqual(100, t3.Quantity); }
public override bool IsExcluded(ProductEvent pevent, Trade trade, Market market) { var isExcluded = base.IsExcluded(pevent, trade, market); if (isExcluded) return true; if (trade.Product is Swap) { var swap = trade.Product as Swap; if (swap.PayLeg.IsFixedRate && swap.ReceiveLeg.IsFixedRate) return true; } return false; }
public static double GetNominal(Trade trade) { if (trade.Product != null) { if (trade.Product.IsMultiplyTraded) return trade.Quantity * trade.Product.Nominal; string ss = trade.Product.GetBuySell(trade); if (ss == null) return trade.Product.Nominal; return ss.Equals("Sell") ? Math.Abs(trade.Product.Nominal) * -1 : Math.Abs(trade.Product.Nominal); } return 0; }
static void Main() { // creating AAPL security var security = new Security { Id = "AAPL@NASDAQ", PriceStep = 0.1m, Decimals = 1, }; var trades = new List<Trade>(); // generation 1000 random ticks // for (var i = 0; i < 1000; i++) { var t = new Trade { Time = DateTime.Today + TimeSpan.FromMinutes(i), Id = i + 1, Security = security, Volume = RandomGen.GetInt(1, 10), Price = RandomGen.GetInt(1, 100) * security.PriceStep ?? 1m + 99 }; trades.Add(t); } using (var drive = new LocalMarketDataDrive()) { // get AAPL storage var aaplStorage = drive.GetSecurityDrive(security); // get tick storage var tradeStorage = (IMarketDataStorage<Trade>)aaplStorage.GetTickStorage(new CsvMarketDataSerializer<ExecutionMessage>()); // saving ticks tradeStorage.Save(trades); // loading ticks var loadedTrades = tradeStorage.Load(DateTime.Today, DateTime.Today + TimeSpan.FromMinutes(1000)); foreach (var trade in loadedTrades) { Console.WriteLine(LocalizedStrings.Str2968Params, trade.Id, trade); } Console.ReadLine(); // deleting ticks (and removing file) tradeStorage.Delete(DateTime.Today, DateTime.Today + TimeSpan.FromMinutes(1000)); } }
private void EmitNewTradeEvent(IFIXInstrument instrument, Trade trade) { if (NewTrade != null) { NewTrade(this, new TradeEventArgs(trade, instrument, this)); } if (factory != null) { factory.OnNewTrade(instrument, trade); } }
/// <summary> /// Adjust an existing position, or create new one if none exists. /// </summary> /// <param name="fill"></param> /// <returns>any closed PL for adjustment</returns> public decimal Adjust(Trade fill) { Position p; decimal cpl = 0; if (posdict.TryGetValue(fill.symbol, out p)) cpl += posdict[fill.symbol].Adjust(fill); else posdict.Add(fill.symbol, new PositionImpl(fill)); _totalclosedpl += cpl; return cpl; }
public bool Check(Trade trade) { Boolean result = true; var entity = Env.Current.StaticData.GetPartyById(trade.EntityId).Code; if (entity.Equals("SMF") && trade.Product.ProcessingType.Equals("FX") && trade.Product.UnderlierInfo.Equals("FX:USD:IDR")) { trade.SetProperty("OverridePB", "CGMI_PB_FI"); } return result; }
public static AccountActivity NewTrade(Trade f, Position p) { var aa = new AccountActivity(); aa.CurrentPos = p; aa.symbol = f.symbol; aa.side = f.xsize > 0; aa.id = f.id; aa.price = f.xprice; aa.size = f.xsize; aa.type = ActivityType.Fill; return aa; }
public void TestFixtureSetUp() { sunshine = new ItemType(1, "Sunshine", 1.5f); p1 = new Trade(sunshine, 1.0f, 100); p2 = new Trade(sunshine, 10.0f, 10); s1 = new Trade(sunshine, 5.0f, 100); s2 = new Trade(sunshine, 50.0f, 100); pt1 = new TransactionItem(p1); pt2 = new TransactionItem(p2); st1 = new TransactionItem(s1); st2 = new TransactionItem(s2); }
public override bool Reconcile(Trade otTrade, Trade externalTrade, Market market, bool fullMatch, DateTime reconciliationDate, IList<Exception> exceps) { var unmatchReason = string.Empty; var ref1 = otTrade.GetProperty(ReconcileTaskExecutor.Reconciled); if (ref1 != null && ref1.ToLowerInvariant().Equals("true")) return false; var ref2 = externalTrade.GetProperty(ReconcileTaskExecutor.Reconciled); if (ref2 != null && ref2.ToLowerInvariant().Equals("true")) return false; if (!(otTrade.Product.GetType() == externalTrade.Product.GetType())) return false; if (otTrade.BookId != externalTrade.BookId) return false; if (otTrade.PrimeBrokerId != externalTrade.PrimeBrokerId && otTrade.ClearerId != externalTrade.ClearerId) { if (fullMatch) return false; unmatchReason += "Account "; } var prod1 = otTrade.Product; var prod2 = externalTrade.Product; var fut1 = prod1 as Future; var fut2 = prod2 as Future; if (fut1 != null && fut2 != null) { var ticker1 = fut1.Ticker; var ticker2 = fut2.Ticker; if (!string.IsNullOrEmpty(ticker1) && !string.IsNullOrEmpty(ticker2)) { if (!ticker1.Equals(ticker2)) return false; } } var fx1 = prod1 as FX; var fx2 = prod2 as FX; if (fx1 != null && fx2 != null) { if (!fx1.CurrencyPair.Equals(fx2.CurrencyPair)) return false; if (fullMatch) { if (Math.Abs(fx1.PrimaryAmount - fx2.PrimaryAmount) > Utilities.Epsilon) return false; if (Math.Abs(fx1.QuotingAmount - fx2.QuotingAmount) > Utilities.Epsilon) return false; } return true; } if (prod1 is Bond || prod1 is Equity) { if (prod1.Id != prod2.Id) return false; } if (fullMatch) { if (Math.Abs(otTrade.Quantity - externalTrade.Quantity) > Utilities.Epsilon) return false; } return true; }
static void Main() { // создаем тестовый инструмент var security = new Security { Id = "TestId", PriceStep = 0.1m, Decimals = 1, }; var trades = new List<Trade>(); // генерируем 1000 произвольных сделок // for (var i = 0; i < 1000; i++) { var t = new Trade { Time = DateTime.Today + TimeSpan.FromMinutes(i), Id = i + 1, Security = security, Volume = RandomGen.GetInt(1, 10), Price = RandomGen.GetInt(1, 100) * security.PriceStep ?? 1m + 99 }; trades.Add(t); } var storage = new StorageRegistry(); // получаем хранилище для тиковых сделок var tradeStorage = storage.GetTradeStorage(security); // сохраняем сделки tradeStorage.Save(trades); // загружаем сделки var loadedTrades = tradeStorage.Load(DateTime.Today, DateTime.Today + TimeSpan.FromMinutes(1000)); foreach (var trade in loadedTrades) { Console.WriteLine(LocalizedStrings.Str2968Params, trade.Id, trade); } Console.ReadLine(); // удаляем сделки (очищаем файл) tradeStorage.Delete(DateTime.Today, DateTime.Today + TimeSpan.FromMinutes(1000)); }
public static double GetSettlementAmount(Trade trade) { if (trade.SettleAmount != 0) return trade.SettleAmount; var pr = trade.Product; if (pr is IPremiumScheduleBased) { var prems = (pr as IPremiumScheduleBased).Premium; if (prems != null && prems.Count > 0) { return prems[0].SignedAmount; } } return 0; }
/// <summary> /// Adjust an existing position, or create new one if none exists. /// </summary> /// <param name="fill"></param> /// <returns>any closed PL for adjustment</returns> public decimal Adjust(Trade fill) { Position p; decimal cpl = 0; int idx = -1; if (_symidx.TryGetValue(fill.symbol, out idx)) cpl += _poslist[idx].Adjust(fill); else { _poslist.Add(new PositionImpl(fill)); _symidx.Add(fill.symbol, _poslist.Count - 1); } _totalclosedpl += cpl; return cpl; }
public static Invoice createInvoice () { ZfDate today = new ZfDateDay (); ZfDate nextMonth = new ZfDateMonth (DateUtils.addMonths (today, 1)); Invoice invoice = new Invoice (ConformanceLevel.BASIC); // <1> invoice.setHeader(new Header() .setInvoiceNumber("20131122-42") .setCode(DocumentCode._380) .setIssued(today) .addNote(new Note("MFG")) .setName ("Rechnung")); Trade trade = new Trade (); trade.setAgreement (new Agreement () // <2> .setSeller (new TradeParty () .setName ("Seller Inc.") .setAddress (new Address ("80331", "Marienplatz 1", "München", Country.DE)) .addTaxRegistrations (new TaxRegistration ("DE122...", Reference.FC))) .setBuyer (new TradeParty () .setName ("Buyer Inc.") .setAddress (new Address ("50667", "Domkloster 4", "Köln", Country.DE)) .addTaxRegistrations (new TaxRegistration ("DE123...", Reference.FC)))); trade.setDelivery (new Delivery (nextMonth)); trade.setSettlement (new Settlement () .setPaymentReference ("20131122-42") .setCurrency (Currency.EUR) .addPaymentMeans (new PaymentMeans () .setPayeeAccount (new CreditorFinancialAccount ("DE01234..")) .setPayeeInstitution (new FinancialInstitution ("GENO..."))) .setMonetarySummation (new MonetarySummation () .setLineTotal (new Amount (100, Currency.EUR)) .setChargeTotal (new Amount (0, Currency.EUR)) .setAllowanceTotal (new Amount (0, Currency.EUR)) .setTaxBasisTotal (new Amount (100, Currency.EUR)) .setTaxTotal (new Amount (19, Currency.EUR)) .setGrandTotal (new Amount (119, Currency.EUR)))); trade.addItem (new Item () .setProduct (new Product ().setName ("Saddle")) .setDelivery (new SpecifiedDelivery (new Quantity (1, UnitOfMeasurement.UNIT)))); invoice.setTrade (trade); return invoice; }
public TradeImpl(Trade copytrade) { // copy constructor, for copying using by-value (rather than by default of by-reference) id = copytrade.id; cur = copytrade.Currency; type = copytrade.Security; ex = copytrade.ex; accountid = copytrade.Account; symbol = copytrade.symbol; side = copytrade.side; comment = copytrade.comment; xsize = copytrade.xsize; xprice = copytrade.xprice; xtime = copytrade.xtime; xdate = copytrade.xdate; }
void BeginSimulation() { int counter = 0; for (int i = 0; i < 1000000; i++) { counter++; Trade trade = new Trade(); trade.Counter = counter; trade.Price = _rand.NextDouble(); AddNewTrade(trade); Thread.Sleep(1); } }
public static double GetCurrentNominal(Trade trade, SimpleDate date, DateTime effectiveDate) { if (trade.Product != null) { var nominal = Math.Abs(trade.CurrentNominal(date, effectiveDate, false)); int sign = 1; if (trade.Product.IsMultiplyTraded) sign = trade.Quantity > 0 ? 1 : -1; else { string ss = trade.Product.GetBuySell(trade); if (ss != null && ss.Equals("Sell")) sign = -1; } return sign * nominal; } return 0; }
public bool Check(Trade trade, StringBuilder msg) { var bond = trade.Product as Bond; //Is this a Sell of a EUR BOND trade.RemoveProperty(PropName); if (trade.Quantity < 0 && bond != null && bond.Currency.Equals("EUR")) { //Need to notify user to check Funding if (MessageBox.Show("Please check funding for this Bond " + bond.Description + " " + bond.Isin, "Check EUR Funding", MessageBoxButtons.OKCancel) == DialogResult.Cancel) { return false; } trade.SetProperty(PropName, "true"); } return true; }
public void Pass_in_arguments_as_dictionary() { ObjectFactory.Initialize(x => { x.ForRequestedType<IView>().TheDefaultIsConcreteType<View>(); }); var theNode = new Node(); var theTrade = new Trade(); var args = new ExplicitArguments(); args.Set(theNode); args.SetArg("trade", theTrade); var command = ObjectFactory.GetInstance<Command>(args); Assert.IsInstanceOfType(typeof (View), command.View); Assert.AreSame(theNode, command.Node); Assert.AreSame(theTrade, command.Trade); }
public bool Check(Trade trade) { var result = false; var user = Env.Current.Admin.GetUserById(SessionHelper.UserId); var isAuthorized = false; String message = null; if (trade.TradingSystem == null || string.IsNullOrWhiteSpace(trade.TradingSystem)) { if (isAuthorized || (trade.InputUserId == SessionHelper.UserId && trade.TradeTime.Date.Equals(new DateTime().Date))) result = true; else { message = "** Only the user who originally booked the trade (only at T) or Operation can cancel it."; result = false; } } else { var test = DateTime.Today; test = trade.TradeTime; test = trade.TradeTime.Date; if (isAuthorized && trade.TradeTime.Date.Equals(DateTime.Today)) result = true; else { if (isAuthorized && user.Name != "orchestra") return true; else { message = "** Only Operation can cancel a trade coming from an electronic platform trades."; result = false; } } } if (!result) { result = false; } return result; }
private void EmitNewTradeEvent(IFIXInstrument instrument, Trade trade) { if (this.MarketDataFilter != null) { trade = this.MarketDataFilter.FilterTrade(trade, instrument.Symbol); } if (trade != null) { if (NewTrade != null) { NewTrade(this, new TradeEventArgs(trade, instrument, this)); } if (factory != null) { factory.OnNewTrade(instrument, trade); } } }
// Use this for initialization void Start () { GameManager = GameObject.Find ("GameManager"); _GM = GameManager.gameObject.GetComponent( typeof(Game_Manager) ) as Game_Manager; _Player = GameManager.gameObject.GetComponent( typeof(Player) ) as Player; _Ship = GameManager.gameObject.GetComponent( typeof(Ship) ) as Ship; _Warehouse = GameManager.gameObject.GetComponent( typeof(Warehouse) ) as Warehouse; _Trade = GameManager.gameObject.GetComponent( typeof(Trade) ) as Trade; Yes_Canvas = Yes_Canvas.GetComponent<Canvas> (); No_Canvas = No_Canvas.GetComponent<Canvas> (); All_Canvas = All_Canvas.GetComponent<Canvas> (); None_Canvas = None_Canvas.GetComponent<Canvas> (); None1_Canvas = None1_Canvas.GetComponent<Canvas> (); Del_Canvas = Del_Canvas.GetComponent<Canvas> (); Enter_Canvas = Enter_Canvas.GetComponent<Canvas> (); One_Canvas = One_Canvas.GetComponent<Canvas> (); Two_Canvas = Two_Canvas.GetComponent<Canvas> (); Three_Canvas = Three_Canvas.GetComponent<Canvas> (); Four_Canvas = Four_Canvas.GetComponent<Canvas> (); Five_Canvas = Five_Canvas.GetComponent<Canvas> (); Six_Canvas = Six_Canvas.GetComponent<Canvas> (); Seven_Canvas = Seven_Canvas.GetComponent<Canvas> (); Eight_Canvas = Eight_Canvas.GetComponent<Canvas> (); Nine_Canvas = Nine_Canvas.GetComponent<Canvas> (); Zero_Canvas = Zero_Canvas.GetComponent<Canvas> (); Six_Canvas = Six_Canvas.GetComponent<Canvas> (); Seven_Canvas = Seven_Canvas.GetComponent<Canvas> (); Eight_Canvas = Eight_Canvas.GetComponent<Canvas> (); Nine_Canvas = Nine_Canvas.GetComponent<Canvas> (); Zero_Canvas = Zero_Canvas.GetComponent<Canvas> (); Buy_Canvas = Buy_Canvas.GetComponent<Canvas> (); Sell_Canvas = Sell_Canvas.GetComponent<Canvas> (); QuitTrading_Canvas = QuitTrading_Canvas.GetComponent<Canvas> (); TransferCargo_Canvas = TransferCargo_Canvas.GetComponent<Canvas> (); VisitBank_Canvas = VisitBank_Canvas.GetComponent<Canvas> (); General_Canvas = General_Canvas.GetComponent<Canvas> (); Arms_Canvas = Arms_Canvas.GetComponent<Canvas> (); Silk_Canvas = Silk_Canvas.GetComponent<Canvas> (); Opium_Canvas = Opium_Canvas.GetComponent<Canvas> (); HongKong_Canvas = HongKong_Canvas.GetComponent<Canvas> (); Shanghai_Canvas = Shanghai_Canvas.GetComponent<Canvas> (); Nagasaki_Canvas = Nagasaki_Canvas.GetComponent<Canvas> (); Saigon_Canvas = Saigon_Canvas.GetComponent<Canvas> (); Manila_Canvas = Manila_Canvas.GetComponent<Canvas> (); Singapore_Canvas = Singapore_Canvas.GetComponent<Canvas> (); Batavia_Canvas = Batavia_Canvas.GetComponent <Canvas> (); Places_Canvas = Places_Canvas.GetComponent <Canvas> (); Amount = Amount.GetComponent<Canvas> (); Amount.enabled = false; All_Canvas.enabled = false; None_Canvas.enabled = false; None1_Canvas.enabled = false; Del_Canvas.enabled = false; Enter_Canvas.enabled = false; One_Canvas.enabled = false; Two_Canvas.enabled = false; Three_Canvas.enabled = false; Four_Canvas.enabled = false; Five_Canvas.enabled = false; Six_Canvas.enabled = false; Seven_Canvas.enabled = false; Eight_Canvas.enabled = false; Nine_Canvas.enabled = false; Zero_Canvas.enabled = false; Buy_Canvas.enabled = false; Sell_Canvas.enabled = false; QuitTrading_Canvas.enabled = false; TransferCargo_Canvas.enabled = false; VisitBank_Canvas.enabled = false; General_Canvas.enabled = false; Silk_Canvas.enabled = false; Arms_Canvas.enabled = false; Opium_Canvas.enabled = false; HongKong_Canvas.enabled = false; Shanghai_Canvas.enabled = false; Nagasaki_Canvas.enabled = false; Saigon_Canvas.enabled = false; Manila_Canvas.enabled = false; Singapore_Canvas.enabled = false; Batavia_Canvas.enabled = false; Places_Canvas.enabled = false; Debt = Debt.GetComponent<Text> (); Cash = Cash.GetComponent<Text> (); Bank = Bank.GetComponent<Text> (); if (_GM.get_StartChoice () == 1) { GameState = "start"; Debug.Log (GameState); _Player.Cash = 400; Cash.text = _Player.Cash.ToString(); _Player.Debt = 5000; Debt.text = _Player.Debt.ToString(); Debug.Log ("Choice is 1"); } else { Debug.Log (GameState); _Ship.Guns = 5; Guns.text = _Ship.Guns.ToString(); Debt.text = "0"; } Location = Location.GetComponent<Text> (); Location.text = _Ship.Location; Vacant = Vacant.GetComponent<Text> (); Vacant.text = _Warehouse.Vacant.ToString(); Used = Used.GetComponent<Text> (); Used.text = _Warehouse.In_Use.ToString(); W_Opium = W_Opium.GetComponent<Text> (); W_Opium.text = _Warehouse.Opium.ToString(); W_Silk = W_Silk.GetComponent<Text> (); W_Silk.text = _Warehouse.Silk.ToString(); W_Arms = W_Arms.GetComponent<Text> (); W_Arms.text = _Warehouse.Arms.ToString(); W_Generals = W_Generals.GetComponent<Text> (); W_Generals.text = _Warehouse.General.ToString(); H_Opium = H_Opium.GetComponent<Text> (); H_Opium.text = _Ship.Opium.ToString(); H_Silk = H_Silk.GetComponent<Text> (); H_Silk.text = _Ship.Silk.ToString(); H_Arms = H_Arms.GetComponent<Text> (); H_Arms.text = _Ship.Arms.ToString(); H_Generals = H_Generals.GetComponent<Text> (); H_Generals.text = _Ship.General.ToString(); Hold = Hold.GetComponent<Text> (); Hold.text = _Ship.Hold.ToString(); Status = Status.GetComponent<Text> (); Status.text = _Ship.Status.ToString(); Guns = Guns.GetComponent<Text> (); Guns.text = _Ship.Guns.ToString(); Firm = Firm.GetComponent<Text> (); if(_GM.get_PlayerName() == ""){ _GM.set_PlayerName ("Nobel House"); } Firm.text = FirmText + " " + _GM.get_PlayerName() + ", " + _Ship.Location; _Player.Donation = Random.Range (5, 200); Debug.Log (_Player.Donation); Report.text = ReportText + ReportText2 + _Player.Donation + ReportText3; }
//=========================================================================== protected override void NewBar() { DTime = Bars[ci].Time; ci = Bars.Range.To - 1; //==== Fractal ==================================================================================== if (_frInd.TopSeries[Bars.Range.To - frac] > 0) { if (frU) { frU = false; frU3 = frU2; frU2 = frU1; frU1 = _frInd.TopSeries[Bars.Range.To - frac]; tmU3 = tmU2; tmU2 = tmU1; tmU1 = Bars[Bars.Range.To - frac].Time; } else { if (_frInd.TopSeries[Bars.Range.To - frac] > frU1) { frU1 = _frInd.TopSeries[Bars.Range.To - frac]; tmU1 = Bars[Bars.Range.To - frac].Time; } } XXPrint("{0} - frU1={1} frU2={2} frU3={3} frD1={4} frD2={5} frD3={6} nkz4={7} nkz2={8} tu={9} td={10} dl={11} frac={12}", Bars[Bars.Range.To - frac].Time, frU1, frU2, frU3, frD1, frD2, frD3, nkz4, nkz2, tu, td, dl, frac); } if (_frInd.BottomSeries[Bars.Range.To - frac] > 0) { if (!frU) { frU = true; frD3 = frD2; frD2 = frD1; frD1 = _frInd.BottomSeries[Bars.Range.To - frac]; tmD3 = tmD2; tmD2 = tmD1; tmD1 = Bars[Bars.Range.To - frac].Time; } else { if (_frInd.BottomSeries[Bars.Range.To - frac] < frD1) { frD1 = _frInd.BottomSeries[Bars.Range.To - frac]; tmD1 = Bars[Bars.Range.To - frac].Time; } } XXPrint("{0} - frU1={1} frU2={2} frU3={3} frD1={4} frD2={5} frD3={6} nkz4={7} nkz2={8} tu={9} td={10} dl={11} frac={12}", Bars[Bars.Range.To - frac].Time, frU1, frU2, frU3, frD1, frD2, frD3, nkz4, nkz2, tu, td, dl, frac); } // Первое начиртание зон ===================================================================================== if (k == 0) { // Индекс свечипоследнего nu = false; nd = false; if (tu) { zmax = dt1 * Instrument.Point; nkz4 = zmax - ((NKZ - 5 - (NKZ * kf)) * Instrument.Point); nkz2 = zmax - (((NKZ * 2) - (NKZ * 2 * kf)) * Instrument.Point); nkz4v = zmax - ((NKZ - 5) * Instrument.Point); nkz2v = zmax - ((NKZ * 2) * Instrument.Point); nkz4 = Math.Round(nkz4, Instrument.PriceScale); nkz2 = Math.Round(nkz2, Instrument.PriceScale); nkz4v = Math.Round(nkz4v, Instrument.PriceScale); nkz2v = Math.Round(nkz2v, Instrument.PriceScale); XXPrint("Первая прорисовка ВВЕРХ - {0} - nkz2={1} nkz4={2} - zmax={3}", Bars[ci].Time, nkz2, nkz4, zmax); } if (td) { zmin = dt1 * Instrument.Point; nkz4 = zmin + ((NKZ - 5 - (NKZ * kf)) * Instrument.Point); nkz2 = zmin + (((NKZ * 2) - (NKZ * 2 * kf)) * Instrument.Point); nkz4v = zmin + ((NKZ - 5) * Instrument.Point); nkz2v = zmin + (((NKZ * 2)) * Instrument.Point); nkz4 = Math.Round(nkz4, Instrument.PriceScale); nkz2 = Math.Round(nkz2, Instrument.PriceScale); nkz4v = Math.Round(nkz4v, Instrument.PriceScale); nkz2v = Math.Round(nkz2v, Instrument.PriceScale); XXPrint("Первая прорисовка ВНИЗ - {0} - nkz2={1} nkz4={2} - zmin={3}", Bars[ci].Time, nkz2, nkz4, zmin); } toolRectangle.Point1 = new ChartPoint(Bars[ci].Time, nkz4); toolRectangle.Point2 = new ChartPoint(Bars[ci].Time.AddHours(24), nkz4v); toolRectangle1.Point1 = new ChartPoint(Bars[ci].Time, nkz2); toolRectangle1.Point2 = new ChartPoint(Bars[ci].Time.AddHours(24), nkz2v); } //==================================================================================================================== if (k > 0) { if (tu && Bars[ci].High > zmax) { zmax = Bars[ci].High; nkz4 = zmax - ((NKZ - 5 - (NKZ * kf)) * Instrument.Point); nkz2 = zmax - (((NKZ * 2) - (NKZ * 2 * kf)) * Instrument.Point); nkz4v = zmax - ((NKZ - 5) * Instrument.Point); nkz2v = zmax - ((NKZ * 2) * Instrument.Point); nkz4 = Math.Round(nkz4, Instrument.PriceScale); nkz2 = Math.Round(nkz2, Instrument.PriceScale); nkz4v = Math.Round(nkz4v, Instrument.PriceScale); nkz2v = Math.Round(nkz2v, Instrument.PriceScale); XXPrint("ПЕРЕРИСОВКА ВВЕРХ - {0} - nkz2={1} nkz4={2} - 1U", Bars[ci].Time, nkz2, nkz4); toolRectangle.Point1 = new ChartPoint(Bars[ci].Time, nkz4); toolRectangle.Point2 = new ChartPoint(Bars[ci].Time.AddHours(48), nkz4v); nd = false; nu = false; toolRectangle1.Point1 = new ChartPoint(Bars[ci].Time, nkz2); toolRectangle1.Point2 = new ChartPoint(Bars[ci].Time.AddHours(48), nkz2v); } if (td && Bars[ci].Low < zmin) { zmin = Bars[ci].Low; nkz4 = zmin + ((NKZ - 5 - (NKZ * kf)) * Instrument.Point); nkz2 = zmin + (((NKZ * 2) - (NKZ * 2 * kf)) * Instrument.Point); nkz4v = zmin + ((NKZ - 5) * Instrument.Point); nkz2v = zmin + (((NKZ * 2)) * Instrument.Point); nkz4 = Math.Round(nkz4, Instrument.PriceScale); nkz2 = Math.Round(nkz2, Instrument.PriceScale); nkz4v = Math.Round(nkz4v, Instrument.PriceScale); nkz2v = Math.Round(nkz2v, Instrument.PriceScale); XXPrint("ПЕРЕРИСОВКА ВНИЗ - {0} - nkz2={1} nkz4={2} - 1U", Bars[ci].Time, nkz2, nkz4); toolRectangle.Point1 = new ChartPoint(Bars[ci].Time, nkz4); toolRectangle.Point2 = new ChartPoint(Bars[ci].Time.AddHours(48), nkz4v); nd = false; nu = false; toolRectangle1.Point1 = new ChartPoint(Bars[ci].Time, nkz2); toolRectangle1.Point2 = new ChartPoint(Bars[ci].Time.AddHours(48), nkz2v); } //== Касание зоны/1\4 ====================================================================================================== if (n4) { if (tu && Bars[ci].Low < nkz4 && !nu) { nu = true; XXPrint("ПЕРЕСЕЧЕНИЕ 1/4 ВНИЗ - {0} - {1}", Bars[ci].Time, nkz4); } if (td && Bars[ci].High > nkz4 && !nd) { nd = true; XXPrint("ПЕРЕСЕЧЕНИЕ 1/4 ВВЕРХ - {0} - {1}", Bars[ci].Time, nkz4); } } if (tu && Bars[ci].Low < nkz2 && !nu) { nu = true; XXPrint("ПЕРЕСЕЧЕНИЕ 1/2 ВНИЗ - {0} - {1}", Bars[ci].Time, nkz2); } if (td && Bars[ci].High > nkz2 && !nd) { nd = true; XXPrint("ПЕРЕСЕЧЕНИЕ 1/2 ВВЕРХ - {0} - {1}", Bars[ci].Time, nkz2); } // Если пересечение зоны было (nu) и торгуем вверх (tu) =========================================================== if (nu && tu) { // Определение патерна ПИК ПОСЛЕДНЕГО ФРАКТАЛА ПАТЕРНА ВНИЗУ if (_frInd.TopSeries[Bars.Range.To - frac] > 0) { if (frU3 > frU2 && frU1 > frU2 && frD3 != 0 && frD2 != 0) { var vl1 = Tools.Create <VerticalLine>(); vl1.Time = Bars[ci].Time; vl1.Color = Color.Aqua; vl1.Width = 2; TPU = zmax; SLU = frD2 - Instrument.Spread - dlt; SLU = Math.Round(SLU, Instrument.PriceScale); PRU = Math.Round((TPU - Bars[ci].Close) * Math.Pow(10, Instrument.PriceScale), 0); UBU = Math.Round((Bars[ci].Close - SLU) * Math.Pow(10, Instrument.PriceScale), 0); PCU = Math.Round(PRU / UBU, 2); Ot = Math.Round((frU3 - frU2) / (frU1 - frU2), 2); PRUi = (int)PRU; UBUi = (int)UBU; Print("{8} PATERN BUY -- {0} -- TP={1} SL={2} TP/SL={3} Fract 1-{4} 2-{5} 3-{6} Ot={7}", Bars[ci].Time, PRUi, UBUi, PCU, tmU1, tmU2, tmU3, Ot, Instrument.Name); XXPrint("PATERN BUY -- {0} -- TP={1} SL={2} TP/SL={3} Fract 1-{4} 2-{5} 3-{6} Ot={7}", Bars[ci].Time, PRUi, UBUi, PCU, tmU1, tmU2, tmU3, Ot); if (UBU > 20 && UBU < SL1 && PCU > 2 && Bars[ci].Close > nkz2) { XXPrint("BUY -- {0} -- TP={1} SL={2} TP/SL={3} Fract 1-{4} 2-{5} 3-{6} Ot={7}", Bars[ci].Time, PRU, UBU, PCU, tmU1, tmU2, tmU3, Ot); Trade.OpenMarketPosition(Instrument.Id, ExecutionRule.Buy, 0.1, Instrument.Bid, -1, Stops.InPips(UBUi, PRUi), null, null); frD = false; } } } } // Если пересечение зоны было (nd) и торгуем вниз (td) =========================================================== if (nd && td) { // Определение патерна ПИК ПОСЛЕДНЕГО ФРАКТАЛА ПАТЕРНА ВВЕРХУ if (_frInd.BottomSeries[Bars.Range.To - frac] > 0) { if (frD2 > frD3 && frD2 > frD1 && frD3 != 0 && frD2 != 0) { var vl1 = Tools.Create <VerticalLine>(); vl1.Time = Bars[ci].Time; vl1.Color = Color.Aqua; vl1.Width = 2; TPD = zmin; TPD = Math.Round(TPD, Instrument.PriceScale); SLD = frU2 + Instrument.Spread + dlt; SLD = Math.Round(SLD, Instrument.PriceScale); PRD = Math.Round((Bars[ci].Close - TPD) * Math.Pow(10, Instrument.PriceScale), 0); Ot = Math.Round((frD2 - frD3) / (frD2 - frD1), 2); UBD = Math.Round((SLD - Bars[ci].Close) * Math.Pow(10, Instrument.PriceScale), 0); PRDi = (int)PRD; UBDi = (int)UBD; PCD = Math.Round(PRD / UBD, 2); Print("{8} PATERN SELL -- {0} -- TP(п)={1} SL(p)={2} TP/SL={3} Fract 1-{4} 2-{5} 3-{6} Ot={7}", Bars[ci].Time, PRDi, UBDi, PCD, tmD1, tmD2, tmD3, Ot, Instrument.Name); XXPrint("PATERN SELL -- {0} -- TP(п)={1} SL(p)={2} TP/SL={3} Fract 1-{4} 2-{5} 3-{6} Ot={7}", Bars[ci].Time, PRDi, UBDi, PCD, tmD1, tmD2, tmD3, Ot); if (UBD > 20 && UBD < SL1 && PCD > 2 && Bars[ci].Close < nkz2) { XXPrint("SELL -- {0} -- TP={1} SL={2} TP/SL={3} Fract 1-{4} 2-{5} 3-{6} Ot={7}", Bars[ci].Time, PRDi, UBDi, PCD, tmD1, tmD2, tmD3, Ot); Trade.OpenMarketPosition(Instrument.Id, ExecutionRule.Sell, 0.1, Instrument.Ask, -1, Stops.InPips(UBDi, PRDi), null, null); frU = false; } } } } } k++; }
public void Remove(Trade entity) => this.Trades.Remove(entity);
public void Add(Trade entity) => this.Trades.Add(entity);
/// <summary> /// Constructor. </summary> /// <param name="timeSeries"> the time series </param> /// <param name="trade"> a single trade </param> public CashFlow(TimeSeries timeSeries, Trade trade) { TimeSeries = timeSeries; Calculate(trade); FillToTheEnd(); }
private void OnSubscription(SubscribedResponse response) { _streams.SubscriptionSubject.OnNext(response); var channelId = response.ChanId; // ******************** // ADD HANDLERS BELOW // ******************** switch (response.Channel) { case "ticker": _channelIdToHandler[channelId] = (data, config) => Ticker.Handle(data, response, config, _streams.TickerSubject); break; case "trades": //if pair is null means that is funding if (response.Pair == null) { _channelIdToHandler[channelId] = (data, config) => Funding.Handle(data, response, config, _streams.FundingsSubject); } else { _channelIdToHandler[channelId] = (data, config) => Trade.Handle(data, response, config, _streams.TradesSubject, _streams.TradesSnapshotSubject); } break; case "candles": _channelIdToHandler[channelId] = (data, config) => Candles.Handle(data, response, _streams.CandlesSubject); break; case "book": if ("R0".Equals(response.Prec, StringComparison.OrdinalIgnoreCase)) { _channelIdToHandler[channelId] = (data, config) => RawBook.Handle(data, response, config, _streams.RawBookSubject, _streams.RawBookSnapshotSubject, _streams.BookChecksumSubject); } else { _channelIdToHandler[channelId] = (data, config) => Book.Handle(data, response, config, _streams.BookSubject, _streams.BookSnapshotSubject, _streams.BookChecksumSubject); } break; case "status": if (response.Key.StartsWith("deriv")) { _channelIdToHandler[channelId] = (data, config) => DerivativePairStatus.Handle(data, response, _streams.DerivativePairSubject); } if (response.Key.StartsWith("liq")) { _channelIdToHandler[channelId] = (data, config) => LiquidationFeedStatus.Handle(data, response, _streams.LiquidationFeedSubject); } break; //default: // Log.Warning($"Missing subscription handler '{response.Channel}'"); // break; } }
/// <summary> /// 构造函数 /// </summary> /// <param name="trade"></param> public TradeBuyerPay(Trade trade) { this.TradeInfo = trade; }
//============== //=============================================================================================================================== protected override void NewBar() { DTime = Bars[Bars.Range.To - 1].Time; ci = Bars.Range.To - 1; dlt = dl * Instrument.Point; //========= Рисуем линию начала торгов Европы ============================================================================= if (DTime.Hour == 7 && DTime.Minute == 00) { var vl1 = Tools.Create <VerticalLine>(); vl1.Time = Bars[Bars.Range.To - 1].Time; vl1.Color = Color.Aqua; vl1.Width = 3; } m15F = _ftoInd.FisherSeries[Bars.Range.To - 1]; //==================================================================================================================================== posActiveMineB = Trade.GetActivePositions(mgB, true); if (posActiveMineB != null && posActiveMineB.Length > 0 && posGuidBuy != posActiveMineB[0].Id) { posGuidBuy = posActiveMineB[0].Id; } posActiveMineS = Trade.GetActivePositions(mgS, true); if (posActiveMineS != null && posActiveMineS.Length > 0 && posGuidSell != posActiveMineS[0].Id) { posGuidSell = posActiveMineS[0].Id; } //=== КОРЕКЦИЯ ======================================================================================================================= if (posGuidBuy != Guid.Empty && Trade.GetPosition(posGuidBuy).State == PositionState.Closed) { posGuidBuy = Guid.Empty; } if (posGuidSell != Guid.Empty && Trade.GetPosition(posGuidSell).State == PositionState.Closed) { posGuidSell = Guid.Empty; } //==== Торги ========================================================================================================================= if (DTime.Hour < 6) { torg = true; k = 0; tr = false; } //==== Торги ========================================================================================================================= if (DTime.Hour == 7 && DTime.Minute == 5) { Print("{0} - {1} {2} - {3}", DTime, m5F, tmM1, m1F); if (posGuidBuy == Guid.Empty && torg && m5F < -0.3 && m1F < -0.3) { torg = false; var result107 = Trade.OpenMarketPosition(Instrument.Id, ExecutionRule.Buy, 0.1, Instrument.Bid, -1, Stops.InPips(SL1, null), null, null); if (result107.IsSuccessful) { posGuidBuy = result107.Position.Id; } } if (posGuidSell == Guid.Empty && torg && m5F > 0.3 && m1F > 0.3) { torg = false; var result207 = Trade.OpenMarketPosition(Instrument.Id, ExecutionRule.Sell, 0.1, Instrument.Ask, -1, Stops.InPips(SL1, null), null, null); if (result207.IsSuccessful) { posGuidSell = result207.Position.Id; } } } // Если 15:00 по Киеву - закрыть все ордера if (DTime.Hour == 12) { if (posGuidBuy != Guid.Empty) { var res1 = Trade.CloseMarketPosition(posGuidBuy); if (res1.IsSuccessful) { posGuidBuy = Guid.Empty; } } if (posGuidSell != Guid.Empty) { var res2 = Trade.CloseMarketPosition(posGuidSell); if (res2.IsSuccessful) { posGuidSell = Guid.Empty; } } } // Если фишер пересек красную линию - закрыть все ордера if (FU) { //====================================================================================================================================== //Значение счетчика прохода фишера через 0 FU - вверх FD - вниз //if ( _ftoInd.FisherSeries[Bars.Range.To-2]<0 && _ftoInd.FisherSeries[Bars.Range.To-1]>0) isFU=true; else isFU=false; //if ( _ftoInd.FisherSeries[Bars.Range.To-2]>0 && _ftoInd.FisherSeries[Bars.Range.To-1]<0) isFD=true; else isFD=false; // isFMU isFMD - синяя линия пересекла линию фишера //if ( _ftoInd.FisherSeries[Bars.Range.To-2]<_ftoInd.Ma1Series[Bars.Range.To-2] && _ftoInd.FisherSeries[Bars.Range.To-1]>_ftoInd.Ma1Series[Bars.Range.To-1]) isFMU=true; else isFMU=false; //if ( _ftoInd.FisherSeries[Bars.Range.To-2]>_ftoInd.Ma1Series[Bars.Range.To-2] && _ftoInd.FisherSeries[Bars.Range.To-1]<_ftoInd.Ma1Series[Bars.Range.To-1]) isFMD=true; else isFMD=false; // isFM2U isFM2D - красная линия пересекла линию фишера if (_ftoInd.FisherSeries[Bars.Range.To - 2] < _ftoInd.Ma2Series[Bars.Range.To - 2] && _ftoInd.FisherSeries[Bars.Range.To - 1] > _ftoInd.Ma2Series[Bars.Range.To - 1]) { isFM2U = true; } else { isFM2U = false; } if (_ftoInd.FisherSeries[Bars.Range.To - 2] > _ftoInd.Ma2Series[Bars.Range.To - 2] && _ftoInd.FisherSeries[Bars.Range.To - 1] < _ftoInd.Ma2Series[Bars.Range.To - 1]) { isFM2D = true; } else { isFM2D = false; } if (posGuidBuy != Guid.Empty && isFM2D) { var res1 = Trade.CloseMarketPosition(posGuidBuy); if (res1.IsSuccessful) { posGuidBuy = Guid.Empty; } } if (posGuidSell != Guid.Empty && isFM2U) { var res2 = Trade.CloseMarketPosition(posGuidSell); if (res2.IsSuccessful) { posGuidSell = Guid.Empty; } } } if (posGuidBuy != Guid.Empty && (Trade.GetPosition(posGuidBuy).Pips > 50 || m15F > -0.3)) { tr = true; } if (posGuidSell != Guid.Empty && (Trade.GetPosition(posGuidSell).Pips > 50 || m15F < 0.3)) { tr = true; } if (tr) { TrailActiveOrders(); } }
void ptt_GotFillEvent(Trade t) { fills++; pt.Adjust(t); }
public void SetTradeStats(Trade trade) { var positions = Positions.Values; //Capital usage stats trade.CapitalTotal = Capital.Gross.Count(x => x > 0) > 0 ? Capital.Gross.Where(x => x > 0).Average() : 0; trade.CapitalLong = Capital.Long.Count(x => x > 0) > 0 ? Capital.Long.Where(x => x > 0).Average() : 0; trade.CapitalShort = Capital.Short.Count(x => x > 0) > 0 ? Capital.Short.Where(x => x > 0).Average() : 0; trade.CapitalNet = trade.CapitalLong - trade.CapitalShort; //Realized dollar result stats trade.ResultDollars = RealizedPnL; trade.ResultDollarsLong = RealizedPnLLong; trade.ResultDollarsShort = RealizedPnLShort; //Realized percent result stats trade.ResultPct = trade.CapitalTotal > 0 ? (double)(trade.ResultDollars / trade.CapitalTotal) : 0; trade.ResultPctLong = trade.CapitalLong > 0 ? (double)(trade.ResultDollarsLong / trade.CapitalLong) : 0; trade.ResultPctShort = trade.CapitalShort > 0 ? (double)(trade.ResultDollarsShort / trade.CapitalShort) : 0; //Commissions if (trade.Orders != null) { trade.Commissions = trade.Orders.Sum(x => x.CommissionInBase); } //Unrealized result stats trade.UnrealizedResultDollars = TotalPnL - RealizedPnL; trade.UnrealizedResultDollarsLong = positions.Sum(x => x.PnLLong - x.RealizedPnLLong); trade.UnrealizedResultDollarsShort = positions.Sum(x => x.PnLShort - x.RealizedPnLShort); //Unrealized percent result stats trade.UnrealizedResultPct = trade.CapitalTotal > 0 ? (double)(trade.UnrealizedResultDollars / trade.CapitalTotal) : 0; trade.UnrealizedResultPctLong = trade.CapitalLong > 0 ? (double)(trade.UnrealizedResultDollarsLong / trade.CapitalLong) : 0; trade.UnrealizedResultPctShort = trade.CapitalShort > 0 ? (double)(trade.UnrealizedResultDollarsShort / trade.CapitalShort) : 0; }
private void UpdateLastTradedSymbol(Trade trade) { LastTradedSymbol = trade.Symbol; MethodLaunchCounter++; }
private void OnRtnDepthMarketData(IntPtr pApi, ref CThostFtdcDepthMarketDataField pDepthMarketData) { DataRecord record; if (!_dictAltSymbol2Instrument.TryGetValue(pDepthMarketData.InstrumentID, out record)) { mdlog.Warn("合约{0}不在订阅列表中却收到了数据", pDepthMarketData.InstrumentID); return; } Instrument instrument = record.Instrument; CThostFtdcDepthMarketDataField DepthMarket; _dictDepthMarketData.TryGetValue(pDepthMarketData.InstrumentID, out DepthMarket); //将更新字典的功能提前,因为如果一开始就OnTrade中下单,涨跌停没有更新 _dictDepthMarketData[pDepthMarketData.InstrumentID] = pDepthMarketData; if (TimeMode.LocalTime == _TimeMode) { //为了生成正确的Bar,使用本地时间 _dateTime = Clock.Now; } else { //直接按HH:mm:ss来解析,测试过这种方法目前是效率比较高的方法 try { // 只有使用交易所行情时才需要处理跨天的问题 ChangeTradingDay(pDepthMarketData.TradingDay); int HH = int.Parse(pDepthMarketData.UpdateTime.Substring(0, 2)); int mm = int.Parse(pDepthMarketData.UpdateTime.Substring(3, 2)); int ss = int.Parse(pDepthMarketData.UpdateTime.Substring(6, 2)); _dateTime = new DateTime(_yyyy, _MM, _dd, HH, mm, ss, pDepthMarketData.UpdateMillisec); } catch (Exception) { _dateTime = Clock.Now; } } if (record.TradeRequested) { //通过测试,发现IB的Trade与Quote在行情过来时数量是不同的,在这也做到不同 if (DepthMarket.LastPrice == pDepthMarketData.LastPrice && DepthMarket.Volume == pDepthMarketData.Volume) { } else { //行情过来时是今天累计成交量,得转换成每个tick中成交量之差 int volume = pDepthMarketData.Volume - DepthMarket.Volume; if (0 == DepthMarket.Volume) { //没有接收到最开始的一条,所以这计算每个Bar的数据时肯定超大,强行设置为0 volume = 0; } else if (volume < 0) { //如果隔夜运行,会出现今早成交量0-昨收盘成交量,出现负数,所以当发现为负时要修改 volume = pDepthMarketData.Volume; } Trade trade = new Trade(_dateTime, pDepthMarketData.LastPrice == double.MaxValue ? 0 : pDepthMarketData.LastPrice, volume); EmitNewTradeEvent(instrument, trade); } } if (record.QuoteRequested) { //if ( //DepthMarket.BidVolume1 == pDepthMarketData.BidVolume1 //&& DepthMarket.AskVolume1 == pDepthMarketData.AskVolume1 //&& DepthMarket.BidPrice1 == pDepthMarketData.BidPrice1 //&& DepthMarket.AskPrice1 == pDepthMarketData.AskPrice1 //) //{ } //else { Quote quote = new Quote(_dateTime, pDepthMarketData.BidPrice1 == double.MaxValue ? 0 : pDepthMarketData.BidPrice1, pDepthMarketData.BidVolume1, pDepthMarketData.AskPrice1 == double.MaxValue ? 0 : pDepthMarketData.AskPrice1, pDepthMarketData.AskVolume1 ); EmitNewQuoteEvent(instrument, quote); } } if (record.MarketDepthRequested) { EmitNewMarketDepth(instrument, _dateTime, 0, MDSide.Ask, pDepthMarketData.AskPrice1, pDepthMarketData.AskVolume1); EmitNewMarketDepth(instrument, _dateTime, 0, MDSide.Bid, pDepthMarketData.BidPrice1, pDepthMarketData.BidVolume1); //EmitNewMarketDepth(instrument, _dateTime, 1, MDSide.Ask, pDepthMarketData.AskPrice2, pDepthMarketData.AskVolume2); //EmitNewMarketDepth(instrument, _dateTime, 1, MDSide.Bid, pDepthMarketData.BidPrice2, pDepthMarketData.BidVolume2); //EmitNewMarketDepth(instrument, _dateTime, 2, MDSide.Ask, pDepthMarketData.AskPrice3, pDepthMarketData.AskVolume3); //EmitNewMarketDepth(instrument, _dateTime, 2, MDSide.Bid, pDepthMarketData.BidPrice3, pDepthMarketData.BidVolume3); //EmitNewMarketDepth(instrument, _dateTime, 3, MDSide.Ask, pDepthMarketData.AskPrice4, pDepthMarketData.AskVolume4); //EmitNewMarketDepth(instrument, _dateTime, 3, MDSide.Bid, pDepthMarketData.BidPrice4, pDepthMarketData.BidVolume4); //EmitNewMarketDepth(instrument, _dateTime, 4, MDSide.Ask, pDepthMarketData.AskPrice5, pDepthMarketData.AskVolume5); //EmitNewMarketDepth(instrument, _dateTime, 4, MDSide.Bid, pDepthMarketData.BidPrice5, pDepthMarketData.BidVolume5); } // 价差生成功能 do { if (null == CTPAPI.GetInstance().SpreadMarketData) { break; } ISpreadMarketData SpreadMarketData = CTPAPI.GetInstance().SpreadMarketData; var ticks = SpreadMarketData.CalculateSpread(pDepthMarketData); if (null == ticks) { break; } foreach (var tick in ticks) { Instrument inst = InstrumentManager.Instruments[tick.Symbol]; if (null == inst) { continue; } if (!double.IsNaN(tick.Price)) { Trade trade = new Trade(_dateTime, tick.Price, tick.Size); trade.ProviderId = tick.ProviderId; EmitNewTradeEvent(inst, trade); } if (!double.IsNaN(tick.Ask) && !double.IsNaN(tick.Bid)) { Quote quote = new Quote(_dateTime, tick.Bid, tick.BidSize, tick.Ask, tick.AskSize); quote.ProviderId = tick.ProviderId; EmitNewQuoteEvent(inst, quote); } } } while (false); // 直接回报CTP的行情信息 if (EmitOnRtnDepthMarketData) { CTPAPI.GetInstance().FireOnRtnDepthMarketData(pDepthMarketData); } }
protected override void onFilled(Position position, Trade trade) { }