private void btnChartMarket_Click(object sender, EventArgs e) { WinForms.SetWaitCursor(true); try { zChartInterval interval = (zChartInterval)Enum.Parse(typeof(zChartInterval), comboChartInterval.Text); EZInstrument instrument = APIMain.Instance.ShowInstrumentDialog(); if (instrument == null) { status.Text = "No instrument selected."; } else { status.Text = "*** LOADING CHART ***"; RequestChartData(instrument, interval, Convert.ToInt32(numericPeriod.Value)); } } finally { WinForms.SetWaitCursor(false); } }
void api_OnInstrumentFound(EZInstrument ttInstrument, bool success) { #region Thread Safety //cross thread - so you don't get the cross theading exception if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate { api_OnInstrumentFound(ttInstrument, success); }); return; } #endregion if (success) { } else { string errorMsg = ""; // Instrument not found and TTAPI has given up looking for it MessageBox.Show(this, "Could not find instrument:\n\n" + ttInstrument.Name + "\n\n" + errorMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
void api_OnInstrumentFound(EZInstrument ttInstrument, bool success) { //cross thread - so you don't get the cross theading exception if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate { api_OnInstrumentFound(ttInstrument, success); }); return; } if (success) { //TTInstrument ttInstrument = new TTInstrument(instrument.Key); if (!ttInstruments.ContainsKey(ttInstrument.Key)) { ttInstruments[ttInstrument.Key] = ttInstrument; } Message("Subscribed to " + ttInstrument.Name); //btnOrder.Enabled = true; } else { string errorMsg = ""; /*if (e.Error != null) * errorMsg = e.Error.Message;*/ // Instrument not found and TTAPI has given up looking for it MessageBox.Show(this, "Could not find instrument:\n\n" + ttInstrument.Name + "\n\n" + errorMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public Trade(string tradeName, EZInstrument tradeInstrument) { this.Name = tradeName; this.tradeInstrument = tradeInstrument; VirtualQuantity = 1; QuantityMultiplier = 1; BuySell = zBuySell.Buy; // TODO: Not sure if we want this to be initialized this.currentTradeState = TradeState.NOT_STARTED; AutoRestart = false; Throttle = 5; this.tradeActive = true; this.Metrics = null; throttleTimer = new Timer(); throttleTimer.Elapsed += throttleTimer_Elapsed; execution = new SimpleExecutionEngine(); execution.PartialFill += execution_PartialFill; execution.CompleteFill += execution_CompleteFill; // Create the TradeSteps that make up this trade. tradeSteps = new Dictionary <TradeStepType, TradeStep>(); tradeSteps[TradeStepType.PRECONDITIONS] = new TradeStep(TradeStepType.PRECONDITIONS, BooleanRuleCombination.AND); tradeSteps[TradeStepType.ENTRY] = new TradeStep(TradeStepType.ENTRY); tradeSteps[TradeStepType.EXIT] = new TradeStep(TradeStepType.EXIT); tradeSteps[TradeStepType.STOP] = new TradeStep(TradeStepType.STOP); }
public ezSpreadLeg(EZInstrument instrument, zBuySell buySell, int executeSize, double priceMultiplier) { this.Instrument = instrument; this.buySell = buySell; this.executeSize = executeSize; this.priceMultiplier = priceMultiplier; }
/// <summary> /// Example: to get 15 minute bars, /// interval = ChartInterval.Minute /// period = 15 /// </summary> /// <param name="market"></param> /// <param name="interval"></param> /// <param name="period"></param> /// <param name="startDate"></param> /// <param name="endDate">Leave endDate = null for realtime (endDate = current date)</param> static public EZChartDataSeries MakeChartData(EZInstrument instrument, ezBarInterval barInterval, DateTime startDate, DateTime?endDate = null) { Market market = APIMain.MarketFromInstrument(instrument); // Load the data for the selected market. BarInterval interval = new BarInterval(APIConvert.ToChartInterval(barInterval.Interval), barInterval.Period); ChartDataSeries ctsChartData = new ChartDataSeries(market, interval, SessionTimeRange.Empty); var session = new ezSessionTimeRange(); EZChartDataSeries chartData = new EZChartDataSeries(market.Description, barInterval, session); var chartThread = new ChartDataThread(ctsChartData, chartData, startDate, endDate); var thread = new Thread(new ThreadStart(chartThread.Run)); thread.Name = market.Description + ":" + barInterval; thread.Start(); return(chartData); //dataPoints = new List<ezBarDataPoint>(); /*foreach (HistoricalQuote hq in historical) * { * ezBarDataPoint dp = new ezBarDataPoint(hq.Open, hq.High, hq.Low, hq.Close, 0, hq.Volume); * dataPoints.Add(dp); * }*/ }
static public ezPrice FromDouble(EZInstrument instrument, double price) { var ezPrice = new ezPrice(price); ezPrice.instrument = instrument; return(ezPrice); }
private void RequestChartData(EZInstrument instrument, zChartInterval interval, int period) { ChartDataForm chartForm; // Set EndDate to the current trading date. //DateTime dtEndDate = selectedContract.GetTradeDate(DateTime.Now); DateTime dtEndDate = DateTime.Now; DateTime dtStartDate; // Pick a different start date depending on if we are viewing DAYS, HOURS, MINUTES, etc... if (interval == zChartInterval.Week) { dtStartDate = dtEndDate.AddMonths(-16); } else if (interval == zChartInterval.Day) { dtStartDate = dtEndDate.AddMonths(-5); } else if (interval == zChartInterval.Minute) { dtStartDate = dtEndDate; if (period <= 15) // 15 minute (or less) bars { dtStartDate = dtStartDate.AddTradeHours(-4); } else // more than 15 minute bars { dtStartDate = dtStartDate.AddTradeDays(-2); } } else { // Anything we haven't covered, we'll load a couple days (not ideal - needs to be improved). dtStartDate = dtEndDate; dtStartDate = dtStartDate.AddTradeDays(-3); /*// This little loop here will ensure that we load the previous trade date as well as today and will account for weekends * // and holidays. * while ((selectedContract.GetTradeDate(dtStartDate) == dtEndDate)) * { * dtStartDate = dtStartDate.AddDays(-1); * }*/ } // Create a BarInterval object to tell the API what bar interval we want. // So for example, if we wanted a 15 minute bar, we would do: New ezBarInterval(zChartDataType.Minute, 15) ezBarInterval ezbi = new ezBarInterval(interval, period); IChartDataProvider provider = new ChartDataProviderCTS(instrument.Name + " : " + ezbi, ezbi, ezSessionTimeRange.Empty); chartForm = new ChartDataForm(provider); WinForms.SetWaitCursor(true); //provider.LoadHistoricalChartData(APIMain.MarketFromInstrument(instrument), dtStartDate, dtEndDate); provider.LoadRealTimeChartData(APIMain.MarketFromInstrument(instrument), dtStartDate); chartForm.Show(); }
void api_OnInsideMarketUpdate(EZInstrument instrument) { if (instrument == null || currentInstrument == null || instrument.Key != currentInstrument.Key) { return; } /*if (selectedMarketData.Equals("Bid Price")) * UpdateDataValue(instrument.Bid.ToString()); * else if (selectedMarketData.Equals("Bid Quantity")) * UpdateDataValue(instrument.BidQty.ToString()); * else if (selectedMarketData.Equals("Offer Price")) * UpdateDataValue(instrument.Ask.ToString()); * else if (selectedMarketData.Equals("Offer Quantity")) * UpdateDataValue(instrument.AskQty.ToString());*/ ezPrice price = instrument.Last; ezQuantity qty = instrument.LastQty; // Check if the price has moved. if (price != lastPrint) { Spy.Print("{0} : {1}", price, lastPrint); //StoreLastPrice(price); lastPrint = price; timeFrames.StoreTradeVolume(qty); UpdateDataValue(timeFrames.VolumeInTimePeriod(TimeSpan.FromMinutes(5))); lastPrintTotalVolume = instrument.LastTotalVolume; } else // last price is the same - check to see if another trade occurred at the same price { if (instrument.LastTotalVolume > lastPrintTotalVolume) { timeFrames.StoreTradeVolume(qty); UpdateDataValue(timeFrames.VolumeInTimePeriod(TimeSpan.FromMinutes(5))); lastPrintTotalVolume = instrument.LastTotalVolume; } } //UpdateDataValue(instrument.LastQty.ToString()); /*this.Invoke((MethodInvoker)delegate * { * lblBid1.Text = instrument.Bid.ToString(); * lblBidVol1.Text = instrument.BidQty.ToString(); * lblOffer1.Text = instrument.Ask.ToString(); * lblOfferVol1.Text = instrument.AskQty.ToString(); * lblLast1.Text = instrument.Last.ToString(); * lblLastVol1.Text = instrument.LastQty.ToString(); * lblTotalVol1.Text = instrument.Volume.ToString(); * lblNet1.Text = instrument.NetPos.ToString(); * lblBuys1.Text = instrument.NetBuys.ToString(); * lblSells1.Text = instrument.NetSells.ToString(); * });*/ }
private void btnMarket2_Click(object sender, EventArgs e) { EZInstrument instrument = api.ShowInstrumentDialog(); if (instrument != null) { lblMarket2.Text = instrument.Description; instrument2 = instrument; } }
static public EZInstrument MakeInstrument(Market market) { ezInstrumentKey iKey = MakeInstrumentKey(market); var ezi = new EZInstrument(iKey); ezi.Key = iKey; ezi.Name = market.Description; ezi.Description = market.Description; return(ezi); }
public override void UpdateProviderFromPropertyValues() { selectedMarketQuoteItem = prop["QuoteItem"]; ezInstrumentKey instrumentKey = APIFactory.InstrumentKeyFromString(prop["InstrumentKey"]); currentInstrument = APIMain.InstrumentFromKey(instrumentKey); //api.SubscribeToInstrument(instrument.Key); api.OnInsideMarketUpdate += api_OnInsideMarketUpdate; api_OnInsideMarketUpdate(currentInstrument); }
void api_OnInsideMarketUpdate(EZInstrument ezi) { if (ezi == spread) { this.Invoke((MethodInvoker) delegate { lstDisplay.Items.Insert(0, string.Format("bid: {0:0} ask: {1:0} last: {2:0} mid: {3:0}", spread.Bid.ToDouble(), spread.Ask.ToDouble(), spread.Last.ToDouble(), spread.MidPrice.ToDouble())); }); Console.WriteLine("bid: {0:0} ask: {1:0} last: {2:0} mid: {3:0}", spread.Bid, spread.Ask, spread.Last, spread.MidPrice); } }
void api_OnFill(FillOriginator originator, FillAction action, EZInstrument ttInstrument, EZFill fill, EZFill newFill) { //cross thread - so you don't get the cross theading exception if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate { api_OnFill(originator, action, ttInstrument, fill, newFill); }); return; } }
void api_OnOrder(EZOrderStatus status, EZInstrument ttInstrument, EZOrder order, EZOrder newOrder) { //cross thread - so you don't get the cross theading exception if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate { api_OnOrder(status, ttInstrument, order, newOrder); }); return; } }
void SubscribeToInstrument(EZInstrument instrument) { // Look at our TradeDetailTag and determine the MarketQuoteItem that we are // interested in (i.e. LastPrice, BidPrice, AskPrice, etc.) //selectedMarketQuoteItem = quoteItem; //ezInstrumentKey instrumentKey = APIFactory.InstrumentKeyFromString(instrumentKeyStr); //currentInstrument = APIMain.InstrumentFromKey(instrumentKey); currentInstrument = instrument; api.OnInsideMarketUpdate += api_OnInsideMarketUpdate; api_OnInsideMarketUpdate(currentInstrument); }
void api_OnInsideMarketUpdate(EZInstrument instrument) { //cross thread - so you don't get the cross threading exception if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate { api_OnInsideMarketUpdate(instrument); }); return; } Message(string.Format("{0:h:mm:ss}: bid {1} @ {2} ask {3} @ {4} last {5} @ {6} [{7}]", DateTime.Now, instrument.BidQty, instrument.Bid, instrument.AskQty, instrument.Ask, instrument.LastQty, instrument.Last, instrument.Volume)); }
void api_OnInsideMarketUpdate(EZInstrument instrument) { if (instrument == null || currentInstrument == null || instrument.Key != currentInstrument.Key) { return; } if (selectedMarketQuoteItem == null) { return; } if (selectedMarketQuoteItem.Equals("Bid Price")) { UpdateDataValue(instrument.Bid.ToString()); } else if (selectedMarketQuoteItem.Equals("Bid Quantity")) { UpdateDataValue(instrument.BidQty.ToString()); } else if (selectedMarketQuoteItem.Equals("Offer Price")) { UpdateDataValue(instrument.Ask.ToString()); } else if (selectedMarketQuoteItem.Equals("Offer Quantity")) { UpdateDataValue(instrument.AskQty.ToString()); } else if (selectedMarketQuoteItem.Equals("Last Price")) { UpdateDataValue(instrument.Last.ToString()); } else if (selectedMarketQuoteItem.Equals("Last Quantity")) { UpdateDataValue(instrument.LastQty.ToString()); } /*this.Invoke((MethodInvoker)delegate * { * lblBid1.Text = instrument.Bid.ToString(); * lblBidVol1.Text = instrument.BidQty.ToString(); * lblOffer1.Text = instrument.Ask.ToString(); * lblOfferVol1.Text = instrument.AskQty.ToString(); * lblLast1.Text = instrument.Last.ToString(); * lblLastVol1.Text = instrument.LastQty.ToString(); * lblTotalVol1.Text = instrument.Volume.ToString(); * lblNet1.Text = instrument.NetPos.ToString(); * lblBuys1.Text = instrument.NetBuys.ToString(); * lblSells1.Text = instrument.NetSells.ToString(); * });*/ }
void api_OnTimeAndSales(EZInstrument ttInstrument, DateTime timeStamp, Price LTP, Quantity LTQ, TradeDirection direction, bool isOTC) { #region Thread Safety //cross thread - so you don't get the cross theading exception if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate { api_OnTimeAndSales(ttInstrument, timeStamp, LTP, LTQ, direction, isOTC); }); return; } #endregion }
void api_OnMarketDepth(EZInstrument ttInstrument, EZMarketDepth marketDepth) { #region Thread Safety //cross thread - so you don't get the cross theading exception if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate { api_OnMarketDepth(ttInstrument, marketDepth); }); return; } #endregion }
void api_OnInsideMarketUpdate(EZInstrument instrument) { #region Thread Safety //cross thread - so you don't get the cross theading exception if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate { api_OnInsideMarketUpdate(instrument); }); return; } #endregion }
public void Sell(EZInstrument instrument, int quantity, string strategyName) { if (strategyName != null) { executionStatus[strategyName] = new ExecutionStatus(strategyName); } ezPrice bid = instrument.Bid; EZOrder ezo = api.SellLimit(instrument, quantity, bid, strategyName); StoreOrder(strategyName, ezo); Spy.Print("SELL: {0} @ {1}", quantity, bid); }
public void Buy(EZInstrument instrument, int quantity, string strategyName) { if (strategyName != null) { executionStatus[strategyName] = new ExecutionStatus(strategyName); executionStatus[strategyName].quantitySubmitted = quantity; } ezPrice ask = instrument.Ask; EZOrder ezo = api.BuyLimit(instrument, quantity, ask, strategyName); StoreOrder(strategyName, ezo); Spy.Print("BUY: {0} @ {1}", quantity, ask); }
private void RequestChartData(EZInstrument instrument, zChartInterval interval, int period) { // Set EndDate to the current trading date. //DateTime dtEndDate = selectedContract.GetTradeDate(DateTime.Now); DateTime dtEndDate = DateTime.Now; DateTime dtStartDate; zChartInterval enBarInterval = zChartInterval.Hour; if (interval == zChartInterval.Day) { enBarInterval = zChartInterval.Day; // User select Day bars, load a few months of them. dtStartDate = dtEndDate.AddMonths(-3); } else { enBarInterval = interval; // User selected non-Day bars (Hour, Minute, etc.), load a couple of days of them. dtStartDate = dtEndDate; dtStartDate = dtStartDate.AddDays(-3); /*// This little loop here will ensure that we load the previous trade date as well as today and will account for weekends * // and holidays. * while ((selectedContract.GetTradeDate(dtStartDate) == dtEndDate)) * { * dtStartDate = dtStartDate.AddDays(-1); * }*/ } // Create a BarInterval object to tell the API what bar interval we want. // So for example, if we wanted a 15 minute bar, we would do: New ezBarInterval(zChartDataType.Minute, 15) ezBarInterval oBarIntvl = new ezBarInterval(enBarInterval, period); string chartName = instrument.Name + " : " + oBarIntvl; IChartDataProvider provider = new ChartDataProviderCTS(chartName, oBarIntvl, ezSessionTimeRange.Empty); if (LoadingNewChart != null) { LoadingNewChart(provider); } this.SetChartDataProvider(provider); WinForms.SetWaitCursor(true); provider.LoadHistoricalChartData(APIMain.MarketFromInstrument(instrument), dtStartDate, dtEndDate); }
void api_OnInsideMarketUpdate(EZInstrument instrument) { if (instrument == null || currentInstrument == null || instrument.Key != currentInstrument.Key) { return; } if (selectedMarketQuoteItem == null) { return; } if (selectedMarketQuoteItem.Equals("BidPrice")) { UpdateDataValuePrice(instrument.Bid.ToString()); } else if (selectedMarketQuoteItem.Equals("BidQty")) { UpdateDataValuePrice(instrument.BidQty.ToString()); } else if (selectedMarketQuoteItem.Equals("AskPrice")) { UpdateDataValuePrice(instrument.Ask.ToString()); } else if (selectedMarketQuoteItem.Equals("AskQuantity")) { UpdateDataValuePrice(instrument.AskQty.ToString()); } else if (selectedMarketQuoteItem.Equals("LastPrice")) { UpdateDataValuePrice(instrument.Last.ToString()); } else if (selectedMarketQuoteItem.Equals("LastQty")) { UpdateDataValuePrice(instrument.LastQty.ToString()); } else if (selectedMarketQuoteItem.Equals("MidPrice")) { UpdateDataValuePrice(instrument.MidPrice.ToString()); } else if (selectedMarketQuoteItem.Equals("CurrentTime")) { UpdateDataValueTime(); } }
/// <summary> /// I'm setting the WaitCursor here (especially for the first time the /// market dialog loads, it can be a little slow). The "finally" should /// ensure that we are never left hanging with the WaitCursor. But I /// will also attempt to set the cursor back to default within the /// ShowInstrumentDialog method (and/or the showing of the form). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSelectMarket_Click(object sender, EventArgs e) { txtMarket.Text = "Loading Market Chooser..."; Application.DoEvents(); Cursor.Current = Cursors.WaitCursor; Cursor.Show(); try { // Store the existing trade instrument in case we want to // change it back (if the user cancels the market selection // dialog, for instance). EZInstrument storeTradeInstrument = tradeInstrument; tradeInstrument = api.ShowInstrumentDialog(); if (tradeInstrument != null) { txtMarket.Text = tradeInstrument.Name; } else { // User cancelled the market selection dialog, so let's // try to restore the previously selected trade instrument // (which may have been null - so handle that also). tradeInstrument = storeTradeInstrument; if (tradeInstrument == null) { txtMarket.Text = "(no market selected)"; } else { txtMarket.Text = tradeInstrument.Name; } } } finally { Cursor.Current = Cursors.Default; Cursor.Show(); } }
public override void UpdateProviderFromPropertyValues() { //selectedMarketData = prop["QuoteItem"]; ezInstrumentKey instrumentKey = APIFactory.InstrumentKeyFromString(prop["InstrumentKey"]); // Get historical data for 1-hour "bars". EZInstrument instrument = APIMain.InstrumentFromKey(instrumentKey); zChartInterval interval = zChartInterval.Hour; int period = 1; // TODO analyze different time periods (ex: different hours of the trading session) to // get a better "AverageVolumePerTimePeriod" calculation. EZChartDataSeries historicalData = api.RequestHistoricalData(instrument, interval, period); if (historicalData == null) { averageVolumePerTimePeriod = prop["AverageVolumePerTimePeriod"] ?? 0; timePeriodLength = prop["TimePeriodLengthMinutes"] ?? 0.0; } else { int totalVolume = 0; int volumeCount = 0; foreach (ezBarDataPoint dp in historicalData.TradeBars) { totalVolume += dp.Volume; ++volumeCount; } double averageVolumePerHour = (double)totalVolume / (double)volumeCount; timePeriodLength = 5.0; // five minutes averageVolumePerTimePeriod = (int)Math.Round(averageVolumePerHour / 20.0); } currentInstrument = APIMain.InstrumentFromKey(instrumentKey); //api.SubscribeToInstrument(instrument.Key); api.OnInsideMarketUpdate += api_OnInsideMarketUpdate; api_OnInsideMarketUpdate(currentInstrument); }
public void SetTradeInstrument(EZInstrument instrument) { tradeInstrument = instrument; FireUpdateEvent(); }