Esempio n. 1
0
		protected BarFactoryItem(Instrument instrument, BarType barType, long barSize)
		{
			this.factory = null;
			this.instrument = instrument;
			this.barType = barType;
			this.barSize = barSize;
		}
Esempio n. 2
0
 public void Subscribe(IDataProvider provider, Instrument instrument)
 {
     if (provider.Status != ProviderStatus.Connected)
     {
         provider.Connect();
     }
     Dictionary<Instrument, int> dictionary = null;
     if (!this.subscriptions.TryGetValue((int)provider.Id, out dictionary))
     {
         dictionary = new Dictionary<Instrument, int>();
         this.subscriptions[(int)provider.Id] = dictionary;
     }
     int num = 0;
     bool flag = false;
     if (!dictionary.TryGetValue(instrument, out num))
     {
         flag = true;
         num = 1;
     }
     else
     {
         if (num == 0)
         {
             flag = true;
         }
         num++;
     }
     dictionary[instrument] = num;
     if (flag)
     {
         provider.Subscribe(instrument);
     }
 }
 public HistoricalDataRequest(Instrument instrument, DateTime dateTime1, DateTime dateTime2, byte dataType)
 {
     this.Instrument = instrument;
     this.DateTime1 = dateTime1;
     this.DateTime2 = dateTime2;
     this.DataType = dataType;
 }
Esempio n. 4
0
		public override object Read(BinaryReader reader)
		{
			reader.ReadByte();
			int id = reader.ReadInt32();
			InstrumentType type = (InstrumentType)reader.ReadByte();
			string symbol = reader.ReadString();
			string description = reader.ReadString();
			byte currencyId = reader.ReadByte();
			string exchange = reader.ReadString();
			Instrument instrument = new Instrument(id, type, symbol, description, currencyId, exchange);
			instrument.tickSize = reader.ReadDouble();
			instrument.maturity = new DateTime(reader.ReadInt64());
			instrument.factor = reader.ReadDouble();
			instrument.strike = reader.ReadDouble();
			instrument.putcall = (PutCall)reader.ReadByte();
			instrument.margin = reader.ReadDouble();
			int num = reader.ReadInt32();
			for (int i = 0; i < num; i++)
			{
				AltId altId = new AltId();
				altId.providerId = reader.ReadByte();
				altId.symbol = reader.ReadString();
				altId.exchange = reader.ReadString();
				instrument.altId.Add(altId);
			}
			return instrument;
		}
Esempio n. 5
0
 protected override void OnInit()
 {
   this.instrument = (Instrument) this.args[0];
   this.InitDataSeriesList();
   this.InitDataSeriesViewer();
   this.Text = string.Format("Data [{0}]", (object) this.instrument.Symbol);
 }
 public override void Subscribe(Instrument instrument)
 {
     if (instrument.Parent != null)
     {
         this.strategyBySynthInstrument[instrument.Id] = this.strategyBySynthInstrument[instrument.Parent.Id];
         this.strategyBySynthInstrument[instrument.Id].OnSubscribe(instrument);
         return;
     }
     SellSideInstrumentStrategy sellSideInstrumentStrategy = (SellSideInstrumentStrategy)Activator.CreateInstance(base.GetType(), new object[]
     {
         this.framework,
         string.Concat(new object[]
         {
             base.Name,
             "(",
             instrument,
             ")"
         })
     });
     this.SetupStrategy(sellSideInstrumentStrategy);
     sellSideInstrumentStrategy.Instrument = instrument;
     this.strategyBySynthInstrument[instrument.Id] = sellSideInstrumentStrategy;
     sellSideInstrumentStrategy.OnSubscribe(instrument);
     sellSideInstrumentStrategy.dataProvider = base.DataProvider;
     sellSideInstrumentStrategy.executionProvider = base.ExecutionProvider;
     sellSideInstrumentStrategy.raiseEvents = true;
     base.AddStrategy(sellSideInstrumentStrategy, false);
     sellSideInstrumentStrategy.OnStrategyStart();
 }
        // 从分类好的目录中取中所有合约
        private SortedDictionary<int, FileInfo> GetData_Instrument(Instrument inst)
        {
            SortedDictionary<int, FileInfo> resultList = new SortedDictionary<int, FileInfo>();

            if (string.IsNullOrEmpty(DataPath_Instrument))
                return resultList;            

            // 直接查找某一目录是否存在
            string instrument = inst.Symbol;
            int i = inst.Symbol.IndexOf('.');
            if(i>=0)
            {
                instrument = instrument.Substring(0,i);
            }

            var di = new DirectoryInfo(DataPath_Instrument);

            if (!di.Exists)
                return resultList;

            var list = di.GetDirectories(instrument, System.IO.SearchOption.AllDirectories);
            foreach(var l in list)
            {
                UnionAndUpdate(resultList, GetFiles(l, inst.Symbol));
            }

            return resultList;
        }
