예제 #1
0
        /// <summary>
        /// 发送订单支付记录
        /// </summary>
        /// <param name="tradeRecord"></param>
        /// <returns></returns>
        public static string SendOrderPayRecord(TradeRecord tradeRecord)
        {
            try
            {
                Dictionary <string, string> parameters = new Dictionary <string, string>();

                parameters.Add("paySerial.id", tradeRecord.id);
                parameters.Add("data", tradeRecord.data_id);
                parameters.Add("paySerial.lkl_wt_state", tradeRecord.lkl_wt_state.ToString());
                parameters.Add("paySerial.termail_no", tradeRecord.termail_no);
                parameters.Add("paySerial.order_no", tradeRecord.order_no);
                parameters.Add("paySerial.batch_no", tradeRecord.batch_no);
                parameters.Add("paySerial.relation_order", tradeRecord.relation_order);
                parameters.Add("paySerial.order_type", tradeRecord.order_type.ToString());
                parameters.Add("paySerial.shop_type", tradeRecord.shop_type.ToString());
                parameters.Add("paySerial.reconc_str", tradeRecord.reconc_str);
                parameters.Add("paySerial.amount", tradeRecord.amount);
                string  url        = SysConfigHelper.readerNode("savePaymentLog");
                string  jsonResult = HttpHelper.getHttp(url, parameters, null);
                JObject jobject    = JObject.Parse(jsonResult);
                return(jobject["data"].ToString());
            }
            catch (Exception e)
            {
                log.Write("向后台发送订单支付记录时出错,订单号:" + tradeRecord.cloud_no + ",错误详情:" + e.Message);
                return(null);
            }
        }
예제 #2
0
        public void DeleteWithdrawal(InvestInfo investInfo, TradeRecord record)
        {
            var    capital        = investInfo.HoldingAssets.Where(x => x.AssetName.Equals("WON"));
            double withdrawalCost = record.Amount * (1 + record.RelativeFee * 0.01) + record.AbsoluteFee;

            capital.First().Amount += withdrawalCost;
        }
예제 #3
0
        private static void Generate(string file)
        {
            var header = new Header
            {
                version = 1,
                type    = "type1"
            };
            var records = new TradeRecord[64];

            for (var i = 0; i < records.Length; i++)
            {
                records[i] = new TradeRecord
                {
                    account = i + 1,
                    id      = i,
                    volume  = i * 10d,
                    comment = "comment" + i
                };
            }

            var bytes = StructureParser.Serialize(header, records);

            File.WriteAllBytes(file, bytes);

            Console.WriteLine("Test binary file is generated!");
            Console.WriteLine("Please copy to server in temparery folder and put file name with '-u' command");
        }
예제 #4
0
        /// <summary>
        /// 发送订单记录
        /// </summary>
        /// <param name="tradeRecord"></param>
        /// <returns></returns>
        public static string SendOrderRecord(TradeRecord tradeRecord)
        {
            try
            {
                Dictionary <string, string> parameters = new Dictionary <string, string>();

                parameters.Add("paySerial.cloud_no", tradeRecord.cloud_no);
                parameters.Add("paySerial.write_card_state", tradeRecord.write_card_stat);
                parameters.Add("paySerial.termail_no", tradeRecord.termail_no);
                parameters.Add("paySerial.order_no", tradeRecord.order_no);
                parameters.Add("paySerial.branch_shop_no", tradeRecord.branch_shop_no);
                parameters.Add("paySerial.branch_termail_no", tradeRecord.branch_termail_no);
                string  url        = SysConfigHelper.readerNode("savePaymentLog");
                string  jsonResult = HttpHelper.getHttp(url, parameters, null);
                JObject jobject    = JObject.Parse(jsonResult);

                tradeRecord.id = jobject["data"].ToString();

                return(tradeRecord.id);
            }
            catch (Exception e)
            {
                log.Write("向后台发送订单记录时出错,订单号:" + tradeRecord.cloud_no + ",错误详情:" + e.Message);
                return(null);
            }
        }
