//Снятие заявки private void DataGridViewOrders_DoubleClick(object sender, EventArgs e) { try { var MouseEvent = (MouseEventArgs)e; var dataGrid = (DataGridView)sender; dataGrid.ClearSelection(); if (MouseEvent.Button == MouseButtons.Right) { var hti = dataGrid.HitTest(MouseEvent.X, MouseEvent.Y); int index = hti.RowIndex; if (index >= 0) { DataGridViewRow row = dataGrid.Rows[index]; row.Selected = true; MThread.InitThread(() => { decimal number = Convert.ToDecimal(row.Cells[2].Value.ToString()); var sec = Trader.Objects.tSecurities.SearchFirst(s => s == row.Cells[3].Value); if (sec != null) { Trader.CancelOrder(sec, number); } }); } } } catch (Exception ee) { MessageBox.Show(ee.ToString()); } }
private void dataGridViewStopOrders_DoubleClick(object sender, EventArgs e) { var MouseEvent = (MouseEventArgs)e; var dataGrid = (DataGridView)sender; dataGrid.ClearSelection(); if (MouseEvent.Button == MouseButtons.Right) { var hti = dataGrid.HitTest(MouseEvent.X, MouseEvent.Y); int index = hti.RowIndex; if (index >= 0) { DataGridViewRow row = dataGrid.Rows[index]; row.Selected = true; MThread.InitThread(() => { decimal number = Convert.ToDecimal(row.Cells[1].Value.ToString()); var sec = this.SearchSecurity(row.Cells[2].Value.ToString()); if (sec != null) { Trader.CancelStopOrder(sec, number); } }); } } }
/// <summary> /// Показать рыночное сообщение /// </summary> /// <param name="Msg"></param> public void ShowTransReply(string Msg) { if (this.TrElement.NotIsNull()) { if (threadMsg.NotIsNull()) { threadMsg.Abort(); threadMsg = null; } panelMessage.GuiAsync(() => { panelMessage.Visible = true; textBoxMessage.Text = Msg; this.SetBottomMessage(Msg); }); MThread.InitThread(() => { Thread.Sleep(4000); panelMessage.GuiAsync(() => { panelMessage.Visible = false; }); }); } }
public void PostInit() { Ctx.m_instance.m_resizeMgr.addResizeObject(Ctx.m_instance.m_uiMgr as IResizeObject); //m_tickMgr.AddTickObj(m_inputMgr as ITickedObject); Ctx.m_instance.m_inputMgr.postInit(); Ctx.m_instance.m_tickMgr.addTick(Ctx.m_instance.m_playerMgr as ITickedObject); Ctx.m_instance.m_tickMgr.addTick(Ctx.m_instance.m_monsterMgr as ITickedObject); Ctx.m_instance.m_tickMgr.addTick(Ctx.m_instance.m_fObjectMgr as ITickedObject); Ctx.m_instance.m_tickMgr.addTick(Ctx.m_instance.m_npcMgr as ITickedObject); Ctx.m_instance.m_tickMgr.addTick(Ctx.m_instance.m_spriteAniMgr as ITickedObject); Ctx.m_instance.m_tickMgr.addTick(Ctx.m_instance.m_sceneEffectMgr as ITickedObject); Ctx.m_instance.m_tickMgr.addTick(Ctx.m_instance.m_sceneCardMgr as ITickedObject); //Ctx.m_instance.m_tickMgr.addTick(Ctx.m_instance.m_aiSystem.aiControllerMgr as ITickedObject); Ctx.m_instance.m_uiMgr.findCanvasGO(); Ctx.m_instance.m_dataPlayer.m_dataPack.postConstruct(); Ctx.m_instance.m_dataPlayer.m_dataCard.registerCardAttr(); // 注册卡牌组属性 Ctx.m_instance.m_resLoadMgr.postInit(); Ctx.m_instance.m_TaskQueue.m_pTaskThreadPool = Ctx.m_instance.m_TaskThreadPool; Ctx.m_instance.m_TaskThreadPool.initThreadPool(2, Ctx.m_instance.m_TaskQueue); // 获取主线程 ID MThread.getMainThreadID(); }
public void AutoOrdersLoopControl() { MThread.InitThread(() => { foreach (var ord in ObjAutoOrders.ToArray) { var sec = GetSecCodeAndClass(ord.SecAndCode); if (sec.NotIsNull()) { Order order = null; if (ord.CondAutoOrder == AutoOrders.CondAutoOrder.MoreOrEquals) { if (sec.LastPrice >= ord.PriceCondition) { order = new Order() { Sec = sec, Direction = ord.Direction, Price = ord.Price, Volume = (int)ord.Volume, ClientCode = ord.Comment }; } } else if (ord.CondAutoOrder == AutoOrders.CondAutoOrder.LessOrEquals) { if (sec.LastPrice <= ord.PriceCondition) { order = new Order() { Sec = sec, Direction = ord.Direction, Price = ord.Price, Volume = (int)ord.Volume, ClientCode = ord.Comment }; } } if (order.NotIsNull()) { ObjAutoOrders.Delete(ord); Trader.CreateOrder(order); SignalView.GSMSignaler.SendSignalCall(); textBoxLogSign.GuiAsync(() => { textBoxLogSign.Text = DateTime.Now.ToString() + " AutoOrder: " + order.Sec.Shortname + "(" + order.Sec.Code + ")" + ", Price: " + order.Price + " (" + order.Volume + ")" + ", " + (order.IsBuy() ? "BUY" : "SELL") + ", " + order.ClientCode + "\r\n" + textBoxLogSign.Text; }); } } } }); }
private void buttonSignTestDev_Click(object sender, EventArgs e) { SignalView.GSMSignaler.SendTestSignal(); MThread.InitThread(() => { Thread.Sleep(1000); SignalView.GSMSignaler.SendTestSignal(false); }); }
private void buttonSignTestCall_Click(object sender, EventArgs e) { SignalView.GSMSignaler.SendSignalCall(); MThread.InitThread(() => { Thread.Sleep(15000); SignalView.GSMSignaler.SendSignalResetCall(); }); }
private void ToolStripMenuItemTestSign_Click_1(object sender, EventArgs e) { SignalView.GSMSignaler.SendTestSignal(); MThread.InitThread(() => { Thread.Sleep(1000); SignalView.GSMSignaler.SendTestSignal(false); }); }
private void ToolStripMenuItemSignCall_Click(object sender, EventArgs e) { SignalView.GSMSignaler.SendSignalCall(); MThread.InitThread(() => { Thread.Sleep(15000); SignalView.GSMSignaler.SendSignalResetCall(); }); }
/*private void InitFormCreateOrders() * { * try * { * this.OnTimer2s += () => * { * if (CreateOrderSec != null) * { * var pos = Trader.Objects.Positions.FirstOrDefault(p => p.Sec == CreateOrderSec); * OrdersLastPrice.GuiAsync(() => * { * if (CreateOrderSec != null) * if (CreateOrderSec.LastTrade != null) * OrdersLastPrice.Text = CreateOrderSec.LastTrade.Price.ToString(); * if (pos != null) * { * labelPosSec.Text = pos.Data.CurrentNet.ToString(); * labelOrdersCountOrder.Text = pos.Data.OrdersBuy.ToString() + " / " + pos.Data.OrdersSell.ToString(); * } * else * { * labelPosSec.Text = "0"; * labelOrdersCountOrder.Text = "0"; * } * }); * } * }; * * OrdersSetPrice.InitWheelDecimal(); * OrdersSetVolume.InitWheelDecimal(); * * textBoxOrderFindSec.TextChanged += (sen, e) => * { * var textBox_fs = (TextBox)sen; * string secCode = textBox_fs.Text; * this.SelectSecurity(secCode); * }; * } * catch (Exception ee) * { * MessageBox.Show(ee.ToString()); * } * }*/ /// <summary> /// Переключатель на нужный инструмент /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /*private void labelOrdersClass_Click(object sender, EventArgs e) * { * try * { * if (CreateOrderSec != null) * { * * if (labelOrdersClass.Tag == null) labelOrdersClass.Tag = 0; * int index = (int)labelOrdersClass.Tag; * var listSec = Trader.Objects.Securities.Where(s => s.Code == CreateOrderSec.Code).ToArray(); * if (listSec.Length > 0) * { * if (index >= listSec.Length) index = 0; * var classSec = listSec.ElementAt(index); * this.SelectSecurity(CreateOrderSec.Code, classSec.Class.Code); * index++; * labelOrdersClass.Tag = index; * } * } * } * catch (Exception ee) * { * MessageBox.Show(ee.ToString()); * } * }*/ /// <summary> /// Осуществляет поиск и подстановку значений в формы нужно инструмента. /// </summary> /// <param name="secCode"></param> /*private void SelectSecurity(string secCode, string secClass = "") * { * try * { * Securities sec = null; * if (secClass != "") * { * sec = this.SearchSecurity(secCode, secClass); * } * else * { * sec = this.SearchSecurity(secCode); * } * if (sec != null) * { * CreateOrderSec = sec; * * labelOrdersSec.Text = CreateOrderSec.Code; * labelOrdersClass.Text = CreateOrderSec.Class.Code; * if (CreateOrderSec.LastTrade != null) * { * OrdersLastPrice.Text = CreateOrderSec.LastTrade.Price.ToString(); * OrdersSetPrice.Value = CreateOrderSec.LastTrade.Price; * } * } * else * { * labelOrdersSec.Text = "---"; * labelOrdersClass.Text = secClass; * OrdersLastPrice.Text = "0"; * OrdersSetPrice.Value = 0; * } * } * catch (Exception ee) * { * MessageBox.Show(ee.ToString()); * } * }*/ /*private void dataGridViewOrders_SelectionChanged(object sender, EventArgs e) * { * try * { * var dataGrid = (DataGridView)sender; * DataGridViewRow selectRow = null; * foreach (var r in dataGrid.SelectedRows) * selectRow = (DataGridViewRow)r; * if (selectRow != null) * { * CreateOrderSec = (Securities)selectRow.Cells[3].Value; * OrdersSetPrice.DecimalPlaces = CreateOrderSec.Scale; * OrdersSetPrice.Increment = CreateOrderSec.Params.MinPriceStep; * OrdersSetPrice.Value = Convert.ToDecimal(selectRow.Cells[5].Value); * OrdersSetVolume.Value = Convert.ToDecimal(selectRow.Cells[6].Value); * * textBoxOrderFindSec.Text = CreateOrderSec.Code; * } * } * catch (Exception ee) * { * MessageBox.Show(ee.ToString()); * } * }*/ /*private void buttonOrderCreateBuy_Click(object sender, EventArgs e) * { * try * { * if (CreateOrderSec != null && OrdersSetPrice.Value > 0 && OrdersSetVolume.Value > 0) * { * Common.Ext.NewThread(() => * { * Trader.CreateOrder(new Order() * { * Price = OrdersSetPrice.Value, * Volume = Convert.ToInt32(OrdersSetVolume.Value), * Direction = OrderDirection.Buy, * Sec = CreateOrderSec * }); * }); * } * } * catch (Exception ee) * { * MessageBox.Show(ee.ToString()); * } * }*/ /*private void buttonOrderCreateSell_Click(object sender, EventArgs e) * { * try * { * if (CreateOrderSec != null && OrdersSetPrice.Value > 0 && OrdersSetVolume.Value > 0) * { * Common.Ext.NewThread(() => * { * Trader.CreateOrder(new Order() * { * Price = OrdersSetPrice.Value, * Volume = Convert.ToInt32(OrdersSetVolume.Value), * Direction = OrderDirection.Sell, * Sec = CreateOrderSec * }); * }); * } * } * catch (Exception ee) * { * MessageBox.Show(ee.ToString()); * } * }*/ /* private void OrdersLastPrice_Click(object sender, EventArgs e) * { * OrdersSetPrice.Value = Convert.ToDecimal(OrdersLastPrice.Text); * }*/ private void ButtonOrdersCancelAll_Click(object sender, EventArgs e) { if (CreateOrderSec != null) { MThread.InitThread(() => { Trader.CancelAllOrder(CreateOrderSec); }); } }
private void buttonMimize20s_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; MThread.InitThread(() => { Thread.Sleep(20000); this.GuiAsync(() => { this.WindowState = FormWindowState.Normal; }); }); }
/// <summary> Флаг определяющий, была ли загружена история.</summary> //public bool WasReadHistory = false; /// <summary> Флаг определяющий контроль за сделками, для избежания дубликатов </summary> //public bool ControlTrades = false; /// <summary> Запись коллекции в сериализованном виде. </summary> /// <param name="filename"></param> public bool WriteCollectionInFile(string filename) { MThread.InitThread(() => { object obj = null; lock (syncLock) { obj = this.ObjCollection.Collection.Clone(); } this.TimeLastSave = DateTime.Now; Stream stream = File.Open(filename, FileMode.Create); var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binaryFormatter.Serialize(stream, obj); stream.Close(); }); return(true); }
private void buttonExitPos_Click(object sender, EventArgs e) { if (Securities.NotIsNull()) { var pos = Trader.Objects.tPositions.SearchFirst(p => p.Sec == Securities); if (pos != null) { if (pos.CurrentVolume != 0) { MThread.InitThread(() => { OrderDirection?direction = pos.IsBuy() ? OrderDirection.Sell : OrderDirection.Buy; decimal LastPrice = Securities.Params.LastPrice; decimal Price = direction == OrderDirection.Sell ? Price = LastPrice - Securities.Params.MinPriceStep * 5 : LastPrice + Securities.Params.MinPriceStep * 5; this.GuiAsync(() => { var clientCode = comboBoxCodeClient.SelectedItem.NotIsNull() ? comboBoxCodeClient.SelectedItem.ToString() : ""; Trader.CreateOrder(new Order() { Sec = Securities, Direction = direction, Price = Price, Volume = pos.CurrentVolume, ClientCode = clientCode }); }); }); } else { ShowTransReply("По данному инструменту нет позиций."); } } } }
public static void Setup() { if (_ready) { return; } Console.WriteLine("MStats.Setup"); _ready = true; _mSpanHeapHandle = Marshal.AllocHGlobal((IntPtr)MAX_HEAP_SIZE); _mSpanHeap = (MSpan *)_mSpanHeapHandle.ToPointer(); _mThreadIdx = 0; _threadID = new ThreadLocal <int>(); _mThreadMap = new ConcurrentDictionary <int, int>(); for (int i = 0; i < _mThread.Length; i++) { _mThread[i] = new MThread(_mSpanHeap + (MAX_THREAD_HEAP_SIZE * i)); } AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnAppExit); }
/// <summary>Отрисовка всего графика </summary> /// <param name="graphic">Полотно</param> protected void PaintAll() { if (!Candels.IssetCollection()) { return; } GetMinMax(); //Отрисовка свечей в приоритете Candels.PaintCandles(); RightPrices.Paint(RightPrices.Panel.Params.MaxPrice, RightPrices.Panel.Params.MinPrice); if (ActiveCandles.ActiveCandle1.NotIsNull() && ActiveCandles.ActiveCandle2.NotIsNull()) { if (ActiveCandles.ActiveCandle1.dataCandle.Index > ActiveCandles.ActiveCandle2.dataCandle.Index) { GHorVolumes.activeCandle1 = ActiveCandles.ActiveCandle1; GHorVolumes.activeCandle2 = ActiveCandles.ActiveCandle2; } else { GHorVolumes.activeCandle1 = ActiveCandles.ActiveCandle2; GHorVolumes.activeCandle2 = ActiveCandles.ActiveCandle1; } if (TypeHorVolume == 3) { GHorVolumes.activeCandle2 = null; } } CandleInfo LastCandle = null; Levels.Panel.Clear(); var leftCandle = Candels.AllDataPaintedCandle.Last(); var rightCandle = Candels.AllDataPaintedCandle.First(); //Паинт foreach (var dCandle in Candels.AllDataPaintedCandle.ToArray()) { dCandle.PrevCandleInfo = LastCandle; Volumes.PaintByCandle(dCandle); GHorVolumes.EachCandle(dCandle); Levels.PaintByCandle(dCandle, leftCandle, rightCandle, Candels.AllDataPaintedCandle.Count); Indicators.ForEach((ind) => { if (ind is Indicator) { ((Indicator)ind).EachFullCandle(dCandle); } }); LastCandle = dCandle; } LevelsOrders.Paint(); Levels.Paint(); ActualizeActiveCandle(); if (ThreadPaintHotVol.NotIsNull()) { ThreadPaintHotVol.Abort(); ThreadPaintHotVol = null; } if (ThreadPaintHotVol.IsNull()) { ThreadPaintHotVol = MThread.InitThread(() => { GHorVolumes.CollectionCandles = Candels.AllDataPaintedCandle; if (TypeHorVolume == 1) { if (ActiveCandles.ActiveCandle1.NotIsNull()) { GHorVolumes.PaintHorVolEachBlock(ActiveCandles.ActiveCandle1.dataCandle.Index + 1); } } else if (TypeHorVolume == 2 || TypeHorVolume == 3) { GHorVolumes.PaintHorVolByPeriodCandleDelta(false, false); } else if (TypeHorVolume == 5) { GHorVolumes.PaintHorVolByPeriodCandleDelta(false, true, limitHorVol); } else if (TypeHorVolume == 4) { GHorVolumes.PaintCollectionHVol(); } ThreadPaintHotVol = null; }); } ToCanvas(); }
/// <summary> Обновление стакана </summary> public void UpdateDepth() { if (TrElement.IsNull()) { return; } int count = 20; var orders = Trader.Objects.tOrders .SearchAll(o => o.Sec == TrElement.Security && o.Status == OrderStatus.ACTIVE); var ordersBuy = orders.Where(o => o.Direction == OrderDirection.Buy) .OrderByDescending(o => o.Price).ToArray(); var ordersSell = orders.Where(o => o.Direction == OrderDirection.Sell) .OrderBy(o => o.Price).ToArray(); var pricesBuy = ordersBuy.Select(o => o.Price).Take(count).ToArray(); var pricesSell = ordersSell.Select(o => o.Price).Take(count).ToArray(); if (ArraySell.IsNull()) { ArraySell = new DataGridViewRow[count]; for (int i = count - 1; i >= 0; i--) { var k = dataGridViewDepth.Rows.Add(); ArraySell[i] = dataGridViewDepth.Rows[k]; ArraySell[i].Cells[0].Value = ""; ArraySell[i].Cells[1].Value = ""; ArraySell[i].Cells[2].Value = ""; ArraySell[i].Cells[3].Value = ""; ArraySell[i].Cells[2].Style.BackColor = Color.LightCoral; ArraySell[i].Cells[1].Style.Font = new Font(DataGridView.DefaultFont, FontStyle.Regular); } } if (ArrayBuy.IsNull()) { ArrayBuy = new DataGridViewRow[count]; for (int i = 0; i < count; i++) { var k = dataGridViewDepth.Rows.Add(); ArrayBuy[i] = dataGridViewDepth.Rows[k]; ArrayBuy[i].Cells[0].Value = ""; ArrayBuy[i].Cells[1].Value = ""; ArrayBuy[i].Cells[2].Value = ""; ArrayBuy[i].Cells[3].Value = ""; ArrayBuy[i].Cells[2].Style.BackColor = Color.LightGreen; ArrayBuy[i].Cells[1].Style.Font = new Font(DataGridView.DefaultFont, FontStyle.Regular); } } MThread.InitThread(() => { //Синхронизуируем между потоками dataGridViewDepth.GuiAsync(() => { if (ArraySell.NotIsNull()) { //Наполняем Sell for (int i = 0; i < ArraySell.Length; i++) { var row = ArraySell[i]; if (pricesSell.Length <= i) { ArraySell[i].Cells[2].Value = ""; ArraySell[i].Cells[1].Value = ""; ArraySell[i].Cells[1].Tag = null; ArraySell[i].Cells[3].Tag = null; continue; } var ordersByPrice = ordersSell.Where(o => o.Price == pricesSell[i]).ToArray(); var volOrders = ordersByPrice.Sum(o => o.Balance); decimal Price = pricesSell[i]; int Volume = volOrders; int countOrd = ordersByPrice.Count(); ArraySell[i].Cells[2].Value = Price.ToString(); ArraySell[i].Cells[1].Value = countOrd.ToString() + " (" + Volume.ToString() + ")"; ArraySell[i].Cells[1].Tag = new StructClickDepth() { Flag = "sell", Price = Price, Volume = Volume, }; ArraySell[i].Cells[3].Tag = new StructClickDepth() { Flag = "buy", Price = Price, Volume = Volume, }; } } if (ArrayBuy.NotIsNull()) { //Наполняем Buy for (int i = 0; i < ArrayBuy.Length; i++) { var row = ArrayBuy[i]; if (pricesBuy.Length <= i) { ArraySell[i].Cells[2].Value = ""; ArraySell[i].Cells[1].Value = ""; ArraySell[i].Cells[1].Tag = null; ArraySell[i].Cells[3].Tag = null; continue; } var ordersByPrice = ordersBuy.Where(o => o.Price == pricesBuy[i]).ToArray(); var volOrders = ordersByPrice.Sum(o => o.Balance); decimal Price = pricesBuy[i]; int Volume = volOrders; int countOrd = ordersByPrice.Count(); ArrayBuy[i].Cells[2].Value = Price.ToString(); ArrayBuy[i].Cells[3].Value = countOrd.ToString() + " (" + Volume.ToString() + ")"; ArrayBuy[i].Cells[1].Tag = new StructClickDepth() { Flag = "sell", Price = Price, Volume = Volume, }; ArrayBuy[i].Cells[3].Tag = new StructClickDepth() { Flag = "buy", Price = Price, Volume = Volume, }; } } }); }); }
private void EventStrategy() { if (checkBoxFGActivate.Checked) { if (threadStrategy.IsNull() || threadStrategy.ThreadState == ThreadState.Stopped) { if (DataTrading.Collection.Count() == 0) { return; } if (FastGapSettings.StepTime == 0) { return; } threadStrategy = MThread.InitThread(() => { var allStocks = DataTrading.Collection.ToArray(); foreach (var elem in allStocks) { if (elem.ListStrategy.Count > 0) { foreach (var stg in elem.ListStrategy) { if (stg is Strategy.Strategy) { var strategy = (Strategy.Strategy)stg; strategy.StepTime = FastGapSettings.StepTime; strategy.TimeFrame = FastGapSettings.TimeFrame; strategy.IndexStartCandle = FastGapSettings.IndexStartCandle; strategy.Option_1 = FastGapSettings.Option_1; strategy.Option_2 = FastGapSettings.Option_2; strategy.Option_3 = FastGapSettings.Option_3; var now = DateTime.Now; if (strategy.TimeLastAction < now.AddSeconds(strategy.StepTime * -1)) { var tf = elem.StorageTF.GetTimeFrame(strategy.TimeFrame); strategy.Security = elem.Security; strategy.BeforeAction(() => { }); var log = strategy.ActionCollection(tf.Candles.Collection); strategy.TimeLastAction = now; if (!log.Empty()) { showLog = true; this.FastGapLog = log + this.FastGapLog; } } } Thread.Sleep(1); } } } threadStrategy = null; }); if (showLog) { showLog = false; Form_MessageSignal.Show(this.FastGapLog, null); textBoxFGLog.Text = this.FastGapLog; } } } }
/// <summary> /// Проверка и выставление стоп-ордера /// </summary> /// <param name="Price"></param> /// <param name="volume"></param> public void SetStopOrder(decimal Price, int volume, bool checkSet = true) { if (Price == 0) { ShowTransReply("Некорректная цена стоп-ордера!"); return; } if (volume == 0) { ShowTransReply("Не текущих позиций!"); return; } decimal stepStop = Securities.Params.MinPriceStep * 20; if (volume < 0) { stepStop = stepStop * -1; volume = volume * -1; } var stopOrder = new StopOrder() { Sec = Securities, Price = Price - stepStop, Volume = volume, ConditionPrice = Price, DateExpiry = DateMarket.ExtractDateTime(dateTimePickerStopOrder.Value), ClientCode = ClientCode.Value, Comment = Define.STOP_LOSS }; if (this.Position.IsBuy() && Price > 0) { stopOrder.Direction = OrderDirection.Sell; if (Price > Securities.LastPrice) { ShowTransReply("Не корректная цена стоп заявки! Необходимо указать цену ниже текущей."); return; } } if (this.Position.IsSell() && Price > 0) { stopOrder.Direction = OrderDirection.Buy; if (Price < Securities.LastPrice) { ShowTransReply("Не корректная цена стоп заявки! Необходимо указать цену выше текущей."); return; } } //Устанавливаем в форму значение стоп цены this.GuiAsync(() => { numericUpDownStopPrice.Value = Price; }); MThread.InitThread(() => { var cancelOrders = this.Trader.Objects.tStopOrders.SearchAll(so => so.Sec == Securities && so.IsActive() && so.Comment.Contains(Define.STOP_LOSS)); if (cancelOrders.NotIsNull()) { this.Trader.CancelListStopOrders(cancelOrders); } Thread.Sleep(500); this.Trader.CreateStopOrder(stopOrder, StopOrderType.StopLimit); if (checkSet) { Thread.Sleep(10000); var allStopOrders = this.Trader.Objects.tStopOrders.SearchAll(so => so.Sec == Securities && so.IsActive()); if (allStopOrders.NotIsNull()) { if (allStopOrders.Count() == 0) { this.SetStopOrder(Price, volume, false); } } } }); }
protected void SendStopOrder(PanelControl panel, bool autoStop = false, bool showInfo = false) { if (autoStop) { if (panel.LastSendStopOrder > DateTime.Now.AddSeconds(-5)) { //Для избежания многократного выставления return; } } var pos = Parent.Trader.Objects.tPositions.SearchFirst(p => p.Sec == panel.TrElement.Security); decimal stepStop = panel.TrElement.Security.Params.MinPriceStep * 20; int volume = pos.NotIsNull() ? pos.Data.CurrentNet : 0; if (volume < 0) { stepStop = stepStop * -1; volume = volume * -1; } //Просмотр инфо по будущему стопу if (showInfo) { string text = "Инфо создаваемой стоп заявки:\n"; text += "Позиций: " + pos.Data.CurrentNet + "\n\n"; text += "Стоп цена: " + panel.PriceStop.Value + "\n"; text += "Цена исполнения: " + (panel.PriceStop.Value - stepStop) + "\n"; text += "Объем: " + volume + "\n"; text += "Дата завершения: " + DateTime.Now.AddDays(1).ToShortDateString() + "\n"; MessageBox.Show(text); return; } if (panel.PriceStop.Value == 0) { SetMessage("Некорректная цена стоп-ордера!"); return; } if (volume == 0) { SetMessage("Не текущих позиций!"); return; } var stopOrder = new StopOrder() { Sec = panel.TrElement.Security, Price = panel.PriceStop.Value - stepStop, Volume = volume, Direction = volume > 0 ? OrderDirection.Sell : OrderDirection.Buy, ConditionPrice = panel.PriceStop.Value, DateExpiry = DateMarket.ExtractDateTime(DateTime.Now.AddDays(1)), Comment = Define.STOP_LOSS }; var lastPrice = panel.TrElement.Security.LastPrice; if (lastPrice > 0) { if (pos.IsBuy() && panel.PriceStop.Value > 0) { stopOrder.Direction = OrderDirection.Sell; if (panel.PriceStop.Value > lastPrice) { SetMessage("Не корректная цена стоп заявки! Необходимо указать цену ниже текущей."); return; } } if (pos.IsSell() && panel.PriceStop.Value > 0) { stopOrder.Direction = OrderDirection.Buy; if (panel.PriceStop.Value < lastPrice) { SetMessage("Не корректная цена стоп заявки! Необходимо указать цену выше текущей."); return; } } } MThread.InitThread(ThreadPriority.Normal, () => { Qlog.CatchException(() => { Thread.Sleep(1000); var countClosed = CancelAllStopOrders(panel); Thread.Sleep(1000); Parent.Trader.CreateStopOrder(stopOrder, StopOrderType.StopLimit); addSignalByStop(stopOrder); }); }); panel.LastSendStopOrder = DateTime.Now; }
private void buttonLoadTicks_Click(object sender, EventArgs e) { OpenFileDialog file = new OpenFileDialog(); file.Multiselect = true; file.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; file.FilterIndex = 2; file.RestoreDirectory = true; if (file.ShowDialog() == DialogResult.OK) { try { labelStatusLoad.GuiAsync(() => { labelStatusLoad.Text = ""; }); int CountFiles = file.FileNames.Length; int CountStat = CountFiles; threadLoadHistory = MThread.InitThread(() => { Qlog.CatchException(() => { foreach (string filename in file.FileNames) { WFile wf = new WFile(filename); var arrayAll = wf.ReadAllLines(); labelStatusLoad.GuiAsync(() => { labelStatusLoad.Text = filename + "\r\n" + labelStatusLoad.Text; progressBalLoadHistory.Maximum = arrayAll.Length + 1; progressBalLoadHistory.Value = 1; }); int counterRow = 0; int numStep = 0; foreach (var str in arrayAll) { if (counterRow == 0) { counterRow++; continue; //пропускаем шапку } var tr = Trade.GetConvertTrade(Securities, str); //Корректируем значения var modifyTrade = ModifyLoadTrade(tr); if (modifyTrade.NotIsNull()) { TrElement.NewTrade(tr, true); if (numStep > 5000) { progressBalLoadHistory.GuiAsync(() => { if (counterRow < progressBalLoadHistory.Maximum) { progressBalLoadHistory.Value = counterRow; } }); Thread.Sleep(2); numStep = 0; } numStep++; } counterRow++; } CountStat--; labelStatusLoad.GuiAsync(() => { labelStatusLoad.Text = "Process: " + CountStat + "/" + CountFiles + "\r\n" + labelStatusLoad.Text; }); } }); }); labelStatusLoad.GuiAsync(() => { labelStatusLoad.Text = "Files: " + CountFiles + "\r\n" + labelStatusLoad.Text; }); } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }
/// <summary> Кликеры по таблице стакана </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGridViewDepth_Click(object sender, EventArgs e) { if (Securities.IsNull()) { return; } var MouseEvent = (MouseEventArgs)e; var dataGrid = (DataGridView)sender; dataGrid.ClearSelection(); var hti = dataGrid.HitTest(MouseEvent.X, MouseEvent.Y); int indexRow = hti.RowIndex; int indexCol = hti.ColumnIndex; if (indexRow < 0 || indexCol < 0) { return; } DataGridViewCell cell = dataGrid.Rows[indexRow].Cells[indexCol]; if (MouseEvent.Button == MouseButtons.Left) { if (cell.Tag != null) { int Volume = Convert.ToInt32(numericUpDownVolume.Value); if (Volume == 0) { ShowTransReply("Не указан объем!"); } if (cell.Tag.GetType().ToString().Contains("StructClickDepth")) { var data = (StructClickDepth)cell.Tag; OrderDirection?direction = null; if (data.Flag == "buy") { direction = OrderDirection.Buy; } if (data.Flag == "sell") { direction = OrderDirection.Sell; } var clientCode = comboBoxCodeClient.SelectedItem.NotIsNull() ? comboBoxCodeClient.SelectedItem.ToString() : ""; MThread.InitThread(() => { Trader.CreateOrder(new Order() { Sec = Securities, Direction = direction, Price = data.Price, Volume = Volume, ClientCode = clientCode }); }); } } } if (MouseEvent.Button == MouseButtons.Right) { if (cell.Tag != null) { if (cell.Tag.GetType().ToString().Contains("StructClickDepth")) { var data = (StructClickDepth)cell.Tag; if (data.Flag == "buy" || data.Flag == "sell") { MThread.InitThread(() => { var ords = Trader.Objects.tOrders.SearchAll(o => o.Sec == Securities && o.Price == data.Price && o.IsActive()); if (ords.NotIsNull()) { foreach (var ord in ords) { Trader.CancelOrder(ord.Sec, ord.OrderNumber); } } }); } } } } }
/// <summary> /// /// </summary> public void AutoSLLoopControl() { if (TimeControl.AddSeconds(PERIOD_CONTROL_SEC) > DateTime.Now) { return; } TimeControl = DateTime.Now; MThread.InitThread(() => { foreach (var objControl in ASLObject.ToArray) { var sec = GetSecCodeAndClass(objControl.SecAndCode); if (sec.NotIsNull()) { var pos = Trader.Objects.tPositions.SearchFirst(p => p.Sec == sec); if (pos.NotIsNull()) { var stopLoss = Trader.Objects.tStopOrders.SearchAll(o => o.Sec == sec && o.IsActive() && o.Comment.Contains(Define.STOP_LOSS) ); var volume = pos.CurrentVolume; //Проверяем, не появились ли лишние стоп ордера if (stopLoss.Count() > 1) { Trader.CancelAllStopOrder(sec); continue; } //Проверяем не изменилась ли позиция else if (stopLoss.Count() == 1) { var activeStop = stopLoss.ElementAt(0); //Снимаем стоп если разные обьемы if (activeStop.Volume != volume) { Trader.CancelAllStopOrder(sec); continue; } //Снимаем стоп если он в другую сторону if (activeStop.IsBuy() && pos.IsBuy()) { Trader.CancelAllStopOrder(sec); continue; } } else if (stopLoss.Count() == 0 && pos.CurrentVolume > 0) { var allTrades = Trader.Objects.tMyTrades.SearchAll(t => t.Trade.Sec == sec) .OrderByDescending(o => o.Trade.Number); if (allTrades.NotIsNull()) { decimal Price = 0; if (allTrades.Count() > 0) { var lastTrade = allTrades.FirstOrDefault(o => o.Trade.Direction == pos.CurrentDirection); if (lastTrade.NotIsNull()) { Price = lastTrade.Trade.Price; } } if (Price == 0) { Price = sec.LastPrice; } var tiks = objControl.Tiks; var stopOrder = new StopOrder() { Sec = sec, Price = Price, ClientCode = objControl.Comment, Comment = Define.STOP_LOSS, Volume = volume, DateExpiry = DateMarket.ExtractDateTime(DateTime.Now.AddDays(10)) }; if (pos.IsBuy()) { stopOrder.Direction = OrderDirection.Sell; stopOrder.ConditionPrice = Price - sec.MinPriceStep * tiks; stopOrder.Price = stopOrder.ConditionPrice - sec.MinPriceStep * 10; } else if (pos.IsSell()) { stopOrder.Direction = OrderDirection.Buy; stopOrder.ConditionPrice = Price + sec.MinPriceStep * tiks; stopOrder.Price = stopOrder.ConditionPrice + sec.MinPriceStep * 10; } Trader.CreateStopOrder(stopOrder, StopOrderType.StopLimit); AutoSLLog("Create order: " + sec.ToString() + " " + (stopOrder.IsBuy() ? "B" : "S") + " " + stopOrder.ConditionPrice); } } } } } }); }
/// <summary> /// Подготовка данных иструмента для форм /// </summary> private void prepareInfoForForm() { if (ThreadInfo.NotIsNull()) { ThreadInfo.Abort(); ThreadInfo = null; return; } if (comboBoxCodeClient.SelectedItem.NotIsNull()) { var listPortf = Trader.Objects.tPortfolios .SearchAll(p => p.Account.AccClasses.FirstOrDefault(c => c == Securities.Class).NotIsNull() && p.Client.Code == comboBoxCodeClient.SelectedItem.ToString()); if (TypeClientLimit.Value >= 0) { listPortf = listPortf.Where(p => p.LimitKind == TypeClientLimit.Value).ToArray(); } if (listPortf.Count() > 0) { Portfolio = listPortf.First(); } } if (ClientCode.Value.Empty()) { Position = Trader.Objects.tPositions.SearchFirst(s => s.Sec == Securities); } else { Position = Trader.Objects.tPositions.SearchFirst(s => s.Sec == Securities && s.Client.Code == ClientCode.Value); } ThreadInfo = MThread.InitThread(() => { if (this.Position.NotIsNull()) { Info.CountCurrentPosition = this.Position.Data.CurrentNet; } if (Securities.LastPrice != 0) { Info.CurrentPrice = Securities.LastPrice; } //orders var orders = this.Trader.Objects.tOrders.SearchAll(so => so.Sec.Code == Securities.Code && so.IsActive()).ToArray(); var ordB = orders.Where(o => o.IsBuy()).ToArray(); var ordS = orders.Where(o => o.IsSell()).ToArray(); Info.CountOrderBuy = ordB.Count(); Info.CountOrderSell = ordS.Count(); Info.CountVolumeBuy = ordB.Sum(o => o.Balance); Info.CountVolumeSell = ordS.Sum(o => o.Balance); var stopOrdersActive = this.Trader.Objects.tStopOrders.SearchAll(so => so.Sec.Code == Securities.Code && so.IsActive()); if (stopOrdersActive.NotIsNull()) { var soBuy = stopOrdersActive.Where(so => so.IsBuy()).ToArray(); var soSell = stopOrdersActive.Where(so => so.IsSell()).ToArray(); var soOrderBuy = soBuy.Where(so => so.Comment.Contains(Define.STOP_LIMIT)).ToArray(); var soOrderSell = soSell.Where(so => so.Comment.Contains(Define.STOP_LIMIT)).ToArray(); var soLimitBuy = soBuy.Where(so => so.Comment.Contains(Define.STOP_LOSS)).ToArray(); var soLimitSell = soSell.Where(so => so.Comment.Contains(Define.STOP_LOSS)).ToArray(); //sLimit Info.CountStopLimitOrderBuy = soLimitBuy.Count(); Info.CountStopLimitOrderSell = soLimitSell.Count(); if (Info.CountStopLimitOrderBuy > 0 || Info.CountStopLimitOrderSell > 0) { Info.CountStopLimitVolumeBuy = soLimitBuy.Sum(so => so.Volume); Info.CountStopLimitVolumeSell = soLimitSell.Sum(so => so.Volume); } //sOrder Info.CountStopOrderBuy = soOrderBuy.Count(); Info.CountStopOrderSell = soOrderSell.Count(); if (Info.CountStopOrderBuy > 0 || Info.CountStopOrderSell > 0) { Info.CountStopVolumeBuy = soOrderBuy.Sum(so => so.Volume); Info.CountStopVolumeSell = soOrderSell.Sum(so => so.Volume); } if (Info.CountCurrentPosition != 0) { var stopOrder = stopOrdersActive.FirstOrDefault(so => so.IsActive()); if (stopOrder.NotIsNull() && Securities.LastTrade.NotIsNull() && Securities.Params.MinPriceStep > 0 && Position.NotIsNull()) { var priceStop = stopOrder.ConditionPrice; decimal gapPrice = priceStop > Info.CurrentPrice ? priceStop - Info.CurrentPrice : Info.CurrentPrice - priceStop; decimal result = (gapPrice / Securities.Params.MinPriceStep) * Securities.Params.StepPrice; decimal countLots = Position.CurrentVolume; Info.ForecastSum = result * countLots; } else { Info.ForecastSum = 0; } } } if (Portfolio.NotIsNull()) { Info.Balanse = this.Portfolio.Balance; Info.FreeBalanse = this.Portfolio.CurrentBalance; Info.VarMargin = this.Portfolio.VarMargin; } ThreadInfo = null; }); }