Esempio n. 8
0
 public ImportTask(Instrument instrument)
 {
   this.Instrument = instrument;
   this.State = ImportTaskState.Pending;
   this.Count = 0;
   this.TotalNum = 0;
   this.Message = string.Empty;
 }
Esempio n. 9
0
		public void Delete(Instrument instrument)
		{
			this.instruments.Remove(instrument);
			if (this.server != null && instrument.isPersistent)
			{
				this.server.Delete(instrument);
			}
			this.framework.eventServer.OnInstrumentDeleted(instrument);
		}
Esempio n. 10
0
 private void textBox_Instrument_Validating(object sender, CancelEventArgs e)
 {
     Instrument = SmartQuant.Shared.Global.Framework.InstrumentManager.Get((sender as TextBox).Text);
     errorProvider1.Clear();
     if (Instrument == null)
     {
         errorProvider1.SetError(textBox_Instrument,"合约不存在");
     }
 }
 public InstrumentViewItem(Instrument instrument)
   : base(new string[5])
 {
   this.Instrument = instrument;
   this.SubItems[0].Text = instrument.Symbol;
   this.SubItems[1].Text = instrument.Type.ToString();
   this.SubItems[2].Text = instrument.Exchange;
   this.SubItems[3].Text = CurrencyId.GetName(instrument.CurrencyId);
   this.SubItems[4].Text = instrument.Maturity == DateTime.MinValue ? string.Empty : instrument.Maturity.ToShortDateString();
 }
Esempio n. 12
0
		public Instrument GetById(int id)
		{
			Instrument instrument = this.instruments.GetById(id);
			if (instrument == null)
			{
				instrument = new Instrument(id, InstrumentType.Synthetic, Guid.NewGuid().ToString(), "", 1);
				this.instruments.Add(instrument);
			}
			return instrument;
		}
Esempio n. 13
0
 public Order(IExecutionProvider provider, Instrument instrument, OrderType type, OrderSide side, double qty, double price = 0.0, double stopPx = 0.0, TimeInForce timeInForce = TimeInForce.Day, string text = "")
     : this()
 {
     this.provider = provider;
     this.instrument = instrument;
     this.type = type;
     this.side = side;
     this.qty = qty;
     this.price = price;
     this.stopPx = stopPx;
     this.timeInForce = timeInForce;
     this.text = text;
     this.portfolio = null;
 }
Esempio n. 14
0
		public void Add(Instrument instrument, bool save = true)
		{
			if (this.Contains(instrument.symbol))
			{
				throw new ApplicationException("Instrument with the same symbol is already present in the framework : " + instrument.symbol);
			}
			instrument.Id = this.next_id;
			this.next_id++;
			this.instruments.Add(instrument);
			if (save && this.server != null)
			{
				this.server.Save(instrument);
			}
			this.framework.eventServer.OnInstrumentAdded(instrument);
		}
Esempio n. 15
0
		public void AddInstance(Instrument instrument, InstrumentStrategy strategy)
		{
			strategy.instruments.Add(instrument);
			strategy.instrument = instrument;
			strategy.raiseEvents = true;
			strategy.dataProvider = this.dataProvider;
			strategy.executionProvider = this.executionProvider;
			this.Add(strategy);
			if (base.Instruments.GetById(instrument.id) == null)
			{
				base.Instruments.Add(instrument);
			}
			strategy.status = StrategyStatus.Running;
			strategy.OnStrategyStart();
		}