예제 #5
0
        /// <summary>
        /// 向退款文件添加一条万通卡退款记录
        /// </summary>
        /// <param name="_2"></param>
        /// <param name="_4"></param>
        /// <param name="_59"></param>
        /// <param name="state"></param>
        /// <param name="id"></param>
        /// <param name="orderNo"></param>
        /// <param name="transType"></param>
        /// <param name="conName"></param>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool AddTradeRecord(TradeRecord tradeRecord)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);
                XmlNode    root   = xmlDoc.SelectSingleNode("records");
                XmlElement record = xmlDoc.CreateElement("record");

                createXmlNode(record, "data_id", tradeRecord.data_id, xmlDoc);
                createXmlNode(record, "lkl_wt_state", tradeRecord.lkl_wt_state.ToString(), xmlDoc);//金额
                createXmlNode(record, "write_card_state", tradeRecord.write_card_stat.ToString(), xmlDoc);
                createXmlNode(record, "cloud_state", tradeRecord.cloud_state.ToString(), xmlDoc);
                createXmlNode(record, "termail_no", tradeRecord.termail_no, xmlDoc);
                createXmlNode(record, "order_no", tradeRecord.order_no, xmlDoc);
                createXmlNode(record, "batch_no", tradeRecord.batch_no, xmlDoc);
                createXmlNode(record, "relation_order", tradeRecord.relation_order, xmlDoc);
                createXmlNode(record, "order_type", tradeRecord.order_type, xmlDoc);
                createXmlNode(record, "shop_type", tradeRecord.shop_type, xmlDoc);
                createXmlNode(record, "reconc_str", tradeRecord.reconc_str, xmlDoc);
                createXmlNode(record, "amount", tradeRecord.amount, xmlDoc);
                createXmlNode(record, "cloud_no", tradeRecord.cloud_no, xmlDoc);

                root.AppendChild(record);
                xmlDoc.Save(filePath);
                log.Write("添加待发送交易纪录成功");
                return(true);
            }
            catch (Exception e)
            {
                log.Write("添加待发送交易纪录异常:" + e.Message);
            }

            return(false);
        }
예제 #6
0
        public ActionResult Submit(int id)
        {
            //1. 登录判断
            if (!IsLogined())
            {
                return(Content("<script>alert('请登录');window.location.href='/Users/Login'</script>"));
            }

            //往数据库的表中修改内容
            using (ShoppingEntities se = new ShoppingEntities())
            {
                string      text  = Request.Form["text"];
                TradeRecord order = se.TradeRecord.FirstOrDefault(u => u.TraPID == id);
                //判断是否提交过评论
                if (order.TraComment == null)
                {
                    var entry = se.Entry(order);
                    entry.State = System.Data.EntityState.Unchanged;
                    entry.Property("TraComment").IsModified = true;
                    order.TraComment = text;
                    if (se.SaveChanges() > 0)
                    {
                        return(Content("<script>alert('提价评价成功!');window.location.href='/Order/Index';</script>"));
                    }
                    else
                    {
                        return(Content("<script>alert('提价评价失败!');window.location.href='/Order/Index';</script>"));
                    }
                }
                else
                {
                    return(Content("<script>alert('已经提交过评论了,请勿重复提交!');window.location.href='/Order/Index';</script>"));
                }
            }
        }
예제 #7
0
        public void RecordTransfer(InvestInfo investInfo, TradeRecord record)
        {
            var targetItem = investInfo.HoldingAssets.Where(x => x.AssetName.Equals(record.ItemName));

            if (targetItem.Count() == 0)
            {
                Messenger.Instance.Send("보유 코인이 없습니다.", Context.WRITE_LOG);
                return;
            }

            if (targetItem.First().AssetName.Equals("WON"))
            {
                Messenger.Instance.Send("원화는 송금할 수 없습니다.", Context.WRITE_LOG);
                return;
            }

            if (targetItem.First().Amount < record.AbsoluteFee + (record.Amount * (record.RelativeFee * 0.01)))
            {
                Messenger.Instance.Send("코인이 부족합니다.", Context.WRITE_LOG);
                return;
            }

            targetItem.First().Amount -= record.AbsoluteFee + (record.Amount * (record.RelativeFee * 0.01));
            Messenger.Instance.Send("송금 완료", Context.WRITE_LOG);
        }
    public void ReadFromDB()
    {
        MongoClient   client   = new MongoClient("mongodb://localhost:27017");
        MongoServer   server   = client.GetServer();
        MongoDatabase database = server.GetDatabase("FinanceLast");

        MongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("TradeRecords");
        QueryDocument query = new QueryDocument();

        foreach (BsonDocument document in collection.Find(query))
        {
            int         a             = document["DailyLineShape"].ToInt32();
            int         b             = document["DailyLineSpeed"].ToInt32();
            int         c             = document["MinLineShape"].ToInt32();
            int         d             = document["MinLineSpeed"].ToInt32();
            TradeRecord currentRecord = this.tradeRecords[a, b, c, d];
            BsonArray   Symbols       = (BsonArray)document["Symbols"];
            foreach (BsonValue symbol in Symbols)
            {
                currentRecord.Symbols.Add(symbol.ToString());
            }
            currentRecord.TradeTimes = document["TradeTimes"].ToInt32();
            currentRecord.Reward     = (float)document["Reward"].ToDouble();
        }
    }
