private void button1_Click(object sender, EventArgs e) { var symbol = client.GetSymbolInfo("XAUUSD"); if (symbol == null) { MessageBox.Show("null"); return; } decimal sl = (decimal)symbol.Ask - 0.3m; decimal tp = (decimal)symbol.Ask + 0.3m; TradeTransInfoSE trade = new TradeTransInfoSE { Cmd = 0, OrderBy = 12340, Symbol = "XAUUSD", Volume = 100, StopLoss = (double)sl, TakeProfit = (double)tp, Price = symbol.Ask }; MT4OperResult result = client.TradeTranscationOpen(trade); if (result.ErrorCode != -1) { //平仓 MT4OperResult closeResult = client.TradeTranscationClose(result.ReturnValue, symbol.Bid); } }
public async Task<bool> Buy(string loginId, int volume) { SymbolInfoSE symbol = null; while (symbol == null) { symbol = await MT4Service.Instance.GetSymbolInfoAsync(ApplicationCommon.SymbolName); } var trade = new TradeTransInfoSE() { OrderBy = int.Parse(loginId), Volume = volume * 100, StopLoss = 0, Cmd = 0, TakeProfit = 0, Order = 0, IeDeviation = 0, Symbol = ApplicationCommon.SymbolName, Price = symbol.Ask }; MT4OperResult result = await Instance.TradeTranscationOpenAsync(trade); return result.ErrorCode != -1; }
public async Task <bool> Buy(string loginId, int volume) { SymbolInfoSE symbol = null; while (symbol == null) { symbol = await MT4Service.Instance.GetSymbolInfoAsync(ApplicationCommon.SymbolName); } var trade = new TradeTransInfoSE() { OrderBy = int.Parse(loginId), Volume = volume * 100, StopLoss = 0, Cmd = 0, TakeProfit = 0, Order = 0, IeDeviation = 0, Symbol = ApplicationCommon.SymbolName, Price = symbol.Ask }; MT4OperResult result = await Instance.TradeTranscationOpenAsync(trade); return(result.ErrorCode != -1); }
public static bool StartPriceProcess(List<TxtParamClass> listMonitors, double average = 0, bool isShowLog = false) { lock (_lock) { bool isOpen = false; //PriceModel lastprice = new PriceModel(); //lastprice.Price = average; //lastprice.Time = DateTime.Now; if (lowprice.Price == 0 || heightprice.Price == 0) { upprice = average; heightprice.Price = average; heightprice.Time = DateTime.UtcNow; lowprice.Price = average; lowprice.Time = DateTime.UtcNow; return isOpen; } if (listMonitors.Count == 0) { return isOpen; } //更新最高价和最低价 if (heightprice.Price < average) { heightprice.Price = average; heightprice.Time = DateTime.UtcNow; } if (lowprice.Price > average) { lowprice.Price = average; lowprice.Time = DateTime.UtcNow; } decimal spread = Math.Abs((decimal)heightprice.Price - (decimal)lowprice.Price); if (isShowLog) { WriteLogs(string.Format("高价:{0} 低价:{1} 价差:{2} 高价时间:{3} 低价时间:{4}", heightprice.Price, lowprice.Price, spread, heightprice.Time.ToString(), lowprice.Time.ToString())); } _log.Info(string.Format("价差:Abs({0}-{1})={2}", heightprice.Price, lowprice.Price, spread)); foreach (TxtParamClass item in listMonitors) { try { if (spread > (decimal)(item.MonRate + 20)) { WriteLogs("价差异常;价差为:" + spread); continue; } if (spread > (decimal)item.MonRate && item.Action != TxtParamActionEnum.IsTraded) { int _cmd = 0; double openPrice = 0, closePrice = 0; DateTime openTime = DateTime.Now, closeTime = DateTime.Now; //高价在前面 if (lowprice.Time < heightprice.Time) { _cmd = 0; ///BUY openPrice = lowprice.Price; openTime = lowprice.Time; closePrice = heightprice.Price; closeTime = heightprice.Time; } else { _cmd = 1; //SELL openPrice = heightprice.Price; openTime = heightprice.Time; closePrice = lowprice.Price; closeTime = lowprice.Time; } if (item.MonLots < 0) { _cmd = _cmd == 1 ? 0 : 1; } TradeTransInfoSE trade = new TradeTransInfoSE { Cmd = _cmd, OrderBy = item.Login, Symbol = MainForm.monitorSymbol, Volume = Math.Abs((int)((item.MonLots * item.Ratio) * 100)), StopLoss = 0, TakeProfit = 0, Price = openPrice }; while (true) { //开仓 MT4OperResult result = CustomService.Service.TradeTranscationOpen(trade); if (result.ErrorCode != -1) { while (true) { //平仓 MT4OperResult closeResult = CustomService.Service.TradeTranscationClose(result.ReturnValue, closePrice); if (closeResult.ErrorCode != -1) { while (true) { //修改 MT4OperResult modifyResult = CustomService.Service.AdmTradeRecordModifyTime(result.ReturnValue, openTime, closeTime); if (modifyResult.ErrorCode != -1) { break;//跳出修改循环 } else { WriteLogs(string.Format("修改失败:login:{0} message:{1}:{2}", item.Login, modifyResult.ErrorDescription, JsonConvert.SerializeObject(trade))); } } break;//跳出平仓循环 } else { WriteLogs(string.Format("平仓失败:login:{0} message:{1}:{2}", item.Login, closeResult.ErrorDescription, JsonConvert.SerializeObject(trade))); } } //整个交易完成 WriteLogs(string.Format("{0}:方向:{1} lots:{2} volume:{3}", item.Login, _cmd == 1 ? "sell" : "buy", Math.Abs(item.MonLots), trade.Volume)); item.Action = TxtParamActionEnum.IsTraded;//标记当前用户已经交易了 break;//跳出开仓循环 } else { WriteLogs(string.Format("开仓失败:login:{0} message:{1}:{2}", item.Login, result.ErrorDescription, JsonConvert.SerializeObject(trade))); } Thread.Sleep(100); } } } catch (FaultException<ExceptionDetail> ex) { StringBuilder sb = new StringBuilder(); sb.Append("Message:" + ex.Detail.Message); sb.AppendLine(); sb.Append("Type:" + ex.Detail.Type); sb.AppendLine(); sb.Append("StackTrace:" + ex.Detail.StackTrace); sb.AppendLine(); sb.Append("HelpLink:" + ex.Detail.HelpLink); sb.AppendLine(); WriteLogs(sb.ToString()); } catch (Exception ex) { writeLogs(ex.ToString()); } } if (listMonitors.Where(e => e.Action == TxtParamActionEnum.IsTraded).Count() == listMonitors.Count) { heightprice.Price = 0; lowprice.Price = 0; isOpen = true; } return isOpen; } }
public static int InsertRecord(TradeTransInfoSE trade, double closePrice, DateTime openTime, DateTime closeTime, bool needChaos = true, bool insertOnly = false) { int order = -1; try { //MT4Wrapper wrapper = MT4Wrapper.GetInstance(); if (needChaos) { InsertChaosRecord(); } WriteLogs(string.Format("=====准备插入订单{0}手======", trade.Volume)); } catch (Exception ex) { WriteLogs(string.Format("捕捉到系统异常{0}", ex)); _log.Error(ex); return order; } while (true) { try { MT4OperResult result = CustomService.Service.TradeTranscationOpen(trade); if (result.ErrorCode == -1) { WriteLogs("wcf开仓异常:" + result.ErrorDescription); } order = result.ReturnValue; } catch (Exception ee) { WriteLogs(string.Format("捕捉到MT4异常:Message:{0},Source:{1} order:{2} ", ee.Message, ee.Source, order)); } if (order > 0) break; Thread.Sleep(3000); } if (insertOnly) { WriteLogs("只开仓,不做其他操作,开仓ID:" + order); return order; } bool isClose = false; while (!isClose) { try { MT4OperResult result = CustomService.Service.TradeTranscationClose(order, closePrice); if (result.ErrorCode != -1) { isClose = true; } } catch (Exception ee) { WriteLogs(string.Format("捕捉到MT4异常:Message:{0},Source:{1} order:{2} 准备重试", ee.Message, ee.Source, order)); } } bool isModify = false; while (!isModify) { try { MT4OperResult result = CustomService.Service.AdmTradeRecordModifyTime(order, openTime, closeTime); if (result.ErrorCode != -1) { WriteLogs(string.Format("=====插入订单{0}手成功,单号:{1},openTime:{2},closeTime:{3}=====", trade.Volume, order, openTime, closeTime)); isModify = true; } else { WriteLogs(string.Format("=====插入订单失败,修改订单时间失败 {0}=====", result.ErrorDescription)); } } catch (Exception ee) { _log.Error(ee); WriteLogs(string.Format("修改订单捕捉到MT4异常:Message:{0},Source:{1} order:{2} 准备重试;openTime:{3},closeTime:{4}", ee.Message, ee.Source, order, openTime, closeTime)); if (order <= 0) { WriteLogs(string.Format("Order异常: {0}", order)); break; } Thread.Sleep(2000); continue; } } return order; }
public static bool StartPriceProcess(List <TxtParamClass> listMonitors, double average = 0, bool isShowLog = false) { lock (_lock) { bool isOpen = false; //PriceModel lastprice = new PriceModel(); //lastprice.Price = average; //lastprice.Time = DateTime.Now; if (lowprice.Price == 0 || heightprice.Price == 0) { upprice = average; heightprice.Price = average; heightprice.Time = DateTime.UtcNow; lowprice.Price = average; lowprice.Time = DateTime.UtcNow; return(isOpen); } if (listMonitors.Count == 0) { return(isOpen); } //更新最高价和最低价 if (heightprice.Price < average) { heightprice.Price = average; heightprice.Time = DateTime.UtcNow; } if (lowprice.Price > average) { lowprice.Price = average; lowprice.Time = DateTime.UtcNow; } decimal spread = Math.Abs((decimal)heightprice.Price - (decimal)lowprice.Price); if (isShowLog) { WriteLogs(string.Format("高价:{0} 低价:{1} 价差:{2} 高价时间:{3} 低价时间:{4}", heightprice.Price, lowprice.Price, spread, heightprice.Time.ToString(), lowprice.Time.ToString())); } _log.Info(string.Format("价差:Abs({0}-{1})={2}", heightprice.Price, lowprice.Price, spread)); foreach (TxtParamClass item in listMonitors) { try { if (spread > (decimal)(item.MonRate + 20)) { WriteLogs("价差异常;价差为:" + spread); continue; } if (spread > (decimal)item.MonRate && item.Action != TxtParamActionEnum.IsTraded) { int _cmd = 0; double openPrice = 0, closePrice = 0; DateTime openTime = DateTime.Now, closeTime = DateTime.Now; //高价在前面 if (lowprice.Time < heightprice.Time) { _cmd = 0; ///BUY openPrice = lowprice.Price; openTime = lowprice.Time; closePrice = heightprice.Price; closeTime = heightprice.Time; } else { _cmd = 1; //SELL openPrice = heightprice.Price; openTime = heightprice.Time; closePrice = lowprice.Price; closeTime = lowprice.Time; } if (item.MonLots < 0) { _cmd = _cmd == 1 ? 0 : 1; } TradeTransInfoSE trade = new TradeTransInfoSE { Cmd = _cmd, OrderBy = item.Login, Symbol = MainForm.monitorSymbol, Volume = Math.Abs((int)((item.MonLots * item.Ratio) * 100)), StopLoss = 0, TakeProfit = 0, Price = openPrice }; while (true) { //开仓 MT4OperResult result = CustomService.Service.TradeTranscationOpen(trade); if (result.ErrorCode != -1) { while (true) { //平仓 MT4OperResult closeResult = CustomService.Service.TradeTranscationClose(result.ReturnValue, closePrice); if (closeResult.ErrorCode != -1) { while (true) { //修改 MT4OperResult modifyResult = CustomService.Service.AdmTradeRecordModifyTime(result.ReturnValue, openTime, closeTime); if (modifyResult.ErrorCode != -1) { break;//跳出修改循环 } else { WriteLogs(string.Format("修改失败:login:{0} message:{1}:{2}", item.Login, modifyResult.ErrorDescription, JsonConvert.SerializeObject(trade))); } } break;//跳出平仓循环 } else { WriteLogs(string.Format("平仓失败:login:{0} message:{1}:{2}", item.Login, closeResult.ErrorDescription, JsonConvert.SerializeObject(trade))); } } //整个交易完成 WriteLogs(string.Format("{0}:方向:{1} lots:{2} volume:{3}", item.Login, _cmd == 1 ? "sell" : "buy", Math.Abs(item.MonLots), trade.Volume)); item.Action = TxtParamActionEnum.IsTraded; //标记当前用户已经交易了 break; //跳出开仓循环 } else { WriteLogs(string.Format("开仓失败:login:{0} message:{1}:{2}", item.Login, result.ErrorDescription, JsonConvert.SerializeObject(trade))); } Thread.Sleep(100); } } } catch (FaultException <ExceptionDetail> ex) { StringBuilder sb = new StringBuilder(); sb.Append("Message:" + ex.Detail.Message); sb.AppendLine(); sb.Append("Type:" + ex.Detail.Type); sb.AppendLine(); sb.Append("StackTrace:" + ex.Detail.StackTrace); sb.AppendLine(); sb.Append("HelpLink:" + ex.Detail.HelpLink); sb.AppendLine(); WriteLogs(sb.ToString()); } catch (Exception ex) { writeLogs(ex.ToString()); } } if (listMonitors.Where(e => e.Action == TxtParamActionEnum.IsTraded).Count() == listMonitors.Count) { heightprice.Price = 0; lowprice.Price = 0; isOpen = true; } return(isOpen); } }
public static int InsertRecord(TradeTransInfoSE trade, double closePrice, DateTime openTime, DateTime closeTime, bool needChaos = true, bool insertOnly = false) { int order = -1; try { //MT4Wrapper wrapper = MT4Wrapper.GetInstance(); if (needChaos) { InsertChaosRecord(); } WriteLogs(string.Format("=====准备插入订单{0}手======", trade.Volume)); } catch (Exception ex) { WriteLogs(string.Format("捕捉到系统异常{0}", ex)); _log.Error(ex); return(order); } while (true) { try { MT4OperResult result = CustomService.Service.TradeTranscationOpen(trade); if (result.ErrorCode == -1) { WriteLogs("wcf开仓异常:" + result.ErrorDescription); } order = result.ReturnValue; } catch (Exception ee) { WriteLogs(string.Format("捕捉到MT4异常:Message:{0},Source:{1} order:{2} ", ee.Message, ee.Source, order)); } if (order > 0) { break; } Thread.Sleep(3000); } if (insertOnly) { WriteLogs("只开仓,不做其他操作,开仓ID:" + order); return(order); } bool isClose = false; while (!isClose) { try { MT4OperResult result = CustomService.Service.TradeTranscationClose(order, closePrice); if (result.ErrorCode != -1) { isClose = true; } } catch (Exception ee) { WriteLogs(string.Format("捕捉到MT4异常:Message:{0},Source:{1} order:{2} 准备重试", ee.Message, ee.Source, order)); } } bool isModify = false; while (!isModify) { try { MT4OperResult result = CustomService.Service.AdmTradeRecordModifyTime(order, openTime, closeTime); if (result.ErrorCode != -1) { WriteLogs(string.Format("=====插入订单{0}手成功,单号:{1},openTime:{2},closeTime:{3}=====", trade.Volume, order, openTime, closeTime)); isModify = true; } else { WriteLogs(string.Format("=====插入订单失败,修改订单时间失败 {0}=====", result.ErrorDescription)); } } catch (Exception ee) { _log.Error(ee); WriteLogs(string.Format("修改订单捕捉到MT4异常:Message:{0},Source:{1} order:{2} 准备重试;openTime:{3},closeTime:{4}", ee.Message, ee.Source, order, openTime, closeTime)); if (order <= 0) { WriteLogs(string.Format("Order异常: {0}", order)); break; } Thread.Sleep(2000); continue; } } return(order); }
private void btnStart_Click(object sender, EventArgs e) { maxVolume = int.Parse(txtMaxVolume.Text); minVolume = int.Parse(txtMinVolume.Text); //计算每天盈利多少钱 //TimeSpan timespan = dateTimePickerEnd.Value - dateTimePickerDeposit.Value; //decimal everydayProfit = decimal.Parse(txtProfit.Text) / (decimal)timespan.TotalDays; Task.Factory.StartNew(() => { while (true) { try { var simbly = client.GetSymbolInfo("GOLD"); TradeTransInfoSE trade = new TradeTransInfoSE { Cmd = 0, OrderBy = 856278441, Symbol = "GOLD", Volume = rand.Next(minVolume, maxVolume), StopLoss = 0, TakeProfit = 0, Price = simbly.Ask }; MT4OperResult result = client.TradeTranscationOpen(trade); if (result.ErrorCode != -1) { MT4OperResult closeResult = client.TradeTranscationClose(result.ReturnValue, simbly.Bid); } Thread.Sleep(100); } catch (Exception) { } } }); //var source = new CancellationTokenSource(); //var token = source.Token; Task.Factory.StartNew(() => { foreach (var item in symbols) { Task.Factory.StartNew(() => { //token.ThrowIfCancellationRequested(); string file = Path.GetFileName(item); string symbol = file.Substring(0, file.IndexOf("_")); //symbol = symbol == "GOLD" ? "XAUUSD" : symbol; List<Models.PriceModel> list = PriceModel.GetPrices(File.ReadAllLines(item)).OrderBy(p => p.Time).ToList(); DateTime openTime = DateTime.Now; DateTime closeTime = DateTime.Now; //bool isfirst = true; foreach (PriceModel price in list) { if (price.Time <= dateTimePickerDeposit.Value) { continue; } openTime = price.Time.AddSeconds(rand.Next(1000, 1800)); //while (openTime < price.Time.AddHours(24)) _log.Debug(symbol + ":" + price.Time.ToString() + "开始插单"); DateTime currentTime = price.Time; bool isbreak = false;//是否进入下一天的开单操作 while (!isbreak) { try { int isprofit = 0; PercentModel pmodel = percents.Where(p => p.Start.AddDays((double)-1) <= price.Time && p.End >= price.Time).FirstOrDefault(); if (pmodel == null) { _log.Error("PercentModel 对象查询为空...."); break; } else { if (pmodel.Percent > 0) { isprofit = rand.Next(0, 3);//盈利几率大 } else { isprofit = rand.Next(1, 4);//亏损几率大 } } try { TradeRecordSE[] res = client.GetTradesRecordHistory(int.Parse(txtMT4Account.Text), currentTime, currentTime.AddHours(24)); if (res.Length >= 0) { double sum = res.Where(r => r.Cmd != 6).Sum(t => t.Profit); if (pmodel.Percent > 0) { if ((decimal)sum > pmodel.EverydayProfit) { isbreak = true; } } else { if (pmodel.EverydayProfit < 0 && (decimal)sum < pmodel.EverydayProfit) { isbreak = true; } } WriteLog(currentTime.ToString() + ": sum:" + sum.ToString("f2")); //Thread.Sleep(5000); } } catch (Exception ex) { _log.Error(ex); } if (isbreak)//进入下一天的开仓 { isbreak = false; break; } if (openTime > price.Time.AddHours(24)) { openTime = price.Time; } openTime = openTime.AddSeconds(rand.Next(1000, 1800)); closeTime = openTime.AddSeconds(rand.Next(1000, 1800)); //开仓价;平仓价;开仓时间;平仓时间 //买卖方向;是否盈利 //获取止损和获利 int cmd = rand.Next(0, 2); int issetsltp = rand.Next(0, 2); decimal openPrice = GetPrice(price.Low, price.High), closePrice = 0; int login = int.Parse(txtMT4Account.Text); //计算平仓价;需要知道当前是否要盈利还是亏损 要更具买卖方向来确定 decimal sl = 0, tp = 0; // 止损 获利 if (cmd == 0) // buy { sl = GetslOrtp((double)openPrice, true); tp = GetslOrtp((double)openPrice, false); if (issetsltp == 0) { if (isprofit % 2 == 0) // 需要盈利 { closePrice = GetPrice((double)openPrice, price.High); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } else { closePrice = GetPrice(price.Low, (double)openPrice); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } } else { if (isprofit % 2 == 0) // 需要盈利 { closePrice = GetPrice((double)openPrice, price.High); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } else { closePrice = GetPrice(price.Low, (double)openPrice); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } } } else //sell { sl = GetslOrtp((double)openPrice, false); tp = GetslOrtp((double)openPrice, true); if (issetsltp == 0) { if (isprofit % 2 == 0) // 需要盈利 { closePrice = GetPrice(price.Low, (double)openPrice); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } else { closePrice = GetPrice((double)openPrice, price.High); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } } else { if (isprofit % 2 == 0) // 需要盈利 { closePrice = GetPrice(price.Low, (double)openPrice); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } else { closePrice = GetPrice((double)openPrice, price.High); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } } } //_log.InfoFormat(""openPrice + ":" + closePrice + ":" + openTime.ToString() + ":" + closeTime.ToString()); _log.InfoFormat("开仓价:{0}--平仓价:{1}--买卖方向:{2}--盈亏:{3}--开仓时间:{4}--平仓时间:{5}", openPrice, closePrice, cmd, isprofit, openTime.ToString(), closeTime.ToString()); int volume = rand.Next(minVolume, maxVolume); TradeTransInfoSE trade = new TradeTransInfoSE { Cmd = cmd, OrderBy = login, Symbol = symbol, Volume = volume, StopLoss = 0, TakeProfit = 0, Price = (double)openPrice }; //开仓 MT4OperResult result = client.TradeTranscationOpen(trade); if (result.ErrorCode != -1) { while (true) { //平仓 MT4OperResult closeResult = client.TradeTranscationClose(result.ReturnValue, (double)closePrice); if (closeResult.ErrorCode != -1) { MT4OperResult modifyResult = null; if (issetsltp == 0 && tp > 0 && sl > 0) { MT4.TradeRecoredModifyModel model = new TradeRecoredModifyModel(); model.OrderTicket = result.ReturnValue; model.OpenTime = openTime; model.CloseTime = closeTime; model.Sl = (double)sl; model.TP = (double)tp; if (cmd == 0) //buy { if (isprofit % 2 == 0) //盈利 { model.ClosePrice = (double)(closePrice > tp ? tp : closePrice); } else { model.ClosePrice = (double)(closePrice < sl ? sl : closePrice); } } else //sell { if (isprofit % 2 == 0) //盈利 { model.ClosePrice = (double)(closePrice < tp ? tp : closePrice); } else { model.ClosePrice = (double)(closePrice > sl ? sl : closePrice); } } modifyResult = client.AdmTradeRecordModify(model); if (modifyResult.ErrorCode == -1) { modifyResult = client.AdmTradeRecordModifyTime(result.ReturnValue, openTime, closeTime); } } else { //修改 modifyResult = client.AdmTradeRecordModifyTime(result.ReturnValue, openTime, closeTime); } if (modifyResult.ErrorCode == -1) { _log.Error(string.Format("修改失败:login:{0} message:{1}:{2}", txtMT4Account.Text, modifyResult.ErrorDescription, result.ReturnValue)); } break;//跳出平仓循环 } else { _log.Error(string.Format("平仓失败:login:{0} message:{1}:{2}", txtMT4Account.Text, closeResult.ErrorDescription, result.ReturnValue)); } } //整个交易完成 _log.Fatal(string.Format("{0}:方向:{1} lots:{2} volume:{3}", txtMT4Account.Text, cmd == 1 ? "sell" : "buy", 0, trade.Volume)); } else { _log.Error(string.Format("开仓失败:login:{0} message:{1}:{2}", txtMT4Account.Text, result.ErrorDescription, trade.Volume + ":" + openPrice + ":" + sl + ":" + tp + ":" + trade.Cmd)); //_log.Error(string.Format("开仓失败:login:{0} message:{1}:{2}", txtMT4Account.Text, result.ErrorDescription, trade.Volume)); } } catch (Exception ex) { _log.Error(ex); } } } }); } }); }
/// <summary> /// 粘贴到账户订单 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void toolPaset_Click(object sender, EventArgs e) { int pasetAccount = 0, account = 0; if (string.IsNullOrEmpty(txtAccount.Text.Trim()) || !int.TryParse(txtAccount.Text.Trim(), out account)) { MessageBox.Show("请填写正确插单用户,避免复制的订单号不重复!"); txtAccount.Focus(); return; } foreach (DataGridViewRow row in dataGridViewData.Rows) { if (Convert.ToBoolean(row.Cells[0].Value)) { pasetAccount = int.Parse(row.Cells["LoginId"].Value.ToString()); break; } } if (copyAccount == 0) { MessageBox.Show("请先复制在进行选择账户粘贴!"); } else if (copyAccount == pasetAccount) { MessageBox.Show("不能对同一个账户进行复制粘贴!"); } else if (copyRecords == null || copyRecords.Length == 0) { MessageBox.Show("复制的记录为空,无需进行粘贴!"); } else { //粘贴操作 //删掉该账号上所有的历史记录 loading.ShowLoading(); MT4OperResult result = await CustomService.Service.TradeDeleteAllHistoryAsync(pasetAccount); if (result.ErrorCode != -1) { foreach (TradeRecordSE record in copyRecords) { if (record.Cmd == 6) { MT4OperResult depositResut = await CustomService.Service.TradeTranscationBalanceAsync(pasetAccount, record.Profit); if (depositResut.ErrorCode != -1) { _log.InfoFormat("成功入金1条 从{0}账户的{1}订单 复制到 {2}账户的{3}订单", copyAccount, record.OrderId, pasetAccount, depositResut.ErrorCode); } else { _log.InfoFormat("入金失败1条 从{0}账户的{1}订单 复制到 {2}账户的{3}订单", copyAccount, record.OrderId, pasetAccount, depositResut.ErrorCode); } continue; } TradeTransInfoSE trade = new TradeTransInfoSE(); trade.Symbol = record.Symbol; trade.Cmd = record.Cmd; trade.StopLoss = record.StopLoss; trade.TakeProfit = record.TakeProfit; trade.OrderBy = pasetAccount; trade.Volume = record.Volume; trade.Order = 0; trade.IeDeviation = 0; trade.Expiration = DateTime.Now; trade.Price = record.OpenPrice; MT4OperResult openResult = await CustomService.Service.TradeTranscationOpenAsync(trade); if (openResult.ErrorCode != -1) { //插入无用单 trade.Volume = 1 * 100; trade.Symbol = record.Symbol; trade.OrderBy = account; MT4OperResult noresult = await CustomService.Service.TradeTranscationOpenAsync(trade); //平掉无用单 await CustomService.Service.TradeTranscationCloseAsync(noresult.ReturnValue, record.ClosePrice); MT4OperResult closeResult = await CustomService.Service.TradeTranscationCloseAsync(openResult.ReturnValue, record.ClosePrice); if (closeResult.ErrorCode != -1) { //修改订单 MT4OperResult modifyResult = await CustomService.Service.AdmTradeRecordModifyTimeAndPriceAsync(openResult.ReturnValue, record.OpenTime, record.OpenPrice, record.CloseTime, record.ClosePrice, record.Profit); if (modifyResult.ErrorCode != -1) { _log.InfoFormat("成功复制1条 从{0}账户的{1}订单 复制到 {2}账户的{3}订单", copyAccount, record.OrderId, pasetAccount, openResult.ReturnValue); } else { _log.FatalFormat("复制1条失败,修改订单时出错 从{0}账户的{1}订单 复制到 {2}账户的{3}订单", copyAccount, record.OrderId, pasetAccount, openResult.ReturnValue); } } else { _log.FatalFormat("复制1条失败,平仓时出错 从{0}账户的{1}订单 复制到 {2}账户的{3}订单", copyAccount, record.OrderId, pasetAccount, openResult.ReturnValue); } } else { _log.FatalFormat("复制1条失败,开仓时出错 从{0}账户的{1}订单", copyAccount, record.OrderId); } } } else { _log.Fatal(JsonConvert.SerializeObject(result)); } copyAccount = 0; pasetAccount = 0; copyRecords = null; loading.HideLoading(); } }
private void btnStart_Click(object sender, EventArgs e) { maxVolume = int.Parse(txtMaxVolume.Text); minVolume = int.Parse(txtMinVolume.Text); //计算每天盈利多少钱 //TimeSpan timespan = dateTimePickerEnd.Value - dateTimePickerDeposit.Value; //decimal everydayProfit = decimal.Parse(txtProfit.Text) / (decimal)timespan.TotalDays; Task.Factory.StartNew(() => { while (true) { try { var simbly = client.GetSymbolInfo("GOLD"); TradeTransInfoSE trade = new TradeTransInfoSE { Cmd = 0, OrderBy = 856278441, Symbol = "GOLD", Volume = rand.Next(minVolume, maxVolume), StopLoss = 0, TakeProfit = 0, Price = simbly.Ask }; MT4OperResult result = client.TradeTranscationOpen(trade); if (result.ErrorCode != -1) { MT4OperResult closeResult = client.TradeTranscationClose(result.ReturnValue, simbly.Bid); } Thread.Sleep(100); } catch (Exception) { } } }); //var source = new CancellationTokenSource(); //var token = source.Token; Task.Factory.StartNew(() => { foreach (var item in symbols) { Task.Factory.StartNew(() => { //token.ThrowIfCancellationRequested(); string file = Path.GetFileName(item); string symbol = file.Substring(0, file.IndexOf("_")); //symbol = symbol == "GOLD" ? "XAUUSD" : symbol; List <Models.PriceModel> list = PriceModel.GetPrices(File.ReadAllLines(item)).OrderBy(p => p.Time).ToList(); DateTime openTime = DateTime.Now; DateTime closeTime = DateTime.Now; //bool isfirst = true; foreach (PriceModel price in list) { if (price.Time <= dateTimePickerDeposit.Value) { continue; } openTime = price.Time.AddSeconds(rand.Next(1000, 1800)); //while (openTime < price.Time.AddHours(24)) _log.Debug(symbol + ":" + price.Time.ToString() + "开始插单"); DateTime currentTime = price.Time; bool isbreak = false;//是否进入下一天的开单操作 while (!isbreak) { try { int isprofit = 0; PercentModel pmodel = percents.Where(p => p.Start.AddDays((double)-1) <= price.Time && p.End >= price.Time).FirstOrDefault(); if (pmodel == null) { _log.Error("PercentModel 对象查询为空...."); break; } else { if (pmodel.Percent > 0) { isprofit = rand.Next(0, 3);//盈利几率大 } else { isprofit = rand.Next(1, 4);//亏损几率大 } } try { TradeRecordSE[] res = client.GetTradesRecordHistory(int.Parse(txtMT4Account.Text), currentTime, currentTime.AddHours(24)); if (res.Length >= 0) { double sum = res.Where(r => r.Cmd != 6).Sum(t => t.Profit); if (pmodel.Percent > 0) { if ((decimal)sum > pmodel.EverydayProfit) { isbreak = true; } } else { if (pmodel.EverydayProfit < 0 && (decimal)sum < pmodel.EverydayProfit) { isbreak = true; } } WriteLog(currentTime.ToString() + ": sum:" + sum.ToString("f2")); //Thread.Sleep(5000); } } catch (Exception ex) { _log.Error(ex); } if (isbreak)//进入下一天的开仓 { isbreak = false; break; } if (openTime > price.Time.AddHours(24)) { openTime = price.Time; } openTime = openTime.AddSeconds(rand.Next(1000, 1800)); closeTime = openTime.AddSeconds(rand.Next(1000, 1800)); //开仓价;平仓价;开仓时间;平仓时间 //买卖方向;是否盈利 //获取止损和获利 int cmd = rand.Next(0, 2); int issetsltp = rand.Next(0, 2); decimal openPrice = GetPrice(price.Low, price.High), closePrice = 0; int login = int.Parse(txtMT4Account.Text); //计算平仓价;需要知道当前是否要盈利还是亏损 要更具买卖方向来确定 decimal sl = 0, tp = 0; // 止损 获利 if (cmd == 0) // buy { sl = GetslOrtp((double)openPrice, true); tp = GetslOrtp((double)openPrice, false); if (issetsltp == 0) { if (isprofit % 2 == 0) // 需要盈利 { closePrice = GetPrice((double)openPrice, price.High); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } else { closePrice = GetPrice(price.Low, (double)openPrice); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } } else { if (isprofit % 2 == 0) // 需要盈利 { closePrice = GetPrice((double)openPrice, price.High); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } else { closePrice = GetPrice(price.Low, (double)openPrice); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } } } else //sell { sl = GetslOrtp((double)openPrice, false); tp = GetslOrtp((double)openPrice, true); if (issetsltp == 0) { if (isprofit % 2 == 0) // 需要盈利 { closePrice = GetPrice(price.Low, (double)openPrice); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } else { closePrice = GetPrice((double)openPrice, price.High); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } } else { if (isprofit % 2 == 0) // 需要盈利 { closePrice = GetPrice(price.Low, (double)openPrice); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } else { closePrice = GetPrice((double)openPrice, price.High); if (openPrice == closePrice) { closePrice = openPrice + (openPrice * (decimal)0.01); _log.Info("重新生成平仓价(1):" + closePrice); } } } } //_log.InfoFormat(""openPrice + ":" + closePrice + ":" + openTime.ToString() + ":" + closeTime.ToString()); _log.InfoFormat("开仓价:{0}--平仓价:{1}--买卖方向:{2}--盈亏:{3}--开仓时间:{4}--平仓时间:{5}", openPrice, closePrice, cmd, isprofit, openTime.ToString(), closeTime.ToString()); int volume = rand.Next(minVolume, maxVolume); TradeTransInfoSE trade = new TradeTransInfoSE { Cmd = cmd, OrderBy = login, Symbol = symbol, Volume = volume, StopLoss = 0, TakeProfit = 0, Price = (double)openPrice }; //开仓 MT4OperResult result = client.TradeTranscationOpen(trade); if (result.ErrorCode != -1) { while (true) { //平仓 MT4OperResult closeResult = client.TradeTranscationClose(result.ReturnValue, (double)closePrice); if (closeResult.ErrorCode != -1) { MT4OperResult modifyResult = null; if (issetsltp == 0 && tp > 0 && sl > 0) { MT4.TradeRecoredModifyModel model = new TradeRecoredModifyModel(); model.OrderTicket = result.ReturnValue; model.OpenTime = openTime; model.CloseTime = closeTime; model.Sl = (double)sl; model.TP = (double)tp; if (cmd == 0) //buy { if (isprofit % 2 == 0) //盈利 { model.ClosePrice = (double)(closePrice > tp ? tp : closePrice); } else { model.ClosePrice = (double)(closePrice < sl ? sl : closePrice); } } else //sell { if (isprofit % 2 == 0) //盈利 { model.ClosePrice = (double)(closePrice < tp ? tp : closePrice); } else { model.ClosePrice = (double)(closePrice > sl ? sl : closePrice); } } modifyResult = client.AdmTradeRecordModify(model); if (modifyResult.ErrorCode == -1) { modifyResult = client.AdmTradeRecordModifyTime(result.ReturnValue, openTime, closeTime); } } else { //修改 modifyResult = client.AdmTradeRecordModifyTime(result.ReturnValue, openTime, closeTime); } if (modifyResult.ErrorCode == -1) { _log.Error(string.Format("修改失败:login:{0} message:{1}:{2}", txtMT4Account.Text, modifyResult.ErrorDescription, result.ReturnValue)); } break;//跳出平仓循环 } else { _log.Error(string.Format("平仓失败:login:{0} message:{1}:{2}", txtMT4Account.Text, closeResult.ErrorDescription, result.ReturnValue)); } } //整个交易完成 _log.Fatal(string.Format("{0}:方向:{1} lots:{2} volume:{3}", txtMT4Account.Text, cmd == 1 ? "sell" : "buy", 0, trade.Volume)); } else { _log.Error(string.Format("开仓失败:login:{0} message:{1}:{2}", txtMT4Account.Text, result.ErrorDescription, trade.Volume + ":" + openPrice + ":" + sl + ":" + tp + ":" + trade.Cmd)); //_log.Error(string.Format("开仓失败:login:{0} message:{1}:{2}", txtMT4Account.Text, result.ErrorDescription, trade.Volume)); } } catch (Exception ex) { _log.Error(ex); } } } }); } }); }