Esempio n. 16
0
 public Stop(Strategy strategy, Position position, DateTime time)
 {
     this.strategy = strategy;
     this.position = position;
     this.instrument = position.instrument;
     this.qty = position.qty;
     this.side = position.Side;
     this.type = StopType.Time;
     this.creationTime = strategy.framework.Clock.DateTime;
     this.completionTime = time;
     this.stopPrice = this.GetInstrumentPrice();
     if (this.completionTime > this.creationTime)
     {
         strategy.framework.Clock.AddReminder(new Reminder(new ReminderCallback(this.OnClock), this.completionTime, null));
     }
 }
Esempio n. 17
0
 public Stop(Strategy strategy, Position position, double level, StopType type, StopMode mode)
 {
     this.strategy = strategy;
     this.position = position;
     this.instrument = position.instrument;
     this.qty = position.qty;
     this.side = position.Side;
     this.level = level;
     this.type = type;
     this.mode = mode;
     this.currPrice = this.GetInstrumentPrice();
     this.trailPrice = this.currPrice;
     this.stopPrice = this.GetStopPrice();
     this.creationTime = strategy.framework.Clock.DateTime;
     this.completionTime = DateTime.MinValue;
     this.Connect();
 }
Esempio n. 18
0
        protected override void OnBar(Instrument instrument, Bar bar)
        {
            // Add bar to bar series.
            Bars.Add(bar);

            // Add bar to group.
            Log(bar, barsGroup);

            // Add upper bollinger band value to group.
            if (bbu.Count > 0)
                Log(bbu.Last, bbuGroup);

            // Add lower bollinger band value to group.
            if (bbl.Count > 0)
                Log(bbl.Last, bblGroup);

            // Add simple moving average value bands to group.
            if (sma.Count > 0)
                Log(sma.Last, smaGroup);

            // Calculate performance.
            Portfolio.Performance.Update();

            // Add equity to group.
            Log(Portfolio.Value, equityGroup);

            // Check strategy logic.
            if (!HasPosition(instrument))
            {
                if (bbu.Count > 0 && bar.Close >= bbu.Last)
                {
                    Order enterOrder = SellOrder(Instrument, Qty, "Enter");
                    Send(enterOrder);
                }
                else if (bbl.Count > 0 && bar.Close <= bbl.Last)
                {
                    Order enterOrder = BuyOrder(Instrument, Qty, "Enter");
                    Send(enterOrder);
                }
            }
            else
                UpdateExitLimit();
        }
Esempio n. 19
0
		public void Add(Instrument instrument, BarType barType, long barSize)
		{
			BarFactoryItem item;
			switch (barType)
			{
			case BarType.Time:
				item = new TimeBarFactoryItem(instrument, barSize);
				break;
			case BarType.Tick:
				item = new TickBarFactoryItem(instrument, barSize);
				break;
			case BarType.Volume:
				item = new VolumeBarFactoryItem(instrument, barSize);
				break;
			default:
				throw new ArgumentException(string.Format("Unknown bar type - {0}", barType));
			}
			this.Add(item);
		}