예제 #9
0
        public void TestMethod_01()
        {
            var header = new Header
            {
                version = 1,
                type    = "type1"
            };
            var records = new TradeRecord[64];

            for (var i = 0; i < records.Length; i++)
            {
                records[i] = new TradeRecord
                {
                    account = i + 1,
                    id      = i,
                    volume  = i * 10d,
                    comment = "comment" + i
                };
            }

            var bytes = StructureParser.Serialize(header, records);

            Assert.AreNotEqual(bytes.Length, 0, "Bad encoded");

            File.WriteAllBytes(BIN_FILE, bytes);
        }
        private void TransakcjaStop(TradeRecord tradeRecordStop)
        {
            try
            {
                SyncAPIConnector     connector     = new SyncAPIConnector(serverData);
                Credentials          credentials   = new Credentials(userId, password, "", "pixelNet");
                LoginResponse        loginResponse = APICommandFactory.ExecuteLoginCommand(connector, credentials, true);
                TRADE_OPERATION_CODE toc;
                if (tradeRecordStop.Cmd == 1)
                {
                    toc = TRADE_OPERATION_CODE.SELL;
                }
                else
                {
                    toc = TRADE_OPERATION_CODE.BUY;
                }

                double price      = tradeRecordStop.Close_price.GetValueOrDefault();
                double sl         = 0.0;
                double tp         = 0.0;
                string symbol     = tradeRecordStop.Symbol;
                double?volume     = tradeRecordStop.Volume;
                long   order      = tradeRecordStop.Order.GetValueOrDefault();
                long   expiration = 0;
                TradeTransInfoRecord ttCloseInfoRecord = new TradeTransInfoRecord(
                    toc,
                    TRADE_TRANSACTION_TYPE.ORDER_CLOSE,
                    price, sl, tp, symbol, volume, order, "", expiration);
                TradeTransactionResponse closeTradeTransactionResponse = APICommandFactory.ExecuteTradeTransactionCommand(connector, ttCloseInfoRecord, true);
                LogoutResponse           logoutResponse = APICommandFactory.ExecuteLogoutCommand(connector);
            }
            catch (Exception e) { MessageBox.Show(e.Message); }
        }
예제 #11
0
        void ModifyPosition(ConnectionStringBuilder builder)
        {
            var connectionString = builder.ToString();

            this.dataTrade = new DataTrade(connectionString);

            this.dataTrade.Logon       += OnLogon;
            this.dataTrade.AccountInfo += DataTrade_AccountInfo;
            this.dataTrade.Start();

            bool status = this.logonEvent.WaitOne(LogonWaitingTimeout);

            status &= this.accountInfoEvent.WaitOne(LogonWaitingTimeout);

            Assert.IsTrue(status, "Timeout of logon event");

            var         start    = DateTime.UtcNow;
            TradeRecord order    = this.dataTrade.Server.SendOrderEx("EURUSD", TradeCommand.Market, TradeRecordSide.Buy, 0, 10000, null, null, null, null, null, "comment", null, null, 1000000);
            DateTime    end      = DateTime.UtcNow;
            TimeSpan    interval = (end - start);

            Console.WriteLine("Interval = {0}", interval);

            var modified = order.Modify(null, null, null, 1.0, null, null, null, null);

            order.Close();

            this.dataTrade.Logon       -= this.OnLogon;
            this.dataTrade.AccountInfo -= DataTrade_AccountInfo;
            this.dataTrade.Stop();
            this.dataTrade.Dispose();
        }
