public KwuickService(ISession session, IBodyParser bodyParser, ICreateKUser createKUser, IResponseManager responseManager, IKUserFetcher kUserFetcher, ICommClient commClient) { _session = session; _bodyParser = bodyParser; _createKUser = createKUser; _responseManager = responseManager; _kUserFetcher = kUserFetcher; _commClient = commClient; }
public void ExecuteAsync( ICommClient port, ModbusCommand command) { var data = new ClientCommData(this); data.UserData = command; Codec.ClientEncode(data); port.QueryAsync(data); }
/// <summary> /// Calculates a flat commission for a given order. /// </summary> /// <param name="client">The order for which to calculate the commission.</param> /// <returns>The value of the commission.</returns> public override Money Calculate(ICommClient client) { Money amount = null; Money fee = null; if (!(client.IsSizeBased)) { // Value based order bool isValueInclComm = true; if (client.OrderType == OrderTypes.AmountBased) isValueInclComm = client.IsValueInclComm; if (isValueInclComm) { // Value includes the commission -> calculate backwards using Amount // Value includes commission -> Subtract the previous calculated commission amount = client.Amount + client.PreviousCalculatedFee; fee = calculateNett(amount, client); AdjustBondCommission(client, ref fee); } else { // Value does not include the commission -> calculate normal amount = client.Amount - client.PreviousCalculatedFee; // Sell -> Add Commission over the commission if (client.Type == CommClientType.Order && client.Side == Side.Sell) fee = calculateForwards(amount, client); else fee = calculateNormal(amount, client); } } else { // Size based Order if (client.Type == CommClientType.Order) { // Calculate the Indicative Commission amount = GetAmountSizeBasedOrder(client); if (amount != null) { // amount is fixed (size * price) -> Add the previous calculated commission amount = amount - client.PreviousCalculatedFee; fee = calculateNormal(amount, client); } } else { // Commission is calculated at Order.Fill time // sp price is known fee = calculateNormal(client.Amount, client); } } return ConvertToOrderCurrency(fee, client); }
private void BtnConnectClick(object sender, EventArgs e) { try { switch (CommunicationMode) { case CommunicationMode.RTU: _uart = new SerialPort(PortName, Baud, Parity, DataBits, StopBits); _uart.Open(); _portClient = _uart.GetClient(); _driver = new ModbusClient(new ModbusRtuCodec()) { Address = SlaveId }; _driver.OutgoingData += DriverOutgoingData; _driver.IncommingData += DriverIncommingData; AppendLog(String.Format("Connected using RTU to {0}", PortName)); break; case CommunicationMode.UDP: _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _socket.Connect(new IPEndPoint(IPAddress, TCPPort)); _portClient = _socket.GetClient(); _driver = new ModbusClient(new ModbusTcpCodec()) { Address = SlaveId }; _driver.OutgoingData += DriverOutgoingData; _driver.IncommingData += DriverIncommingData; AppendLog(String.Format("Connected using UDP to {0}", _socket.RemoteEndPoint)); break; case CommunicationMode.TCP: _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); _socket.SendTimeout = 2000; _socket.ReceiveTimeout = 2000; _socket.Connect(new IPEndPoint(IPAddress, TCPPort)); _portClient = _socket.GetClient(); _driver = new ModbusClient(new ModbusTcpCodec()) { Address = SlaveId }; _driver.OutgoingData += DriverOutgoingData; _driver.IncommingData += DriverIncommingData; AppendLog(String.Format("Connected using TCP to {0}", _socket.RemoteEndPoint)); break; } } catch (Exception ex) { AppendLog(ex.Message); return; } btnConnect.Enabled = false; buttonDisconnect.Enabled = true; groupBoxFunctions.Enabled = true; groupBoxTCP.Enabled = false; groupBoxRTU.Enabled = false; groupBoxMode.Enabled = false; grpExchange.Enabled = false; }
/// <summary> /// Calculates a simple, constant commission for a given order. /// </summary> /// <param name="client">The order for which to calculate the commission.</param> /// <returns>The value of the commission.</returns> public override Money Calculate(ICommClient client) { if (FixedSetup != null) { SetCommissionInfoOnOrder(client, string.Format("Fixed commission of {0}.", FixedSetup.ToString())); return FixedSetup; } else { SetCommissionInfoOnOrder(client, "No commission needed."); return new Money(0m, CommCurrency); } }
/// <summary> /// Entry-point for submitting any command /// </summary> /// <param name="port">The client port for the transport</param> /// <param name="command">The command to be submitted</param> /// <returns>The result of the query</returns> public CommResponse ExecuteGeneric( ICommClient port, ModbusCommand command) { var data = new ClientCommData(this); data.UserData = command; Codec.ClientEncode(data); var rVal = port.Query(data); if (data.OutgoingData != null) OnOutgoingData(data.OutgoingData.ToArray()); if (data.IncomingData != null) OnIncommingData(data.IncomingData.ToArray()); return rVal; }
private void DoDisconnect() { if (_socket != null) { _socket.Close(); _socket.Dispose(); _socket = null; } if (_uart != null) { _uart.Close(); _uart.Dispose(); _uart = null; } _portClient = null; _driver = null; }
public ICommRule FindRule(ICommClient client) { List<ICommRule> results = new List<ICommRule>(); ICommRule result = null; // First reset the weights back to 0 foreach (ICommRule rd in dependencies) { rd.Weight = 0; } // Calculate the weight foreach (ICommRule rd in dependencies.Where(x => x.AssetManager.Key == client.Account.AccountOwner.Key && (client.TransactionDate >= x.StartDate) && (Util.IsNullDate(x.EndDate) || (Util.IsNotNullDate(x.EndDate) && client.TransactionDate <= x.EndDate)))) { if (rd.CalculateWeight(client)) { results.Add(rd); } } if (results.Count > 0) result = (ICommRule)results.OrderByDescending(x => x.Weight).FirstOrDefault(); return result; }
/// <summary> /// Calculates a flat commission for a given order. /// </summary> /// <param name="client">The order for which to calculate the commission.</param> /// <returns>The value of the commission.</returns> public override Money Calculate(ICommClient client) { InstrumentSize size = null; Money amount = null; Money fee = null; if (!(client.IsSizeBased)) { // Value based order bool isValueInclComm = true; if (client.OrderType == OrderTypes.AmountBased) isValueInclComm = client.IsValueInclComm; if (isValueInclComm) { // Value includes the commission -> calculate backwards using Amount // Value includes commission -> Subtract the previous calculated commission amount = client.Amount + client.PreviousCalculatedFee; fee = calculateNett(amount, client); } else { // Value does not include the commission -> calculate normal // Calculate the Indicative Commission size = GetSizeAmountBasedOrder(client, isValueInclComm); if (size == null) return null; else fee = calculateNormal(size, client); } } else fee = calculateNormal(client.Value, client); return ConvertToOrderCurrency(fee, client); }
/// <summary> /// Calculates the amount for a size-based order, by finding out the price first. /// </summary> /// <param name="client">The order for which to calculate.</param> /// <param name="isValueInclComm">Is Value Incl. Comm.</param> /// <returns>The calculated amount.</returns> protected InstrumentSize GetSizeAmountBasedOrder(ICommClient client, bool isValueInclComm) { Price price = client.Price; if (price == null) { IPriceDetail priceDetail = client.TradedInstrument.CurrentPrice; if (priceDetail != null) { price = priceDetail.Price; SetCommissionInfoOnOrder(client, string.Format("Use current price {0} from date {1}", price.ToString(), priceDetail.Date.ToShortDateString())); } } else if (client.Price != null) { price = client.Price; SetCommissionInfoOnOrder(client, string.Format("Use price {0} from order", client.Price.ToString())); } if (price == null) { SetCommissionInfoOnOrder(client, "No price available so the commission is €0"); return null; } else { if (isValueInclComm) { // Value includes the commission return (client.Amount + client.PreviousCalculatedFee).CalculateSize(price); } else { // Value does not include the commission return (client.Amount - client.PreviousCalculatedFee).CalculateSize(price); } } }
CommandMsgV2 _StartAdapter(ICommunicationMessage message) { try { CommandMsgV2 resp = new CommandMsgV2(); resp.TK_CommandType = Constants.TK_CommandType.RESPONSE; resp.SeqID = CommandProcessor.AllocateID(); resp.SetValue("ClientID", message.GetValue("ClientID")); resp.SetValue(Constants.MSG_PARANAME_RESPONSE_TO, message.SeqID); long adapterid = Convert.ToInt64(message.GetValue(Constants.MSG_PARANAME_ADAPTER_ID)); C5.HashDictionary <long, AdapterInfo> ads = new C5.HashDictionary <long, AdapterInfo>(); AlarmManager.instance().GetAdaptersInfo(ads); if (!ads.Contains(adapterid)) { resp.SetValue(Constants.MSG_PARANAME_RESULT, "NOK"); resp.SetValue(Constants.MSG_PARANAME_REASON, "采集器不存在."); return(resp); } try { CommandMsgV2 cmd = new CommandMsgV2(); cmd.SeqID = CommandProcessor.AllocateID(); cmd.TK_CommandType = Constants.TK_CommandType.ADAPTER_START; cmd.SetValue("ClientID", adapterid); cmd.SetValue(Constants.MSG_PARANAME_ADAPTER_NAME, ads[adapterid].Name); System.Net.IPEndPoint end = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ads[adapterid].Address), ads[adapterid].ControllerPort); if (end.Port == 0) { resp.SetValue(Constants.MSG_PARANAME_RESULT, "NOK"); resp.SetValue(Constants.MSG_PARANAME_REASON, "不可远程控制的采集器"); } else { ICommClient comm = CommManager.instance().CreateCommClient <CommandMsgV2, TKMessageV2Extractor, TKMessageV2Encoder>("控制器", end.Address.ToString(), end.Port, 30, false, false); comm.Start(); ICommunicationMessage r2 = comm.SendCommand(cmd); resp.SetValue(Constants.MSG_PARANAME_RESULT, r2.GetValue(Constants.MSG_PARANAME_RESULT)); comm.Close(); } } catch (Exception ex) { resp.SetValue(Constants.MSG_PARANAME_RESULT, "NOK"); resp.SetValue(Constants.MSG_PARANAME_REASON, ex.Message); } return(resp); } catch (Exception ex) { Logger.Instance().SendLog(ex.ToString()); return(null); } }
/// <summary> /// Used by method <b>Calculate</b> on derived classes to perform the common part of the commission calculation. /// </summary> /// <param name="size">The size for which to calculate commission.</param> /// <param name="client">The order for which to calculate commission.</param> /// <returns>The value of the commission.</returns> protected Money calculateNormal(InstrumentSize size, ICommClient client) { Money result = new Money(0m, CommCurrency); InstrumentSize comSize = size.Abs(); foreach (CommCalcLineSizeBased line in CommLines) { if (line.Envelops(comSize)) { result = line.Calculate(comSize); SetCommissionInfoOnOrder(client, string.Format("Flat -> Size ({0}) {1} -> use {2}.", comSize.DisplayString, line.DisplayRange, line.LineDistinctives)); break; } } return addFixMinMax(result, client); }
void CommClient_onConnectionBroken(ICommClient ptr, string sLog) { //this.Close(); // do nothing }
private static bool IsDead(ICommClient client) { ICommunicationObject ico = client as ICommunicationObject; return(ico != null && ico.State != CommunicationState.Opened); }
public static void Main() { #if MASTER_TCP || MASTER_UDP || SLAVE_TCP || SLAVE_UDP //setup the board IP NetworkInterface.GetAllNetworkInterfaces()[0] .EnableStaticIP("192.168.0.99", "255.255.255.0", "192.168.0.1"); string localip = NetworkInterface.GetAllNetworkInterfaces()[0] .IPAddress; Debug.Print("The local IP address of your Netduino Plus is " + localip); //define coils, inputs, and analogs _inputs = new InputPort[8]; _coils = new OutputPort[6]; _analogs = new AnalogInput[6]; _inputs[0] = new InputPort(Pins.GPIO_PIN_D0, true, Port.ResistorMode.PullUp); _inputs[1] = new InputPort(Pins.GPIO_PIN_D1, true, Port.ResistorMode.PullUp); _inputs[2] = new InputPort(Pins.GPIO_PIN_D2, true, Port.ResistorMode.PullUp); _inputs[3] = new InputPort(Pins.GPIO_PIN_D3, true, Port.ResistorMode.PullUp); _inputs[4] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp); _inputs[5] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp); _inputs[6] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp); _inputs[7] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp); _coils[0] = new OutputPort(Pins.GPIO_PIN_D8, false); _coils[1] = new OutputPort(Pins.GPIO_PIN_D9, false); _coils[2] = new OutputPort(Pins.GPIO_PIN_D10, false); _coils[3] = new OutputPort(Pins.GPIO_PIN_D11, false); _coils[4] = new OutputPort(Pins.GPIO_PIN_D12, false); _coils[5] = new OutputPort(Pins.GPIO_PIN_D13, false); _analogs[0] = new AnalogInput(Pins.GPIO_PIN_A0); _analogs[1] = new AnalogInput(Pins.GPIO_PIN_A1); _analogs[2] = new AnalogInput(Pins.GPIO_PIN_A2); _analogs[3] = new AnalogInput(Pins.GPIO_PIN_A3); _analogs[4] = new AnalogInput(Pins.GPIO_PIN_A4); _analogs[5] = new AnalogInput(Pins.GPIO_PIN_A5); #else //define coils, inputs, and analogs _inputs = new InputPort[4]; _coils = new OutputPort[6]; _analogs = new AnalogInput[6]; _inputs[0] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp); _inputs[1] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp); _inputs[2] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp); _inputs[3] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp); _coils[0] = new OutputPort(Pins.GPIO_PIN_D8, false); _coils[1] = new OutputPort(Pins.GPIO_PIN_D9, false); _coils[2] = new OutputPort(Pins.GPIO_PIN_D10, false); _coils[3] = new OutputPort(Pins.GPIO_PIN_D11, false); _coils[4] = new OutputPort(Pins.GPIO_PIN_D12, false); _coils[5] = new OutputPort(Pins.GPIO_PIN_D13, false); _analogs[0] = new AnalogInput(Pins.GPIO_PIN_A0); _analogs[1] = new AnalogInput(Pins.GPIO_PIN_A1); _analogs[2] = new AnalogInput(Pins.GPIO_PIN_A2); _analogs[3] = new AnalogInput(Pins.GPIO_PIN_A3); _analogs[4] = new AnalogInput(Pins.GPIO_PIN_A4); _analogs[5] = new AnalogInput(Pins.GPIO_PIN_A5); #endif #if MASTER_TCP //create a TCP socket using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { //refine the socket settings socket.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true ); socket.SendTimeout = 2000; socket.ReceiveTimeout = 2000; //try the connection against the remote device var remoteip = new byte[4] { 192, 168, 0, 60 }; var ipaddr = new IPAddress(remoteip); var ept = new IPEndPoint(ipaddr, 502); socket.Connect(ept); //create a wrapper around the socket ICommClient portClient = socket.GetClient(); //create a client driver var driver = new ModbusClient(new ModbusTcpCodec()); driver.Address = 1; while (true) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncWriteMultipleRegisters); command.Offset = 49; command.Count = 4; //attach the Netduino's input values as data command.Data = new ushort[4]; for (int i = 0; i < 4; i++) { command.Data[i] = (ushort)(_inputs[i].Read() ? 0 : 1); } //execute the command synchronously CommResponse result = driver .ExecuteGeneric(portClient, command); if (result.Status == CommResponse.Ack) { //command successfully } else { //some error Debug.Print("Error=" + command.ExceptionCode); } //just a small delay Thread.Sleep(1000); } } #endif #if MASTER_UDP //create a UDP socket using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { //try the connection against the remote device var remoteip = new byte[4] { 192, 168, 0, 60 }; var ipaddr = new IPAddress(remoteip); var ept = new IPEndPoint(ipaddr, 502); socket.Connect(ept); //create a wrapper around the socket ICommClient portClient = socket.GetClient(); //create a client driver var driver = new ModbusClient(new ModbusTcpCodec()); driver.Address = 1; while (true) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncReadMultipleRegisters); command.Offset = 0; command.Count = 16; //execute the command synchronously CommResponse result = driver .ExecuteGeneric(portClient, command); if (result.Status == CommResponse.Ack) { //command successfully Debug.Print("Success!"); for (int i = 0; i < command.Count; i++) { Debug.Print("Reg#" + i + "=" + command.Data[i]); } } else { //some error Debug.Print("Error=" + command.ExceptionCode); } //just a small delay Thread.Sleep(1000); } } #endif #if MASTER_RTU //create an UART port using (var uart = new SerialPort("COM2", 38400, Parity.Even, 8)) { //open the serial port uart.Open(); var prm = new SerialPortParams("38400,E,8,1"); //create a wrapper around the uart ICommClient portClient = uart .GetClient(prm); //create a client driver var driver = new ModbusClient(new ModbusRtuCodec()); driver.Address = 1; while (true) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncWriteMultipleRegisters); command.Offset = 49; command.Count = 4; //attach the Netduino's input values as data command.Data = new ushort[4]; for (int i = 0; i < 4; i++) { command.Data[i] = (ushort)(_inputs[i].Read() ? 0 : 1); } //execute the command synchronously CommResponse result = driver .ExecuteGeneric(portClient, command); if (result.Status == CommResponse.Ack) { //command successfully } else { //some error Debug.Print("Error=" + command.ExceptionCode); } //just a small delay Thread.Sleep(1000); } } #endif #if SLAVE_RTU //create an UART port using (var uart = new SerialPort("COM2", 38400, Parity.Even, 8)) { //open the serial port uart.Open(); var prm = new SerialPortParams("38400,E,8,1"); //create a server driver var server = new ModbusServer(new ModbusRtuCodec()); server.Address = 1; //listen for an incoming request var listener = uart.GetListener(server); listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand); listener.Start(); Thread.Sleep(Timeout.Infinite); } #endif #if SLAVE_TCP //create a TCP socket using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { //place it as listener on the port 502 (standard Modbus) var ept = new IPEndPoint(IPAddress.Any, 502); socket.Bind(ept); socket.Listen(10); //create a server driver var server = new ModbusServer(new ModbusTcpCodec()); server.Address = 1; while (true) { //wait for an incoming connection var listener = socket.GetTcpListener(server); listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand); listener.Start(); Thread.Sleep(1); } } #endif #if SLAVE_UDP //create a UDP socket using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { //bind it to the port 502 (standard Modbus) var ept = new IPEndPoint(IPAddress.Any, 502); socket.Bind(ept); //create a server driver var server = new ModbusServer(new ModbusTcpCodec()); server.Address = 1; //listen for an incoming request var listener = socket.GetUdpListener(server); listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand); listener.Start(); Thread.Sleep(Timeout.Infinite); } #endif }
/// <summary> /// Converts an amount to the currency of a given order. /// </summary> /// <param name="fee">The amount to convert.</param> /// <param name="client">The order whose currency to convert to.</param> /// <returns></returns> protected Money ConvertToOrderCurrency(Money fee, ICommClient client) { if (fee != null) { if ((ICurrency)fee.Underlying != client.OrderCurrency) fee = fee.Convert(client.OrderCurrency); return fee.Round(); } else return new Money(0, client.OrderCurrency); }
/// <summary> /// Used by method <b>Calculate</b> on derived classes to perform the commission calculation for amount based sell exclusive orders. /// </summary> /// <param name="nettAmount">The amount for which to calculate commission.</param> /// <param name="client">The order for which to calculate commission.</param> /// <returns>The value of the commission.</returns> protected Money calculateForwards(Money nettAmount, ICommClient client) { if (!(client.Type != CommClientType.Transaction && client.Side == Side.Sell && client.IsValueInclComm == false)) throw new ApplicationException("There is a bug in the program flow in the fees module."); Money result = new Money(0m, CommCurrency); Money comAmount = getCommAmount(nettAmount); ITradeableInstrument instrument = (ITradeableInstrument)client.TradedInstrument; if (instrument.CurrentPrice == null) throw new ApplicationException("It is not possible to calculate the commission when there is no current price."); InstrumentSize size = comAmount.CalculateSize(instrument.CurrentPrice.Price); foreach (CommCalcLineSizeBased line in CommLines) { if (line.Envelops(size)) { result = line.Calculate(size); SetCommissionInfoOnOrder(client, string.Format("Flat (forwards) -> Size ({0}) {1} -> use {2}.", comAmount.ToString(), line.DisplayRange, line.LineDistinctives)); break; } } return addFixMinMax(result, client); }
protected virtual TransactionFillDetails getTransactionFillDetailsAmountBasedOrderByGoalSeek( Money grossAmount, Side side, bool isCommissionRelevant, bool isValueInclComm, DateTime settlementDate, Price price, IExchange exchange, ICommRule rule, ICommClient client, decimal servChargePerc, int precision) { decimal realAmount; decimal guess = grossAmount.Abs().CalculateSize(price).Quantity; FinancialMath.MaxCycles = 200; // Check -> use Commission bool useComm = true; bool useAddComm = false; if (!isCommissionRelevant || rule == null) useComm = false; if (useComm) useAddComm = (rule.AdditionalCalculation != null); realAmount = FinancialMath.GoalSeek(x => new InstrumentSize(x, this).CalculateAmount(price).Quantity + (useComm ? rule.CommCalculation.Calculate(client.GetNewInstance(new InstrumentSize(x, this), price, (useAddComm ? rule.AdditionalCalculation.Calculate(client.GetNewInstance(new InstrumentSize(x, this), price)) : null))).Quantity : 0M) + (useAddComm ? rule.AdditionalCalculation.Calculate(client.GetNewInstance(new InstrumentSize(x, this), price)).Quantity : 0M) + (new InstrumentSize(x, this).CalculateAmount(price).Abs().Quantity * servChargePerc), grossAmount.Abs().Quantity, guess, precision); InstrumentSize size = new InstrumentSize(realAmount, this); Money amount = size.CalculateAmount(price); InstrumentSize cleanSize = amount.CalculateSize(price); Money servCh = (amount.Abs() * servChargePerc); Money comm = amount.ZeroedAmount(); Money addComm = amount.ZeroedAmount(); if (useComm) { if (rule.AdditionalCalculation != null) addComm = rule.AdditionalCalculation.Calculate(client.GetNewInstance(cleanSize, price)); comm = rule.CommCalculation.Calculate(client.GetNewInstance(cleanSize, price, addComm)); // if sell -> comm is already in the amount if (side == Side.Sell && (comm + addComm) != null && (comm + addComm).IsNotZero) { amount += (comm + addComm); cleanSize = amount.CalculateSize(price); if (!isValueInclComm) { if (rule.AdditionalCalculation != null) addComm = rule.AdditionalCalculation.Calculate(client.GetNewInstance(cleanSize, price)); comm = rule.CommCalculation.Calculate(client.GetNewInstance(cleanSize, price, addComm)); } } } return new TransactionFillDetails(cleanSize, amount, null, servCh, servChargePerc, comm + addComm, grossAmount.Abs(), side); }
virtual public void Init(ICommClient comm) { m_CommClient = comm; }
private Money calculateNett(Money amount, ICommClient client) { Money fee = null; foreach (CommCalcLineAmountBased line in CommLines) { if (line.CalculateBackwards(amount, out fee)) { SetCommissionInfoOnOrder(client, string.Format("Flat (backwards) -> Amount ({0}) {1} -> use {2}.", amount.ToString(), line.DisplayRange, line.LineDistinctives)); break; } } return fee; }
public ICommRule GetRelevantCommRule(IAccountTypeInternal account, IInstrument instrument, Side side, OrderActionTypes actiontype, DateTime transactionDate, bool isAmountBased, out ICommClient client) { client = new CommClient(account, instrument, side, actiontype, transactionDate, !isAmountBased, null, null, null, null, false); return GetRelevantCommRule(client); }
public ICommRule GetRelevantCommRule(ICommClient client) { return feeFactory.commRuleFinder.FindRule(client); }
/// <summary> /// The method used by <b>Order</b> and <b>Transaction</b> classes to calculate their attached fees. Also, if applicable, /// the service charge is calculated /// </summary> /// <param name="client">The client (order/transaction) for which the fee is calculated.</param> /// <returns>The commission value .</returns> public Commission CalculateCommission(ICommClient client) { Commission cvd = new Commission(); Money fee = null; if (feeFactory.commRuleFinder == null) { throw new ApplicationException("There are no Commission Rules initialised"); } if (client.Account.AccountType != AccountTypes.Customer) return null; ICommRule commRule = feeFactory.commRuleFinder.FindRule(client); ICommCalc commCalculation = null; if (commRule != null) { // Step 01 : Introduction Fee if (commRule.AdditionalCalculation != null) { ICommCalc feeCalc2 = commRule.AdditionalCalculation; client.CommissionInfo = "Additional Fee: " + feeCalc2.Name + ". "; Money fee2 = feeCalc2.Calculate(client); if (fee2 != null) { if (fee2.Sign) fee2 = fee2.Abs() * -1; if (!fee2.Underlying.Equals(client.OrderCurrency)) fee2 = fee2.Convert(client.OrderCurrency); } else fee2 = new Money(0, client.OrderCurrency); client.PreviousCalculatedFee = fee2; cvd.BreakupLines.Add(new CommissionBreakupLine(fee2, CommissionBreakupTypes.AdditionalCommission, client.CommissionInfo)); client.CommissionInfo = ""; } // Step 02 : Commission commCalculation = commRule.CommCalculation; fee = commCalculation.Calculate(client); client.CommissionInfo = "Commission rule: " + commRule.ToString() + ". " + client.CommissionInfo; } else client.CommissionInfo = "No commission rule found."; if (fee != null) { if (fee.Sign) fee = fee.Abs() * -1; if (!fee.Underlying.Equals(client.OrderCurrency)) fee = fee.Convert(client.OrderCurrency); } else fee = new Money(0, client.OrderCurrency); cvd.BreakupLines.Add(new CommissionBreakupLine(fee, CommissionBreakupTypes.Commission, client.CommissionInfo)); return cvd; }
private Money calculateNett(Money amount, ICommClient client) { Money fee = null; Tuple<InstrumentSize, Money> result; Price price = client.Price; if (price == null && client.TradedInstrument.IsTradeable) price = ((ITradeableInstrument)client.TradedInstrument).CurrentPrice.Get(e => e.Price); foreach (CommCalcLineSizeBased line in CommLines) { if (line.CalculateBackwards(amount, price, client.Side, out result)) { SetCommissionInfoOnOrder(client, string.Format("Flat (backwards) -> Size ({0}) {1} -> use {2}.", result.Item1.DisplayString, line.DisplayRange, line.LineDistinctives)); fee = result.Item2; break; } } return fee; }
/// <summary> /// If this is a bond amount based order -> tweak the commission a bit for accrued interest /// </summary> /// <param name="client"></param> /// <param name="fee"></param> protected internal virtual void AdjustBondCommission(ICommClient client, ref Money fee) { decimal sign = client.Side == Side.Buy ? 1M : -1M; if (!client.AmountIsNett && !client.IsValueInclComm && client.AccruedInterest != null && client.AccruedInterest.IsNotZero) fee = client.GrossAmount * (fee.Quantity / (client.Amount + client.AccruedInterest + (fee * sign)).Quantity); }
/// <summary> /// Adds a message to field CommissionInfo of the order. /// </summary> /// <param name="client">The order to which to add the message.</param> /// <param name="message">The message to add.</param> protected void SetCommissionInfoOnOrder(ICommClient client, string message) { client.CommissionInfo += System.Environment.NewLine + message; }
private void BtnConnectClick(object sender, EventArgs e) { try { switch (this.CommunicationMode) { case CommunicationMode.TCP: this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this._socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Debug, true); this._socket.SendTimeout = 2000; this._socket.ReceiveTimeout = 2000; this._socket.Connect((EndPoint) new IPEndPoint(this.IPAddress, this.TCPPort)); this._portClient = this._socket.GetClient(); this._driver = new ModbusClient((IProtocolCodec) new ModbusTcpCodec()) { Address = this.SlaveId }; this._driver.OutgoingData += new ModbusCommand.OutgoingData(((BaseForm)this).DriverOutgoingData); this._driver.IncommingData += new ModbusCommand.IncommingData(((BaseForm)this).DriverIncommingData); this.AppendLog(string.Format("Connected using TCP to {0}", (object)this._socket.RemoteEndPoint)); break; case CommunicationMode.UDP: this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); this._socket.Connect((EndPoint) new IPEndPoint(this.IPAddress, this.TCPPort)); this._portClient = this._socket.GetClient(); this._driver = new ModbusClient((IProtocolCodec) new ModbusTcpCodec()) { Address = this.SlaveId }; this._driver.OutgoingData += new ModbusCommand.OutgoingData(((BaseForm)this).DriverOutgoingData); this._driver.IncommingData += new ModbusCommand.IncommingData(((BaseForm)this).DriverIncommingData); this.AppendLog(string.Format("Connected using UDP to {0}", (object)this._socket.RemoteEndPoint)); break; case CommunicationMode.RTU: this._uart = new SerialPort(this.PortName, this.Baud, this.Parity, this.DataBits, this.StopBits); this._uart.Open(); this._portClient = this._uart.GetClient(); this._driver = new ModbusClient((IProtocolCodec) new ModbusRtuCodec()) { Address = this.SlaveId }; this._driver.OutgoingData += new ModbusCommand.OutgoingData(((BaseForm)this).DriverOutgoingData); this._driver.IncommingData += new ModbusCommand.IncommingData(((BaseForm)this).DriverIncommingData); this.AppendLog(string.Format("Connected using RTU to {0}", (object)this.PortName)); break; } } catch (Exception ex) { this.AppendLog(ex.Message); return; } this.btnConnect.Enabled = false; this.buttonDisconnect.Enabled = true; this.groupBoxFunctions.Enabled = true; this.groupBoxTCP.Enabled = false; this.groupBoxRTU.Enabled = false; this.groupBoxMode.Enabled = false; this.grpExchange.Enabled = false; }
protected virtual TransactionFillDetails getTransactionFillDetailsAmountBasedOrderByGoalSeek( IOrderAmountBased order, DateTime settlementDate, Price price, IExchange exchange, ICommRule rule, ICommClient client, decimal servChargePerc, int precision) { try { TransactionFillDetails details = getTransactionFillDetailsAmountBasedOrderByGoalSeek( order.GrossAmount, order.Side, order.IsCommissionRelevant, order.IsValueInclComm, settlementDate, price, exchange, rule, client, servChargePerc, precision); if (details.IsOK) { Money diff = details.Diff; if (diff != null && diff.IsNotZero && diff.IsWithinTolerance(0.09M)) { details.FixUp(order); details.Size = details.Amount.CalculateSize(price); details.Info = string.Format("F{0}", precision); } } return details; } catch { } return new TransactionFillDetails(); }
/// <summary> /// Calculates the commission for a given order. /// </summary> /// <param name="client">The order for which to calculate the commission.</param> /// <returns>The value of the commission.</returns> public abstract Money Calculate(ICommClient client);
/// <summary> /// Used by method <b>Calculate</b> on derived classes to perform the common part of the commission calculation. /// </summary> /// <param name="amount">The amount for which to calculate commission.</param> /// <param name="client">The order for which to calculate commission.</param> /// <returns>The value of the commission.</returns> protected Money calculateNormal(Money amount, ICommClient client) { Money result = new Money(0m, CommCurrency); Money comAmount = getCommAmount(amount); foreach (CommCalcLine line in CommLines) { if (line.Envelops(comAmount)) { result = line.Calculate(comAmount); SetCommissionInfoOnOrder(client, string.Format("Flat -> Amount ({0}) {1} -> use {2}.", comAmount.ToString(), line.DisplayRange, line.LineDistinctives)); break; } } return addFixMinMax(result, client); }
protected Money addFixMinMax(Money fee, ICommClient client) { // Add Fixed setup if (FixedSetup != null && FixedSetup.IsNotZero) { fee += FixedSetup; SetCommissionInfoOnOrder(client, string.Format("Add setup {0}", FixedSetup.ToString())); } // Check Minimum Value if (MinValue != null && MinValue.IsNotZero && fee < MinValue) { // Extra check -> does the minimum size not exceed the order value Money orderAmount = client.Amount; if (orderAmount != null && orderAmount.IsNotZero) { orderAmount = orderAmount.Abs(); if (!orderAmount.Underlying.Equals(this.CommCurrency)) orderAmount = orderAmount.Convert(this.CommCurrency); if (orderAmount > fee) { fee = MinValue; SetCommissionInfoOnOrder(client, string.Format("Calculated commission {0} is smaller than minimum value {1}", fee.ToString(), MinValue.ToString())); } else SetCommissionInfoOnOrder(client, string.Format("Order amount {0} is smaller than minimum value of the commission {1}, so it is not applied", orderAmount.ToString(), MinValue.ToString())); } } // Check Maximum Value if (MaxValue != null && MaxValue.IsNotZero && fee > MaxValue) { SetCommissionInfoOnOrder(client, string.Format("Calculated commission {0} exceeds the maximum value {1}", fee.ToString(), MaxValue.ToString())); fee = MaxValue; } return fee; }
/// <summary> /// Calculates a slab commission for a given order. /// </summary> /// <param name="client">The order for which to calculate the commission.</param> /// <returns>The value of the commission.</returns> public override Money Calculate(ICommClient client) { Money amount = null; Money fee = null; if (!(client.IsSizeBased)) // Value based order { bool isValueInclComm = true; if (client.OrderType == OrderTypes.AmountBased) isValueInclComm = client.IsValueInclComm; if (isValueInclComm) { decimal realAmount; amount = client.Amount + client.PreviousCalculatedFee; // Value does not include the commission if (client.Side == Side.Sell) // Sell -> Add Commission over the commission realAmount = FinancialMath.GoalSeek(x => x + calculateForwards(new Money(x, (ICurrency)amount.Underlying), client).Quantity, amount.Quantity, amount.Quantity); else //Buy -> calculate normal realAmount = FinancialMath.GoalSeek(x => x + calculateNormal(new Money(x, (ICurrency)amount.Underlying), client).Quantity, amount.Quantity, amount.Quantity); fee = amount - new Money(realAmount, (ICurrency)client.Amount.Underlying); AdjustBondCommission(client, ref fee); } else { amount = client.Amount - client.PreviousCalculatedFee; // Value does not include the commission if (client.Side == Side.Sell) // Sell -> Add Commission over the commission fee = calculateForwards(amount, client); else // Buy -> calculate normal fee = calculateNormal(amount, client); } } else // Size based order { if (client.Type == CommClientType.Order) { // Calculate the Indicative Commission amount = GetAmountSizeBasedOrder(client); if (amount != null) { amount = amount - client.PreviousCalculatedFee; fee = calculateNormal(amount, client); } } else { // Commission is calculated at Order.Fill time // sp price is known fee = calculateNormal(client.Amount, client); } } return ConvertToOrderCurrency(fee, client); }
/// <summary> /// Calculates the amount for a size-based order, by finding out the price first. /// </summary> /// <param name="client">The order for which to calculate.</param> /// <returns>The calculated amount.</returns> protected Money GetAmountSizeBasedOrder(ICommClient client) { Price price = client.Price; if (price == null) { IPriceDetail priceDetail = client.TradedInstrument.CurrentPrice; if (priceDetail != null) { price = priceDetail.Price; SetCommissionInfoOnOrder(client, string.Format("Use current price {0} from date {1}", price.ToString(), priceDetail.Date.ToShortDateString())); } } else if (client.Price != null) { price = client.Price; SetCommissionInfoOnOrder(client, string.Format("Use price {0} from order", client.Price.ToString())); } if (price == null) { SetCommissionInfoOnOrder(client, "No price available so the commission is €0"); return null; } else return client.Value.CalculateAmount(price); }
protected void RunCore( ICommClient medium, ModbusClient driver, CancellationToken token) { Action <bool> setPollingActivity = act => HardwareModel.Instance.IsPollingEnabled = act; int stage = 0; while (token.IsCancellationRequested == false) { //turn the polling activity on App.Current.Dispatcher.BeginInvoke( setPollingActivity, true); if (stage == 0) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncReadInputDiscretes); command.Offset = 0; command.Count = 8; //execute the command synchronously CommResponse result = driver .ExecuteGeneric(medium, command); if (result.Status == CommResponse.Ack) { //command successfully for (int i = 0; i < command.Count; i++) { HardwareModel.Instance.Coils[i].Write(command.Data[i] != 0); } stage = 1; } else { //some error Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode); } } else if (stage == 1) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncReadInputRegisters); command.Offset = 0; command.Count = 6; //execute the command synchronously CommResponse result = driver .ExecuteGeneric(medium, command); if (result.Status == CommResponse.Ack) { //command successfully for (int i = 0; i < command.Count; i++) { HardwareModel.Instance.Analogs[i].Value = command.Data[i] / 1023.0; } stage = 2; } else { //some error Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode); } } else if (stage == 2) { //compose the Modbus command to be submitted var command = new ModbusCommand(ModbusCommand.FuncForceMultipleCoils); command.Offset = 0; command.Count = 6; //attach the Netduino's input values as data command.Data = new ushort[command.Count]; for (int i = 0; i < command.Count; i++) { command.Data[i] = (ushort)(HardwareModel.Instance.Discretes[i].Read() ? 1 : 0); } //execute the command synchronously CommResponse result = driver .ExecuteGeneric(medium, command); if (result.Status == CommResponse.Ack) { //command successfully stage = 0; } else { //some error Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode); } } //turn the polling activity off App.Current.Dispatcher.Invoke( setPollingActivity, false); //just a small delay Thread.Sleep(100); } }
/// <summary> /// Used by method <b>Calculate</b> on derived classes to perform the commission calculation for amount based sell exclusive orders. /// </summary> /// <param name="nettAmount">The amount for which to calculate commission.</param> /// <param name="client">The order for which to calculate commission.</param> /// <returns>The value of the commission.</returns> protected Money calculateForwards(Money nettAmount, ICommClient client) { if (!(client.Type != CommClientType.Transaction && client.Side == Side.Sell)) throw new ApplicationException("There is a bug in the program flow in the fees module."); Money result = new Money(0m, CommCurrency); Money comAmount = getCommAmount(nettAmount); if (client.IsValueInclComm) client.CommissionInfo = ""; foreach (CommCalcLineAmountBased line in CommLines) { if (line.IsUnder(comAmount)) { Money lineAmount = (line.UpperRange - line.LowerRange); result += line.CalculateExtra(lineAmount); SetCommissionInfoOnOrder(client, string.Format("Slab (forwards) {0} -> {1} multiplied with {2}.", line.SerialNo.ToString(), lineAmount.ToString(), line.LineDistinctives)); } else if (line.Envelops(comAmount)) { Money lineAmount = (comAmount - line.LowerRange); result += line.CalculateExtra(comAmount - line.LowerRange); SetCommissionInfoOnOrder(client, string.Format("Slab (forwards) {0} -> {1} multiplied with {2}.", line.SerialNo.ToString(), lineAmount.ToString(), line.LineDistinctives)); } } return addFixMinMax(result, client); }
/// <summary> /// Used by method <b>Calculate</b> on derived classes to perform the common part of the commission calculation. /// </summary> /// <param name="amount">The amount for which to calculate commission.</param> /// <param name="client">The order for which to calculate commission.</param> /// <returns>The value of the commission.</returns> protected Money calculateNormal(Money amount, ICommClient client) { Money result = new Money(0m, CommCurrency); Money comAmount = getCommAmount(amount); if (client.IsValueInclComm) client.CommissionInfo = ""; foreach (CommCalcLineAmountBased line in CommLines) { if (line.IsUnder(comAmount)) { Money lineAmount = (line.UpperRange - line.LowerRange); result += line.Calculate(lineAmount); SetCommissionInfoOnOrder(client, string.Format("Slab {0} -> {1} multiplied with {2}.", line.SerialNo.ToString(), lineAmount.ToString(), line.LineDistinctives)); } else if (line.Envelops(comAmount)) { Money lineAmount = (comAmount - line.LowerRange); result += line.Calculate(comAmount - line.LowerRange); SetCommissionInfoOnOrder(client, string.Format("Slab {0} -> {1} multiplied with {2}.", line.SerialNo.ToString(), lineAmount.ToString(), line.LineDistinctives)); } } return addFixMinMax(result, client); }
protected void Init() { try { //获取应用程序运行路径 string path = AppDomain.CurrentDomain.BaseDirectory; DataSet DBds = new DataSet(); //读入数据库连接参数 DBds = MD5Encrypt.DES.instance().DecryptXML2DS(path + "conf.xml", 1); m_SysPara.Clear(); foreach (DataRow r in DBds.Tables["Parameters"].Rows) { m_SysPara.Add(r["name"].ToString(), r["value"].ToString()); } m_CommClient = CommManager.instance().CreateCommClient <CommandMsgV2, TKMessageV2Extractor, TKMessageV2Encoder>( m_SysPara["Adapter Name"].ToString(), m_SysPara["Server IP"].ToString(), Convert.ToInt32(m_SysPara["Server Port"]), Convert.ToInt32(m_SysPara["Comm Timeout"]), true, false); m_CommClient.onLog += new TK_AlarmManagement.LogHandler(LogReceiver); #region Declear Adapter m_Adapter = new T(); m_Adapter.ControllerPort = Convert.ToInt32(m_SysPara["Controller Port"]); m_Adapter.Name = m_SysPara["Adapter Name"].ToString(); m_Adapter.Interval = Convert.ToInt32(m_SysPara["Retrieve Interval"]); m_Adapter.SvrID = Convert.ToInt32(m_SysPara["SvrID"]); m_Adapter.EncodingStr = m_SysPara["Encoding"]; m_Adapter.Init(m_CommClient); #endregion DefLib.Util.Logger.Instance().SubscibeLog("", new DefLib.Util.Logger.LogFunction(LogReceiver)); //m_Adapter.LogReceived += new TK_AlarmManagement.LogHandler(LogReceiver); m_Adapter.StateChanged += new StateChangeHandler(m_Adapter_StateChanged); m_Name = m_Adapter.Name; // 配置监控终端服务器 List <Constants.TK_CommandType> acceptedCommands = new List <Constants.TK_CommandType>(); acceptedCommands.Add(Constants.TK_CommandType.RESPONSE); List <Constants.TK_CommandType> superCommands = new List <Constants.TK_CommandType>(); superCommands.Add(Constants.TK_CommandType.RESPONSE); m_ControllerServer = CommManager.instance().CreateCommServer <DefaultInterpreter, CommandMsgV2, TKMessageV2Extractor, TKMessageV2Encoder>("监控服务器", acceptedCommands, superCommands, Convert.ToInt32(m_SysPara["Controller Port"]), Convert.ToInt32(m_SysPara["MaxController"]), 30, true, false); m_ControllerServer.onLog += new LogHandler(LogReceiver); acceptedCommands.Clear(); superCommands.Clear(); Dictionary <Constants.TK_CommandType, byte> empty = new Dictionary <Constants.TK_CommandType, byte>(); CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_START, this, empty); CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_STOP, this, empty); CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_GETRUNTIMEINFO, this, empty); CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_GETOMCLIST, this, empty); CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_GETCURLOG, this, empty); CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_GETLOGFILES, this, empty); CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_SHUTDOWN, this, empty); } catch (Exception ex) { Logger.Instance().SendLog("AdapterController", ex.ToString()); throw ex; } }
/// <summary> /// Used by method <b>Calculate</b> on derived classes to perform the commission calculation for amount based sell exclusive orders. /// </summary> /// <param name="amount">The amount for which to calculate commission.</param> /// <param name="client">The order for which to calculate commission.</param> /// <returns>The value of the commission.</returns> protected Money calculateForwards(Money nettAmount, ICommClient client) { if (!(client.Type != CommClientType.Transaction && client.Side == Side.Sell && client.IsValueInclComm == false)) throw new ApplicationException("There is a bug in the program flow in the fees module."); Money result = new Money(0m, CommCurrency); Money comAmount = getCommAmount(nettAmount); foreach (CommCalcLineAmountBased line in CommLines) { if (line.Envelops(comAmount)) { result = line.CalculateExtra(comAmount); SetCommissionInfoOnOrder(client, string.Format("Flat (forwards) -> Amount ({0}) {1} -> use {2}.", comAmount.ToString(), line.DisplayRange, line.LineDistinctives)); break; } } return addFixMinMax(result, client); }