Esempio n. 20
0
		public TickSeries GetHistoricalTrades(IHistoricalDataProvider provider, Instrument instrument, DateTime dateTime1, DateTime dateTime2)
		{
			HistoricalDataRequest request = new HistoricalDataRequest(instrument, dateTime1, dateTime2, 4);
			provider.Send(request);
			this.handle = new ManualResetEventSlim(false);
			this.handle.Wait();
			TickSeries tickSeries = new TickSeries("");
			if (this.historicalData != null)
			{
				foreach (HistoricalData current in this.historicalData)
				{
					DataObject[] objects = current.Objects;
					for (int i = 0; i < objects.Length; i++)
					{
						DataObject dataObject = objects[i];
						tickSeries.Add((Trade)dataObject);
					}
				}
			}
			this.historicalData = null;
			return tickSeries;
		}
        // 得到API中的合约名与交易所
        private void GetApi_Symbol_Exchange_TickSize(Instrument instrument,
            out string altSymbol, out string altExchange,
            out string apiSymbol, out string apiExchange,
            out double apiTickSize)
        {
            // 取合约别名
            altSymbol = instrument.GetSymbol(this.id);
            altExchange = instrument.GetExchange(this.id);
            apiTickSize = instrument.TickSize;

            // 取合约在API中的名字
            apiSymbol = altSymbol;
            apiExchange = altExchange;

            InstrumentField _Instrument;
            if (_dictInstruments.TryGetValue(altSymbol, out _Instrument))
            {
                apiSymbol = _Instrument.InstrumentID;
                apiExchange = _Instrument.ExchangeID;
                apiTickSize = _Instrument.PriceTick;
            }
        }
        private void EmitNewMarketDepth(Instrument instrument, DateTime datatime, int position, MDSide ask, double price, int size)
        {
            MDOperation insert = MDOperation.Update;
            if (MDSide.Ask == ask)
            {
                if (position >= instrument.OrderBook.Ask.Count)
                {
                    insert = MDOperation.Insert;
                }
            }
            else
            {
                if (position >= instrument.OrderBook.Bid.Count)
                {
                    insert = MDOperation.Insert;
                }
            }

            if (price != 0 && size != 0)
            {
                EmitNewMarketDepth(instrument, new MarketDepth(datatime, "", position, insert, ask, price, size));
            }
        }
        public InstrumentList LoadFiles()
        {
            if (!Directory.Exists(Path))
            {
                return instruments;
            }

            var dir = new DirectoryInfo(Path);
            foreach (var fi in dir.GetFiles("*", System.IO.SearchOption.AllDirectories))
            {
                // 以最深层的文件名做为合约名
                string _exchange = string.Empty;
                string _product = string.Empty;
                string _instrument = string.Empty;
                string _symbol = string.Empty;
                string _date = string.Empty;
                if (PathHelper.SplitFileName(fi.Name, out _exchange, out _product, out _instrument, out _date))
                {
                    if (!string.IsNullOrEmpty(_exchange))
                    {
                        _symbol = string.Format("{0}.{1}", _instrument, _exchange);
                    }
                    else
                        _symbol = _instrument;

                    Instrument inst = framework.InstrumentManager.Get(_symbol);
                    if (inst == null)
                    {
                        inst = new Instrument(SmartQuant.InstrumentType.Synthetic, _symbol);
                        framework.InstrumentManager.Add(inst, Save);
                    }
                    instruments.Add(inst);
                }
            }
            return instruments;
        }
Esempio n. 24
0
 public TickBarFactoryItem(Instrument instrument, long barSize)
     : base(instrument, BarType.Tick, barSize)
 {
 }
Esempio n. 25
0
        private void Send(Order order)
        {
            base.EmitExecutionReport(new ExecutionReport
            {
                dateTime    = this.framework.Clock.DateTime,
                order       = order,
                commandID   = order.id,
                instrument  = order.instrument,
                ordQty      = order.qty,
                timeInForce = order.timeInForce,
                execType    = ExecType.ExecNew,
                ordStatus   = OrderStatus.New,
                currencyId  = order.instrument.currencyId,
                ordType     = order.type,
                side        = order.side,
                cumQty      = 0.0,
                lastQty     = 0.0,
                leavesQty   = 0.0,
                lastPx      = 0.0,
                avgPx       = 0.0,
                text        = order.text
            });
            int id = order.instrument.Id;

            if (this.orders[id] == null)
            {
                this.orders[id] = new List <Order>();
            }
            this.orders[id].Add(order);
            switch (order.type)
            {
            case OrderType.Market:
                if (!this.fillMarketOnNext)
                {
                    Instrument instrument = order.instrument;
                    if (this.fillOnQuote)
                    {
                        switch (order.side)
                        {
                        case OrderSide.Buy:
                        {
                            Ask ask = this.framework.DataManager.GetAsk(instrument);
                            if (ask != null)
                            {
                                this.Fill(order, ask.Price, ask.Size);
                                return;
                            }
                            break;
                        }

                        case OrderSide.Sell:
                        {
                            Bid bid = this.framework.DataManager.GetBid(instrument);
                            if (bid != null)
                            {
                                this.Fill(order, bid.Price, bid.Size);
                                return;
                            }
                            break;
                        }
                        }
                    }
                    if (this.fillOnTrade)
                    {
                        Trade trade = this.framework.DataManager.GetTrade(instrument);
                        if (trade != null)
                        {
                            this.Fill(order, trade.Price, trade.Size);
                        }
                    }
                }
                break;

            case OrderType.Stop:
            case OrderType.Limit:
                break;

            default:
                return;
            }
        }
 public override void Unsubscribe(Instrument instrument)
 {
     if (instrument.Parent != null)
     {
         this.strategyBySynthInstrument[instrument.Id].OnUnsubscribe(instrument);
         this.strategyBySynthInstrument.Remove(instrument.Id);
     }
 }