예제 #12
0
        void CloseBy(ConnectionStringBuilder builder)
        {
            var connectionString = builder.ToString();

            using (this.dataTrade = new DataTrade(connectionString))
            {
                this.dataTrade.Logon       += OnLogon;
                this.dataTrade.AccountInfo += DataTrade_AccountInfo;
                this.dataTrade.Start();

                bool status = this.logonEvent.WaitOne(LogonWaitingTimeout);
                status &= this.accountInfoEvent.WaitOne(LogonWaitingTimeout);
                Assert.IsTrue(status, "Timeout of logon event");

                TradeRecord order1 = this.dataTrade.Server.SendOrderEx("EURUSD", TradeCommand.Market, TradeRecordSide.Buy, 0, 10000, null, null, null, null, null, "comment", null, null, 1000000);
                TradeRecord order2 = this.dataTrade.Server.SendOrderEx("EURUSD", TradeCommand.Market, TradeRecordSide.Sell, 0, 10000, null, null, null, null, null, "comment", null, null, 1000000);

                Assert.IsTrue(dataTrade.Server.CloseByPositions(order1.OrderId, order2.OrderId));
                var iter = this.dataTrade.Server.GetTradeTransactionReports(TimeDirection.Backward, false, DateTime.UtcNow.AddMinutes(-5), DateTime.UtcNow.AddMinutes(5), false);
                TradeTransactionReport tradeReport1 = iter.Item;
                iter.Next();
                TradeTransactionReport tradeReport2 = iter.Item;

                //Assert.IsTrue(tradeReport1.PositionById == order1.OrderId);
                Assert.IsTrue(tradeReport2.PositionById == order2.OrderId);


                this.dataTrade.Logon       -= this.OnLogon;
                this.dataTrade.AccountInfo -= DataTrade_AccountInfo;
                this.dataTrade.Stop();
            }
        }
        public void WriteToNotExistsCsvTest()
        {
            string          path   = "";
            CsvDocumentType dt     = new CsvDocumentType(path);
            TradeRecord     record = new TradeRecord();

            dt.WriteRecord(record);
        }
예제 #14
0
 public ActionResult <Exchange> GetOrderAction2([FromBody] TradeRecord rcd)
 {
     return(new Exchange()
     {
         ExchangeName = "香港恒生期货交易所",
         ExchangeNo = "HKEX"
     });
 }
        public TradeRecord GetSelectDataBDSQL(int id)
        {
            TradeRecord result = WorkingBD.SelectDataBDSQL(id);

            Console.WriteLine("Get [TradeRecord] from id: " + id);
            WorkingBD.SaveLog("Отправка одной записи по ID: " + id);
            return(result);
        }
예제 #16
0
        [TestMethod(), Timeout(40000)]//максимально возможное время работы теста (40 секунд)

        #region

        public void CreatedBinaryFile_and_UpLoad_to_CSV_File()
        {
            string path_dat  = @"D:\\Trade-test-3.dat"; //путь и имя бедующего бинарного файла содержащего  структуры
            string path_CSV  = @"D:\\Trade-test-3.csv"; //путь и имя бедующего  файла с разделителями содержащего те же структуры
            int    schetchik = 0;                       //счетчик
            int    result1__ = 0;                       //количество  строк записанных в тестовый бинарный файл
            int    result2__ = 0;                       //количество строк вычитанных из бинарного файла в коллекцию
            int    result3__ = 0;                       //количество строк выгруженных в файл ‘Trade-test-3.csv’
            int    lines     = 1000000;                 //на скольких строках протестировать?



            //создаем массив структур и присваиваем  значения полям каждой структуры
            #region

            TradeRecord[] trade = new TradeRecord[lines]; // создание экземпляра структуры "TradeRecord" на X строк

            for (int i = 0; i < lines; i++)
            {
                trade[i] = new TradeRecord(0 + i, 7777, 88888, "   comment Unit-test 3");
            }
            #endregion


            //создание экземпляра BinaryWriter (запись  в бинарный файл)
            #region BinaryWriter
            using (BinaryWriter writer = new BinaryWriter(File.Open(path_dat, FileMode.OpenOrCreate)))// открывает поток для записи структур в файл
            {
                #region
                foreach (TradeRecord t in trade)
                {
                    writer.Write(t.id);
                    writer.Write(t.account);
                    writer.Write(t.volume);
                    writer.Write(t.comment);

                    schetchik++;
                }
                Console.WriteLine("");
                Console.WriteLine("в бинарный файл 'D:\\Trade-test-3.dat' записано   {0}  строк(и) структуры 'trade'", schetchik);
                result1__ = schetchik;
                schetchik = 0;
                #endregion
            }
            #endregion

            #endregion


            //# 2.выполняем действие над тестируемым классом:'ConvertingBinaryToCSV'

            ConvertingBinaryToCSV convertingBinaryToCSV = new ConvertingBinaryToCSV(path_dat, path_CSV);

            List <TradeRecord> trade_ = convertingBinaryToCSV.fromBinaryFile(path_dat, out result2__); //метод 'fromBinaryFile'
            result3__ = convertingBinaryToCSV.toCSV(trade_, path_CSV);                                 //метод 'toCSV'

            Assert.AreEqual(result1__ + (result1__ - result2__), result3__);                           //сравнение ожидаемого и полученного, если равны то тест пройден
        }
예제 #17
0
        private bool ExeBankRefund(XmlNode xn, TradeRecord tradeRecord)
        {
            try
            {
                if (xn.ChildNodes[11] == null || xn.ChildNodes[12] == null || xn.ChildNodes[13] == null || xn.ChildNodes[14] == null || xn.ChildNodes[15] == null || xn.ChildNodes[16] == null || xn.ChildNodes[17] == null || xn.ChildNodes[18] == null || xn.ChildNodes[19] == null)
                {
                    return(false);
                }

                string _2      = xn.ChildNodes[13].InnerText;
                string _4      = xn.ChildNodes[14].InnerText;
                string _11     = xn.ChildNodes[15].InnerText;
                string _23     = xn.ChildNodes[16].InnerText;
                string _35     = xn.ChildNodes[17].InnerText;
                string _36     = xn.ChildNodes[18].InnerText;
                string _55     = xn.ChildNodes[19].InnerText;
                string pwd     = xn.ChildNodes[20].InnerText;
                string batchNo = xn.ChildNodes[21].InnerText;
                string cloudNo = xn.ChildNodes[22].InnerText;


                string connName       = xn.ChildNodes[2].InnerText;
                string secondShopNo   = "";
                string secondClientNo = "";


                tradeRecord.cloud_no = cloudNo;
                Dictionary <string, string> map = LKLProcedure.payRevoke(_2, _23, _35, _36, _55, pwd, _4, _11, batchNo, tradeRecord);

                if ("00".Equals(map["recode"]))
                {
                    log.Write("退款成功");
                    SendSanweiRefundSuccessNotice(xn, "0");



                    return(true);
                }
                else if ("".Equals(map["recode"].Trim()) || map["recode"] == null)
                {
                    return(false);
                }
                else
                {
                    SendSanweiRefundSuccessNotice(xn, "1");
                    return(false);
                }

                log.Write("退款失败");
                return(false);
            }
            catch (Exception e)
            {
                log.Write("退款异常" + e.Message);
            }
            return(false);
        }
        public void WriteToCsvTest()
        {
            string          path   = "someTest.csv";
            CsvDocumentType dt     = new CsvDocumentType(path);
            TradeRecord     record = new TradeRecord();

            dt.WriteRecord(record);

            //Не ожидается исключения
        }
예제 #19
0
        void SetTrade(TradeRecord t, Bar bar)
        {
            Chart.ClearGraphs();
            var g = Chart.AddGraph();

            g.Plots.Add(new Plot {
                DataSeries = new DataSeries <Bar>(t.Symbol, Lists.Create(bar)),
                Type       = PlotType.Candlestick
            });
        }
예제 #20
0
        public TradesResponse(string body) : base(body)
        {
            JSONArray arr = (JSONArray)this.ReturnData;

            foreach (JSONObject e in arr)
            {
                TradeRecord record = new TradeRecord();
                record.FieldsFromJSONObject(e);
                tradeRecords.AddLast(record);
            }
        }