Esempio n. 27
0
 protected internal override void OnTrade(Instrument instrument, Trade trade)
 {
     this.alphaComponent.OnTrade(trade);
     this.positionComponent.OnTrade(trade);
 }
Esempio n. 28
0
 protected internal override void OnBid(Instrument instrument, Bid bid)
 {
     this.alphaComponent.OnBid(bid);
     this.positionComponent.OnBid(bid);
 }
Esempio n. 29
0
		public void Import(string fileName, string symbol, int type)
		{
			Console.WriteLine("Starting export: " + fileName + " " + symbol);
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			TextReader textReader = File.OpenText(fileName);
			Instrument instrument = this.framework.InstrumentManager.Get(symbol);
			if (instrument == null)
			{
				instrument = new Instrument(InstrumentType.Stock, symbol, "", 1);
				this.framework.InstrumentManager.Add(instrument, true);
			}
			int num4 = 0;
			double num5 = -1.0;
			int num6 = -1;
			double num7 = -1.0;
			int num8 = -1;
			textReader.ReadLine();
			while (true)
			{
				string text = textReader.ReadLine();
				if (text == null)
				{
					break;
				}
				string[] array = text.Split(new char[]
				{
					','
				});
				CultureInfo invariantCulture = CultureInfo.InvariantCulture;
				switch (type)
				{
				case 4:
				{
					DateTime dateTime = DateTime.ParseExact(array[0], "yyyy-MM-dd HH:mm:ss.fff", invariantCulture);
					double num9 = double.Parse(array[1], invariantCulture);
					int num10 = int.Parse(array[2]);
					if (num9 > 0.0 && num10 > 0)
					{
						Trade obj = new Trade(dateTime, 1, instrument.Id, num9, num10);
						this.framework.DataManager.Save(instrument, obj);
						num3++;
					}
					break;
				}
				case 5:
				{
					DateTime dateTime2 = DateTime.ParseExact(array[0], "yyyy-MM-dd HH:mm:ss.fff", invariantCulture);
					double num11 = double.Parse(array[1], invariantCulture);
					int num12 = int.Parse(array[2]);
					double num13 = double.Parse(array[3], invariantCulture);
					int num14 = int.Parse(array[4]);
					if (num11 > 0.0 && num12 > 0 && (num5 != num11 || num6 != num12))
					{
						Bid obj2 = new Bid(dateTime2, 1, instrument.Id, num11, num12);
						this.framework.DataManager.Save(instrument, obj2);
						num5 = num11;
						num6 = num12;
						num2++;
					}
					if (num13 > 0.0 && num14 > 0 && (num7 != num13 || num8 != num14))
					{
						Ask obj3 = new Ask(dateTime2, 1, instrument.Id, num13, num14);
						this.framework.DataManager.Save(instrument, obj3);
						num7 = num13;
						num8 = num14;
						num++;
					}
					break;
				}
				}
				if (num4 % 100000 == 0)
				{
					Console.WriteLine(num4);
				}
				num4++;
			}
			Console.WriteLine(string.Concat(new object[]
			{
				"Lines = ",
				num4,
				" bids: ",
				num2,
				" asks: ",
				num,
				" trades: ",
				num3
			}));
			textReader.Close();
		}
Esempio n. 30
0
		public Leg(Instrument instrument, double weight)
		{
			this.instrument = instrument;
			this.weight = weight;
		}
Esempio n. 31
0
		public Leg(Instrument instrument)
		{
			this.instrument = instrument;
			this.weight = 0.0;
		}
Esempio n. 32
0
		public InstrumentEventArgs(Instrument instrument)
		{
			this.Instrument = instrument;
		}
Esempio n. 33
0
		public void OnInstrumentDeleted(Instrument instrument)
		{
			this.OnEvent(new OnInstrumentDeleted(instrument));
		}
Esempio n. 34
0
 protected internal override void OnAsk(Instrument instrument, Ask ask)
 {
     this.alphaComponent.OnAsk(ask);
     this.positionComponent.OnAsk(ask);
 }
        public void Unsubscribe(int providerId, Instrument instrument)
        {
            IDataProvider provider = this.framework.ProviderManager.GetProvider(providerId) as IDataProvider;

            this.Unsubscribe(provider, instrument);
        }