예제 #21
0
        [TestMethod(), Timeout(20000)]//максимально возможное время работы теста (20 секунд)
        #region

        public void fromBinaryFile_Created_and_Read__Lines()
        {
            string path      = @"D:\\Trade-test-1.dat"; //путь и имя бедующего бинарного файла содержащего  структуры
            int    schetchik = 0;                       //счетчик
            int    result1   = 0;                       //счетчик
            int    lines     = 1000000;                 //на скольких строках протестировать?



            //создаем массив структур и присваиваем  значения полям каждой структуры
            #region

            TradeRecord[] trade = new TradeRecord[lines]; // создание экземпляра структуры "TradeRecord" на X строк

            for (int i = 0; i < lines; i++)
            {
                trade[i] = new TradeRecord(0 + i, lines, 640 + i, "   comment Unit-test 1");
            }
            #endregion


            //создание экземпляра BinaryWriter (запись  в бинарный файл)
            #region BinaryWriter
            using (BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.OpenOrCreate)))// открывает поток для записи структур в файл
            {
                #region
                foreach (TradeRecord t in trade)
                {
                    writer.Write(t.id);
                    writer.Write(t.account);
                    writer.Write(t.volume);
                    writer.Write(t.comment);

                    schetchik++;
                }
                Console.WriteLine("");
                Console.WriteLine("в бинарный файл 'D:\\Trade-test-1.dat' записано   {0}  строк(и) структуры 'trade'", schetchik);
                result1   = schetchik;
                schetchik = 0;
                #endregion
            }
            #endregion

            #endregion


            //# 2.выполняем действие над тестируемым классом:'ReaderFromBinaryFiles'

            ReaderFromBinaryFiles readerFromBinaryFiles = new ReaderFromBinaryFiles(path);
            int result2;//количество строк вычитанных из бинарного файла в коллекцию
            readerFromBinaryFiles.fromBinaryFile(path, out result2);

            Assert.AreEqual(result1, result2);//сравнение ожидаемого и полученного, если равны то тест пройден
        }
예제 #22
0
        public void DeleteDeposit(InvestInfo investInfo, TradeRecord record)
        {
            var targetItem = investInfo.HoldingAssets.Where(x => x.AssetName.Equals(record.ItemName));

            targetItem.First().Amount -= record.Amount;

            if (targetItem.First().Amount == 0)
            {
                investInfo.HoldingAssets.Remove(targetItem.First());
            }
        }
예제 #23
0
 public void PaintUpdate(TradeRecord r)
 {
     try
     {
         Trades.Add(r);
     }
     catch (Exception e)
     {
         Trace.WriteLine(e.ToString());
     }
 }
예제 #24
0
        public string RefundTrade(String orderRef)
        {
            if (orderRef == null || orderRef == string.Empty)
            {
                return("非法委托编号!");
            }

            int reference = int.Parse(orderRef.Trim());

            ERecord srecord = EntrustRecord.GetEntrustRecord(reference);

            if (srecord != null)
            {
                //找到股票委托交易信息
                RefundStruct refund = new RefundStruct()
                {
                    Direction    = srecord.Direction.Trim(),
                    ExchangeId   = srecord.ExchangeId.Trim(),
                    OffSetFlag   = "0",
                    SecurityCode = srecord.Code,
                    SecurityType = "S",
                    OrderRef     = srecord.OrderRef.ToString(),
                    OrderSysId   = srecord.SysOrderRef
                };

                queue_refund_thread.GetQueue().Enqueue(refund);

                return("success");
            }

            RecordItem frecord = TradeRecord.GetInstance().getOrderInfo(reference);

            if (frecord != null)
            {
                //找到期货委托交易信息

                RefundStruct refund = new RefundStruct()
                {
                    Direction    = frecord.Orientation,
                    ExchangeId   = String.Empty,
                    OffSetFlag   = frecord.CombOffsetFlag.ToString(),
                    SecurityCode = frecord.Code,
                    SecurityType = "F",
                    OrderRef     = frecord.OrderRef.ToString(),
                    OrderSysId   = frecord.OrderSysID
                };

                queue_refund_thread.GetQueue().Enqueue(refund);
                return("success");
            }

            return("未找到委托对应交易!");
        }
예제 #25
0
 void IMT4ServerConnectorHost.OnTrade(
     eMT4ServerType serverIndex, TradeRecord ptrTrade, TransType transType)
 {
     try
     {
         _orderManager.Value.OnTradeAsync(serverIndex, ptrTrade, transType, CancellationToken.None).Wait();
     }
     catch (Exception exception)
     {
         m_ptrLogger.LogException(exception);
     }
 }
예제 #26
0
        public TradeRecord MapTradeDataToTradeRecord(string[] tradeData)
        {
            int     tradeAmount = int.Parse(tradeData[0]);
            decimal tradePrice  = decimal.Parse(tradeData[1]);
            var     tradeRecord = new TradeRecord
            {
                TradeAmount = tradeAmount,
                TradePrice  = tradePrice
            };

            return(tradeRecord);
        }
예제 #27
0
        public GetTradeRecordsResponse(string body)
            : base(body)
        {
            this.TradeRecords = new LinkedList <TradeRecord>();
            JSONArray arr = (JSONArray)this.ReturnData;

            foreach (JSONObject tradeRecordJson in arr)
            {
                TradeRecord record = new TradeRecord(tradeRecordJson);
                this.TradeRecords.AddLast(record);
            }
        }
        public void TestCurrencyDestinationCurrency()
        {
            //Arrange
            var mapper = new SimpleTradeMapper();

            string[] strData = { "XXXYYY", "5000", "1.5" };
            //Act
            TradeRecord tradeRec = mapper.Map(strData);

            //Assert
            Assert.AreEqual(tradeRec.DestinationCurrency, "YYY");
        }
예제 #29
0
        public bool TryParse(string tradeRecord, int recordIndex, out TradeRecord parsedTadeRecord)
        {
            parsedTadeRecord = null;
            var fields = tradeRecord.Split(new char[] { ',' });

            if (fields.Length != 3)
            {
                _logger.Warn($"Line {recordIndex} malformed. Only {fields.Length} field(s) found.");
                return(false);
            }

            if (fields[0].Length != 6)
            {
                _logger.Warn($"Trade currencies on line {0} malformed: [{fields[0]}]");
                return(false);
            }

            int tradeAmount;

            if (!int.TryParse(fields[1], out tradeAmount))
            {
                _logger.Warn($"Trade amount on line {0} is not a valid integer: [{fields[1]}]");
                return(false);
            }
            else if (tradeAmount < 0)
            {
                _logger.Warn($"Trade amount on line {0} is a negative number: [{fields[1]}]");
                return(false);
            }

            decimal tradePrice;

            if (!decimal.TryParse(fields[2], out tradePrice))
            {
                _logger.Warn($"Trade price on line {0} is not a valid decimal: [{fields[1]}]");
                return(false);
            }

            var sourceCurrencyCode      = fields[0].Substring(0, 3);
            var destinationCurrencyCode = fields[0].Substring(3, 3);

            // Calculate values
            parsedTadeRecord = new TradeRecord
            {
                SourceCurrency      = sourceCurrencyCode,
                DestinationCurrency = destinationCurrencyCode,
                Lots  = tradeAmount / LotSize,
                Price = tradePrice
            };

            return(true);
        }
예제 #30
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List <TradeRecord> model = null;
                TradeRecord        trade = new TradeRecord();

                //var baseAddress = "http://localhost:8080/";
                var baseAddress = "http://" + tbNameHost.Text + "/";
                var client      = new HttpClient {
                    BaseAddress = new Uri(baseAddress)
                };

                string result = "";
                string Param  = "";
                Param = tbProdId.Text;

                string RequestStr = "api/Convert/" + Param;
                var    task       = client.GetAsync(RequestStr)
                                    .ContinueWith((taskwithresponse) =>
                {
                    var response  = taskwithresponse.Result;
                    var resString = response.Content.ReadAsStringAsync();
                    resString.Wait();
                    result = resString.Result;
                    try
                    {
                        //model = JsonConvert.DeserializeObject<List<TradeRecord>>(result);
                        trade = JsonConvert.DeserializeObject <TradeRecord>(result);
                        model = new List <TradeRecord>();
                        model.Add(trade);
                    }catch (Exception x)
                    {
                        Console.WriteLine("Error JsonConvert: " + x.Message + "\n" + result);
                    }
                });
                task.Wait();

                if (model != null)
                {
                    lvResult.ItemsSource = model;
                }

                tbRequest.Text = RequestStr;
                tbResult.Text  = result;
                Work.SetRichTextBoxText(rtbResult, tbResult.Text);
            }catch (Exception x)
            {
                tbResult.Text = "Error: " + x.Message;
                Work.SetRichTextBoxText(rtbResult, tbResult.Text);
            }
        }
        public TradeRecord Map(string[] fields)
        {
            var sourceCurrencyCode = fields[0].Substring(0, 3);
            var destinationCurrencyCode = fields[0].Substring(3, 3);
            var tradeAmount = int.Parse(fields[1]);
            var tradePrice = decimal.Parse(fields[2]);

            var trade = new TradeRecord
            {
                SourceCurrency = sourceCurrencyCode,
                DestinationCurrency = destinationCurrencyCode,
                Lots = tradeAmount / LotSize,
                Price = tradePrice
            };

            return trade;
        }
        private TradeRecord MapTradeDataToTradeRecord(string[] fields)
        {
            var sourceCurrencCode = fields[0].Substring(0, 3);
            var destinationCurrencyCode = fields[0].Substring(3, 3);
            var tradeAmount = int.Parse(fields[1]);
            var tradePrice = decimal.Parse(fields[2]);

            var tradeRecord = new TradeRecord
            {
                SourceCurrency = sourceCurrencCode,
                DestinationCurrency = destinationCurrencyCode,
                Lots = tradeAmount, // / LotSize,
                Price = tradePrice
            };

            return tradeRecord;
        }
        public void ProcessTrades(Stream stream)
        {
            // read rows
            var lines = new List<string>();
            using (var reader = new StreamReader(stream))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    lines.Add(line);
                }
            }

            var trades = new List<TradeRecord>();

            var lineCount = 1;
            foreach (var line in lines)
            {
                var fields = line.Split(new char[] { ',' });

                if (fields.Length != 3)
                {
                    Console.WriteLine("WARN: Line {0} malformed. Only {1} field(s) found.", lineCount, fields.Length);
                    continue;
                }

                if (fields[0].Length != 6)
                {
                    Console.WriteLine("WARN: Trade currencies on line {0} malformed: '{1}'", lineCount, fields[0]);
                    continue;
                }

                int tradeAmount;
                if (!int.TryParse(fields[1], out tradeAmount))
                {
                    Console.WriteLine("WARN: Trade amount on line {0} not a valid integer: '{1}'", lineCount, fields[1]);
                }

                decimal tradePrice;
                if (!decimal.TryParse(fields[2], out tradePrice))
                {
                    Console.WriteLine("WARN: Trade price on line {0} not a valid decimal: '{1}'", lineCount, fields[2]);
                }

                var sourceCurrencyCode = fields[0].Substring(0, 3);
                var destinationCurrencyCode = fields[0].Substring(3, 3);

                // calculate values
                var trade = new TradeRecord
                {
                    SourceCurrency = sourceCurrencyCode,
                    DestinationCurrency = destinationCurrencyCode,
                    Lots = tradeAmount / LotSize,
                    Price = tradePrice
                };

                trades.Add(trade);

                lineCount++;
            }

            using (var connection = new System.Data.SqlClient.SqlConnection("Data Source=(local);Initial Catalog=TradeDatabase;Integrated Security=True;"))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    foreach (var trade in trades)
                    {
                        var command = connection.CreateCommand();
                        command.Transaction = transaction;
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.CommandText = "dbo.insert_trade";
                        command.Parameters.AddWithValue("@sourceCurrency", trade.SourceCurrency);
                        command.Parameters.AddWithValue("@destinationCurrency", trade.DestinationCurrency);
                        command.Parameters.AddWithValue("@lots", trade.Lots);
                        command.Parameters.AddWithValue("@price", trade.Price);

                        command.ExecuteNonQuery();
                    }

                    transaction.Commit();
                }
                connection.Close();
            }

            Console.WriteLine("INFO: {0} trades processed", trades.Count);
        }