public void Init(ConnectionType connType, int port) { Debuger.Log("connType:{0}, port:{1}", connType, port); if (connType == ConnectionType.TCP) { m_gateway = new TcpGateway(port, this); } else if (connType == ConnectionType.UDP) { m_gateway = new UdpGateway(port, this); } else if (connType == ConnectionType.RUDP) { m_gateway = new KcpGateway(port, this); } else { throw new ArgumentException("未实现该连接类型:" + connType); } onDisconnected = new Signal <ISession>(); m_rpc = new RPCManager(); m_rpc.Init(); }
public DiscordClientConfiguration( IApiClient apiClient, IGateway gateway, IExtendedCacheClient cache) { ApiClient = apiClient; Gateway = gateway; CacheClient = cache; }
public Tuple <IGateway, IBulb, AnswerType> ReceivedPacket(string ipAddress, byte[] data) { var answerType = AnswerType.None; IGateway gateway = null; IBulb bulb = null; try { var packet = PacketFactory.GetAnswer(data); if (packet == null) { return(Tuple.Create((IGateway)null, (IBulb)null, AnswerType.None)); } answerType = packet.Type; gateway = HandleGatewayPacket(packet.GatewayMac, ipAddress); bulb = HandleBulbPacket(gateway, packet); HandleWifiStatePacket(bulb, packet); HandleBulbGroupsPacket(bulb, packet); HandleGroupNamePacket(packet); HandleAccessPoint(packet); } catch (Exception e) { Debug.WriteLine("ReceivedPacket: {0}", e.Message); Debug.WriteLine(e.StackTrace); } return(Tuple.Create(gateway, bulb, answerType)); }
internal JObject(IGateway gateway, string javaClassName, IntPtr javaClass, IntPtr javaObject) { this.Gateway = gateway; this.JavaClassName = javaClassName; this.JavaClass = javaClass; this.JavaObject = javaObject; }
public RefundResponse Refund(PayRequest payRequest) { _gateway = _gateways.GetByStoreId <AlipayGateway>(payRequest.GetStoreId()); var queryModel = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(payRequest.BizContent, new { out_trade_no = "", trade_no = "", refund_amount = 0, refund_reason = "", out_refund_no = "" }); // 记录支付日志 //var content = JsonConvert.SerializeObject(payRequest); //var payHistory = new PaymentHistory(); //payHistory.LogAlipayBarcodeRequestPay(queryModel.out_trade_no, queryModel.total_amount.ToString(), "saleorder", content); //_db.Insert(payHistory); //_db.SaveChange(); var request = new RefundRequest(); request.AddGatewayData(new RefundModel() { OutTradeNo = queryModel.out_trade_no, TradeNo = queryModel.trade_no, RefundAmount = queryModel.refund_amount, RefundReason = queryModel.refund_reason, OutRefundNo = queryModel.out_refund_no }); var response = _gateway.Execute(request); return(response); }
public DefaultGatewayApiClient( IOptions <DefaultGatewayApiClientConfiguration> options, ILogger logger, Token token, IGatewayRateLimiter rateLimiter, IGatewayHeartbeater heartbeater, IGateway gateway, IJsonSerializer serializer) { var configuration = options.Value; Intents = configuration.Intents; LargeThreshold = configuration.LargeThreshold; Id = configuration.Id; Presence = configuration.Presence; Logger = logger; Token = token; RateLimiter = rateLimiter; RateLimiter.Bind(this); Heartbeater = heartbeater; Heartbeater.Bind(this); Gateway = gateway; Gateway.Bind(this); Serializer = serializer; _random = new Random(); }
public CallersFactory(IGateway gateway) { this.Gateway = gateway; this.FieldCallers = new List <object>(); this.MethodCallers = new List <object>(); JNIEnvironment env = this.Gateway.Runtime.JavaEnvironment.JNIEnv; this.FieldCallers.Add(new FieldCaller <IntPtr>(env.GetObjectField, env.GetStaticObjectField)); this.FieldCallers.Add(new FieldCaller <bool>(env.GetBooleanField, env.GetStaticBooleanField)); this.FieldCallers.Add(new FieldCaller <byte>(env.GetByteField, env.GetStaticByteField)); this.FieldCallers.Add(new FieldCaller <ushort>(env.GetCharField, env.GetStaticCharField)); this.FieldCallers.Add(new FieldCaller <short>(env.GetShortField, env.GetStaticShortField)); this.FieldCallers.Add(new FieldCaller <int>(env.GetIntField, env.GetStaticIntField)); this.FieldCallers.Add(new FieldCaller <long>(env.GetLongField, env.GetStaticLongField)); this.FieldCallers.Add(new FieldCaller <float>(env.GetFloatField, env.GetStaticFloatField)); this.FieldCallers.Add(new FieldCaller <double>(env.GetDoubleField, env.GetStaticDoubleField)); this.MethodCallers.Add(new MethodCaller <IntPtr>(env.CallObjectMethod, env.CallStaticObjectMethod)); this.MethodCallers.Add(new MethodCaller <bool>(env.CallBooleanMethod, env.CallStaticBooleanMethod)); this.MethodCallers.Add(new MethodCaller <byte>(env.CallByteMethod, env.CallStaticByteMethod)); this.MethodCallers.Add(new MethodCaller <ushort>(env.CallCharMethod, env.CallStaticCharMethod)); this.MethodCallers.Add(new MethodCaller <short>(env.CallShortMethod, env.CallStaticShortMethod)); this.MethodCallers.Add(new MethodCaller <int>(env.CallIntMethod, env.CallStaticIntMethod)); this.MethodCallers.Add(new MethodCaller <long>(env.CallLongMethod, env.CallStaticLongMethod)); this.MethodCallers.Add(new MethodCaller <float>(env.CallFloatMethod, env.CallStaticFloatMethod)); this.MethodCallers.Add(new MethodCaller <double>(env.CallDoubleMethod, env.CallStaticDoubleMethod)); }
public ApplicationCommandService(IGateway gateway, ILogger <ApplicationCommandService> logger, RestApi api, IOptions <DiscordSettings> settings) { _gateway = gateway ?? throw new ArgumentNullException(nameof(gateway)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _api = api ?? throw new ArgumentNullException(nameof(api)); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); }
/// Perform a $1 authorization... the amount is randomized because some gateways will reject identical, subsequent amounts /// within a short period of time. private void VerifyCardWithAuth(ModelStateDictionary modelState, IGateway gateway, int peopleId) { if (Type != PaymentType.CreditCard) { return; } if (CreditCard.StartsWith("X")) { return; } var random = new Random(); var dollarAmt = (decimal)random.Next(100, 199) / 100; var transactionResponse = gateway.AuthCreditCard(peopleId, dollarAmt, CreditCard, DbUtil.NormalizeExpires(Expires).ToString2("MMyy"), "One Time Auth", 0, CVV, string.Empty, First, Last, Address, Address2, City, State, Country, Zip, Phone); if (!transactionResponse.Approved) { modelState.AddModelError("form", transactionResponse.Message); } // if we got this far that means the auth worked so now let's do a void for that auth. var voidResponse = gateway.VoidCreditCardTransaction(transactionResponse.TransactionId); }
public CustomerRegistrationService( ICustomerRepository repository, IGateway gateway) { _repository = repository; _gateway = gateway; }
private TransactionResponse PayWithCreditCard(IGateway gateway, int?peopleId, Transaction transaction) { return(gateway.PayWithCreditCard(peopleId ?? 0, AmtToPay ?? 0, CreditCard, DbUtil.NormalizeExpires(Expires).ToString2("MMyy"), Description, transaction.Id, CVV, Email, First, Last, Address, Address2, City, State, Country, Zip, Phone)); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IGateway gateway) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } bool anyOrigin = false; bool.TryParse(Configuration["Configuration:AnyOrigin"], out anyOrigin); app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => anyOrigin) // allow any origin .AllowCredentials()); // allow credentials Router router = new Router(Configuration["Configuration:Routes"], gateway); app.Run(async(context) => { var content = await router.RouteRequest(context.Request); context.Response.StatusCode = (int)content.StatusCode; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(content.Body); }); }
private static TransactionResponse PayWithCreditCard(IGateway gateway, PaymentForm paymentForm, int?peopleId, Transaction transaction) { return(gateway.PayWithCreditCard(peopleId ?? 0, paymentForm.AmtToPay ?? 0, paymentForm.CreditCard, DbUtil.NormalizeExpires(paymentForm.Expires).ToString2("MMyy"), paymentForm.Description, transaction.Id, paymentForm.CVV, paymentForm.Email, paymentForm.First, paymentForm.Last, paymentForm.Address, paymentForm.Address2, paymentForm.City, paymentForm.State, paymentForm.Country, paymentForm.Zip, paymentForm.Phone)); }
/// <summary> /// Perform a $1 authorization... the amount is randomized because some gateways will reject identical, subsequent amounts /// within a short period of time. /// </summary> private bool VerifyCardWithAuth(IGateway gateway, PaymentForm pf, int peopleId) { if (pf.Type != PaymentType.CreditCard) { return(true); } if (pf.CreditCard.StartsWith("X")) { return(true); } var random = new Random(); var dollarAmt = (decimal)random.Next(100, 199) / 100; var transactionResponse = gateway.AuthCreditCard(peopleId, dollarAmt, pf.CreditCard, DbUtil.NormalizeExpires(pf.Expires).ToString2("MMyy"), "One Time Auth", 0, pf.CVV, string.Empty, pf.First, pf.Last, pf.Address, pf.Address2, pf.City, pf.State, pf.Country, pf.Zip, pf.Phone); if (!transactionResponse.Approved) { ModelState.AddModelError("form", transactionResponse.Message); return(false); } // if we got this far that means the auth worked so now let's do a void for that auth. var voidResponse = gateway.VoidCreditCardTransaction(transactionResponse.TransactionId); return(true); }
private static void initThrift(IGateway gw) { G.DefaultGateway = gw; var cp = new ClientProcessor(gw); var t_processor = new Client.GW.Processor(cp); var transport = new Thrift.Transport.TServerSocket(6325, 100000, true); System.Threading.ThreadPool.SetMinThreads(1, 0); var tps = new Thrift.Server.TThreadPoolServer(t_processor, transport); Task.Run(() => { Console.WriteLine($"{gw.GetPrimaryKeyString()}:Task: thrift started"); System.Threading.ThreadPool.GetMaxThreads(out var wt, out var cpt); Console.WriteLine($"ThreadPool maxwt:{wt} maxcpt:{cpt}"); tps.Serve(); }); Task.Run(() => {//心跳检测,如果客户端长时间没有发起thrift请求,那么回收token,类似udp判断玩家是否断线 while (true) { cp.CheckHeartbeat(); Thread.Sleep(1000); } }); }
public BarcodePayResponse BarcodePay(PayRequest payRequest) { _gateway = _gateways.GetByStoreId <WechatpayGateway>(payRequest.GetStoreId()); var queryModel = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(payRequest.BizContent, new { body = "", total_amount = 0, out_trade_no = "", auth_code = "" }); // 记录支付日志 var content = JsonConvert.SerializeObject(payRequest); var payHistory = new PaymentHistory(); payHistory.LogWechatBarcodeRequestPay(queryModel.out_trade_no, queryModel.total_amount.ToString(), "saleorder", content); _db.Insert(payHistory); _db.SaveChange(); var request = new BarcodePayRequest(); request.AddGatewayData(new BarcodePayModel() { Body = queryModel.body, TotalAmount = queryModel.total_amount, OutTradeNo = queryModel.out_trade_no, AuthCode = queryModel.auth_code }); request.PaySucceed += BarcodePay_PaySucceed; request.PayFailed += BarcodePay_PayFaild; var response = _gateway.Execute(request); return(response); }
/// <summary> /// Loads Java Environment and Virtual Machine. /// </summary> /// <param name="path"> On Windows: Path to jvm.dll file. </param> /// <param name="parameters"> Optional arguments for virtual machine. </param> /// <param name="jniVersion"> Correct JNI version. See: <see cref="JNIConstants"/>. </param> /// <param name="attachToExistingJVM"></param> public void Load(string path, IDictionary <string, string> parameters = null, int jniVersion = JNIConstants.JNI_VERSION_1_8, bool attachToExistingJVM = false) { if (string.IsNullOrEmpty(path) || !File.Exists(path)) { throw new ArgumentException("You must specify the correct location of JVM library.", "path"); } // Set the working directory to directory with JVM library. Directory.SetCurrentDirectory(Path.GetDirectoryName(path)); var jvmInitArgs = new JavaVMInitArgs { version = jniVersion, ignoreUnrecognized = JavaConverter.ToByte(true) }; if (parameters != null && parameters.Count > 0) { jvmInitArgs.nOptions = parameters.Count; var options = new List <JavaVMOption>(); foreach (var kvp in parameters) { options.Add(new JavaVMOption { optionString = Marshal.StringToHGlobalAnsi($"{ kvp.Key }={ kvp.Value }") }); } JavaVMOption[] parsedOptions = options.ToArray(); fixed(JavaVMOption *a = &parsedOptions[0]) { jvmInitArgs.options = a; } } if (!attachToExistingJVM) { IntPtr environment; IntPtr javaVM; int result = JNINativeImports.JNI_CreateJavaVM(out javaVM, out environment, &jvmInitArgs); if (result != JNIConstants.JNI_OK) { throw new InvalidOperationException($"Error when creating Java Virtual Machine. [JNI_CreateJavaVM -> Return code: { result }]."); } this.JavaEnvironment = new JavaEnvironment(environment); this.JavaEnvironment.VirtualMachine = new JavaVM(javaVM); } else { this.AttachToExistingJVM(jvmInitArgs); } this.Gateway = new GatewayManager(this); }
public GatewayBasedManager(string instance, Dictionary <string, string> config) { Instance = instance; Gateway = GetGateway(instance, config); Gateway.OnDisconnected += delegate(IGateway sender) { OnStop?.Invoke(this); }; Gateway.OnError += delegate(IGateway sender) { OnError?.Invoke(this); }; Gateway.OnReady += delegate(IGateway sender) { OnReady?.Invoke(this); }; }
public CustomerRegistrationServiceTests() { _repo = Substitute.For <ICustomerRepository>(); _gateway = Substitute.For <IGateway>(); _repo.RegisterCustomerTwo(Arg.Any <string>()).Returns(Result.Ok(new Customer())); _gateway.SendMailTwo(Arg.Any <string>()).Returns(Result.Ok(new Customer())); }
public Router(string routeConfigFilePath, IGateway gateway) { this.gateway = gateway; dynamic router = Json.LoadFromFile <dynamic>(routeConfigFilePath); Routes = Json.Deserialize <List <Route> >(Convert.ToString(router.routes)); AuthenticationService = Json.Deserialize <Authentication>(Convert.ToString(router.authenticationService)); }
public Client(IGateway gateway, int bufferSize) { _gateways = new IGateway[] { gateway }; _bufferSize = bufferSize; }
public Payment(IGateway gateway, IHttpClient httpClient, IJsonConvert jsonConvert) { this.gateway = gateway; this.httpClient = httpClient; this.jsonConvert = jsonConvert; gateway.httpClient = httpClient; gateway.jsonConvert = jsonConvert; }
public static string GetName(this IGateway gateway) { if (gateway == null) { throw new ArgumentNullException(nameof(gateway)); } return(GetNameByType(gateway.GetType())); }
public CivicaService(IGateway gateway, IQueryBuilder queryBuilder, ISessionProvider sessionProvider, ICacheProvider cacheProvider, IXmlParser xmlParser) { _gateway = gateway; _queryBuilder = queryBuilder; _sessionProvider = sessionProvider; _cacheProvider = cacheProvider; _xmlParser = xmlParser; }
public ContentContainer(IGateway gateway) { this._gateway = gateway as Gateway; if (this._gateway == null) { throw new ArgumentException("Wrong Gateway"); } Configure(); }
private void RegisterThingsInitHandler(IGateway gateway, GatewayConfigurationPackage gatewayConfigurationPackage) { var initThingsHandler = _messageHub .Handle <ThingStateChangedMessage>() .Where(msg => gateway.Id.Equals(msg.Id) && msg.NewState.IsInitialized()) .Once() .Register(msg => InitThingsAsync(gatewayConfigurationPackage)); _gatewayInitializedHandlers[gatewayConfigurationPackage] = initThingsHandler; }
void UOSApplication.Init(IGateway gateway, uOSSettings settings) { this.gateway = (UnityGateway)gateway; this.gateway.Register( WorldMapController.main, gateway.currentDevice, GlobalPositionDriver.DRIVER_ID, null, GlobalPositionDriver.EVENT_POS_CHANGE); WorldMapController.main.Init(gateway, settings); }
public void array_can_be_coerced_to_concrete_list() { var array = new IGateway[] {new StubbedGateway(), new StubbedGateway()}; var constant = ConcreteType.SourceFor(ConcreteType.ConstructorArgument, "SomeProp", typeof (List<IGateway>), array) .ShouldBeOfType<Constant>(); constant.ReturnedType.ShouldBe(typeof (List<IGateway>)); constant.Value.As<List<IGateway>>() .ShouldHaveTheSameElementsAs(array); }
public static void SetAccessPoint(this ILifxNetwork network, IGateway gateway, IAccessPoint accessPoint, string password) { var n = (LifxNetwork)network; var command = (SetAccessPoint)PacketFactory.GetCommand(CommandType.SetAccessPoint); var ap = (AccessPoint)accessPoint; command.Init(ap.Packet, password); n.SendCommand(gateway, command); n.SendCommand(gateway, PacketFactory.GetCommand(CommandType.GetWifiState)); }
public DiscordClient( IApiClient apiClient, IGateway gateway, ICacheHandler cacheHandler, IDiscordEvents eventHandler) { ApiClient = apiClient; Gateway = gateway; Events = eventHandler; this.cacheHandler = cacheHandler; }
public void array_can_be_coerced_to_concrete_list() { var array = new IGateway[] { new StubbedGateway(), new StubbedGateway() }; var constant = ConcreteType.SourceFor(ConcreteType.ConstructorArgument, "SomeProp", typeof(List <IGateway>), array) .ShouldBeOfType <Constant>(); constant.ReturnedType.ShouldBe(typeof(List <IGateway>)); constant.Value.As <List <IGateway> >() .ShouldHaveTheSameElementsAs(array); }
public void array_can_be_coerced_to_enumerable() { var list = new IGateway[] { new StubbedGateway(), new StubbedGateway() }; var constant = ConcreteType.SourceFor(new Policies(PluginGraph.CreateRoot()), ConcreteType.ConstructorArgument, "SomeProp", typeof(List<IGateway>), list) .ShouldBeOfType<Constant>(); constant.ReturnedType.ShouldBe(typeof(List<IGateway>)); constant.Value.As<List<IGateway>>() .ShouldHaveTheSameElementsAs(list); }
public PayrollAdapter(IGateway gateway) { this.gateway = gateway; }
public void Run() { _gateway = GatewayFactory.createGateway(); // register the generic message listener with the gateway _gateway.registerGenericMessageListener(this); // register the status message listener with the gateway _gateway.registerStatusMessageListener(this); // attempt to login with the local login properties Console.WriteLine("Logging in..."); var loginProperties = new FXCMLoginProperties(UserName, Password, Terminal, Server); // disable the streaming rates (default automatic subscriptions) loginProperties.addProperty(IConnectionManager.__Fields.MSG_FLAGS, IFixDefs.__Fields.CHANNEL_MARKET_DATA.ToString()); _gateway.login(loginProperties); Console.WriteLine("Logged in.\n"); // get instrument list Console.WriteLine("Requesting trading session status..."); lock (_locker) { _currentRequest = _gateway.requestTradingSessionStatus(); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestTradingSessionStatusEvent.WaitOne(); Console.WriteLine("Instruments: {0}\n", _securities.Count); foreach (var pair in _securities) { var security = pair.Value; Console.WriteLine(security.getSymbol() + " " + security.getCurrency() + " " + security.getFXCMSubscriptionStatus() + " " + security.getRoundLot() + " " + security.getContractMultiplier() + " " + security.getFXCMMinQuantity() + " " + security.getFXCMMaxQuantity() + " " + security.getFXCMSymPointSize() + " " + security.getFactor() + " " + security.getFXCMSymPrecision() + " " + security.getProduct() + " " + security.getFXCMProductID() + " " + (security.getFXCMProductID() == IFixValueDefs.__Fields.FXCMPRODUCTID_FOREX ? "Forex" : "CFD")); } Console.WriteLine(); // get account list Console.WriteLine("Requesting account list..."); lock (_locker) { _currentRequest = _gateway.requestAccounts(); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestAccountListEvent.WaitOne(); Console.WriteLine("Accounts: {0}\n", _accounts.Count); // use first account var accountId = _accounts.Keys.First(); // we are unable to continue if Hedging enabled if (_accounts[accountId].getParties().getFXCMPositionMaintenance() != "N") throw new NotSupportedException("The Lean engine does not support accounts with Hedging enabled. Please contact FXCM support to disable Hedging and try again."); // get open order list Console.WriteLine("Requesting open order list..."); lock (_locker) { _currentRequest = _gateway.requestOpenOrders(); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Open orders: {0}\n", _orders.Keys.Count); // cancel all open orders if (_orders.Keys.Count > 0) { Console.WriteLine("Cancelling open orders..."); foreach (var order in _orders.Values.ToList()) { Console.WriteLine("Cancelling order {0}...", order.getOrderID()); var request = MessageGenerator.generateOrderCancelRequest("", order.getOrderID(), order.getSide(), order.getAccount()); lock (_locker) { _currentRequest = _gateway.sendMessage(request); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Order {0} cancelled.", order.getOrderID()); } _orders.Clear(); Console.WriteLine("Open orders cancelled.\n"); } // get open position list Console.WriteLine("Requesting open position list..."); lock (_locker) { _currentRequest = _gateway.requestOpenPositions(); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestPositionListEvent.WaitOne(); Console.WriteLine("Open position list complete.\n"); // get closed position list Console.WriteLine("Requesting closed position list..."); lock (_currentRequest) { _currentRequest = _gateway.requestClosedPositions(); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestPositionListEvent.WaitOne(); Console.WriteLine("Closed position list complete.\n"); // get current quotes for the instrument if (_securities.ContainsKey(Symbol)) { Console.WriteLine("Requesting market data for " + Symbol + "..."); var request = new MarketDataRequest(); request.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL); request.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT); request.addRelatedSymbol(_securities[Symbol]); lock (_locker) { _currentRequest = _gateway.sendMessage(request); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestMarketDataEvent.WaitOne(); Console.WriteLine(Symbol + " - Bid: {0} Ask: {1}\n", _rates[Symbol].getBidClose(), _rates[Symbol].getAskClose()); } // submit limit order Console.WriteLine("Submitting limit order..."); var limitOrderRequest = MessageGenerator.generateOpenOrder(0.7, accountId, 10000, SideFactory.BUY, Symbol, ""); limitOrderRequest.setOrdType(OrdTypeFactory.LIMIT); limitOrderRequest.setTimeInForce(TimeInForceFactory.GOOD_TILL_CANCEL); lock (_locker) { _currentRequest = _gateway.sendMessage(limitOrderRequest); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Limit order submitted.\n"); var limitOrder = _orderRequests[_currentRequest]; // update limit order Console.WriteLine("Updating limit order..."); var orderReplaceRequest = MessageGenerator.generateOrderReplaceRequest("", limitOrder.getOrderID(), limitOrder.getSide(), limitOrder.getOrdType(), 0.8, limitOrder.getAccount()); lock (_locker) { _currentRequest = _gateway.sendMessage(orderReplaceRequest); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Limit order updated.\n"); // cancel limit order Console.WriteLine("Cancelling limit order..."); var orderCancelRequest = MessageGenerator.generateOrderCancelRequest("", limitOrder.getOrderID(), limitOrder.getSide(), limitOrder.getAccount()); lock (_locker) { _currentRequest = _gateway.sendMessage(orderCancelRequest); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Limit order cancelled.\n"); // submit stop market order Console.WriteLine("Submitting stop market order..."); var stopMarketOrderRequest = MessageGenerator.generateOpenOrder(0.7, accountId, 10000, SideFactory.SELL, Symbol, ""); stopMarketOrderRequest.setOrdType(OrdTypeFactory.STOP); stopMarketOrderRequest.setTimeInForce(TimeInForceFactory.GOOD_TILL_CANCEL); lock (_locker) { _currentRequest = _gateway.sendMessage(stopMarketOrderRequest); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Stop market order submitted.\n"); var stopMarketOrder = _orderRequests[_currentRequest]; // cancel stop market order Console.WriteLine("Cancelling stop market order..."); orderCancelRequest = MessageGenerator.generateOrderCancelRequest("", stopMarketOrder.getOrderID(), stopMarketOrder.getSide(), stopMarketOrder.getAccount()); lock (_locker) { _currentRequest = _gateway.sendMessage(orderCancelRequest); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Stop market order cancelled.\n"); // submit stop limit order Console.WriteLine("Submitting stop limit order..."); var stopLimitOrderRequest = MessageGenerator.generateOpenOrder(0.7, accountId, 10000, SideFactory.SELL, Symbol, ""); stopLimitOrderRequest.setOrdType(OrdTypeFactory.STOP_LIMIT); stopLimitOrderRequest.setStopPx(0.695); stopLimitOrderRequest.setTimeInForce(TimeInForceFactory.GOOD_TILL_CANCEL); lock (_locker) { _currentRequest = _gateway.sendMessage(stopLimitOrderRequest); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Stop limit order submitted.\n"); var stopLimitOrder = _orderRequests[_currentRequest]; // cancel stop limit order Console.WriteLine("Cancelling stop limit order..."); orderCancelRequest = MessageGenerator.generateOrderCancelRequest("", stopLimitOrder.getOrderID(), stopLimitOrder.getSide(), stopLimitOrder.getAccount()); lock (_locker) { _currentRequest = _gateway.sendMessage(orderCancelRequest); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Stop limit order cancelled.\n"); // submit market order (buy) Console.WriteLine("Submitting buy market order..."); var buyOrder = MessageGenerator.generateMarketOrder(accountId, 10000, SideFactory.BUY, Symbol, ""); lock (_locker) { _currentRequest = _gateway.sendMessage(buyOrder); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Buy market order submitted.\n"); // submit market order (sell) Console.WriteLine("Submitting sell market order..."); var sellOrder = MessageGenerator.generateMarketOrder(accountId, 10000, SideFactory.SELL, Symbol, ""); lock (_locker) { _currentRequest = _gateway.sendMessage(sellOrder); Console.WriteLine("\tRequestId = {0}\n", _currentRequest); } _requestOrderEvent.WaitOne(); Console.WriteLine("Sell market order submitted.\n"); Console.WriteLine(); Console.WriteLine("Press Return to Logout and exit.\n"); Console.ReadKey(); // log out Console.WriteLine("Logging out..."); _gateway.logout(); Console.WriteLine("Logged out."); // remove the generic message listener, stop listening to updates _gateway.removeGenericMessageListener(this); // remove the status message listener, stop listening to status changes _gateway.removeStatusMessageListener(this); }
public void Init(IGateway gateway, uOSSettings settings, string instanceId) { Debug.Log("Initializing Avatar Guide Driver..."); }
public DecoratedGateway(IGateway innerGateway) { _innerGateway = innerGateway; }
public void Init(IGateway gateway, uOSSettings settings) { this.gateway = (UnityGateway) gateway; }
public ClassWithMultipleConstructors(IGateway gateway, IService service, IWidget widget) { CtorUsed = "Three Args"; }
public GuyWithCtorAndArgs(IGateway gateway, Rule rule) { }
public GuyWithOnlyCtor(IGateway gateway, Rule rule) { }
public ExpenseAdapter(IGateway gateway) { this.gateway = gateway; }
/// <summary> /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC). /// </summary> /// <param name="symbol">Symbol for the data we're looking for.</param> /// <param name="resolution">Resolution of the data request</param> /// <param name="startUtc">Start time of the data in UTC</param> /// <param name="endUtc">End time of the data in UTC</param> /// <returns>Enumerable of base data for this symbol</returns> public IEnumerable<BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc) { if (!_symbolMapper.IsKnownLeanSymbol(symbol)) throw new ArgumentException("Invalid symbol requested: " + symbol.Value); if (resolution == Resolution.Tick) throw new NotSupportedException("Resolution not available: " + resolution); if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd) throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType); if (endUtc < startUtc) throw new ArgumentException("The end date must be greater or equal than the start date."); Console.WriteLine("Logging in..."); // create the gateway _gateway = GatewayFactory.createGateway(); // register the message listeners with the gateway _gateway.registerGenericMessageListener(this); _gateway.registerStatusMessageListener(this); // create local login properties var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server); // log in _gateway.login(loginProperties); // initialize session RequestTradingSessionStatus(); Console.WriteLine("Downloading data from {0} to {1}...", startUtc.ToShortDateString(), endUtc.ToShortDateString()); // download bars var totalBars = new List<TradeBar>(); // calculate the maximum time span for one request (using 10-second bars) const int maxBarsPerRequest = 300; var timeSpanPerRequest = TimeSpan.FromSeconds(maxBarsPerRequest * 10); var start = startUtc; var end = startUtc + timeSpanPerRequest; // request loop while (start < endUtc.AddDays(1)) { _currentBars.Clear(); var mdr = new MarketDataRequest(); mdr.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT); mdr.setResponseFormat(IFixMsgTypeDefs.__Fields.MSGTYPE_FXCMRESPONSE); mdr.setFXCMTimingInterval(FXCMTimingIntervalFactory.SEC10); mdr.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL); mdr.setFXCMStartDate(new UTCDate(ToJavaDateUtc(start))); mdr.setFXCMStartTime(new UTCTimeOnly(ToJavaDateUtc(start))); mdr.setFXCMEndDate(new UTCDate(ToJavaDateUtc(end))); mdr.setFXCMEndTime(new UTCTimeOnly(ToJavaDateUtc(end))); mdr.addRelatedSymbol(_fxcmInstruments[_symbolMapper.GetBrokerageSymbol(symbol)]); AutoResetEvent autoResetEvent; lock (_locker) { _currentRequest = _gateway.sendMessage(mdr); autoResetEvent = new AutoResetEvent(false); _mapRequestsToAutoResetEvents[_currentRequest] = autoResetEvent; } if (!autoResetEvent.WaitOne(1000)) { // no response, continue loop start = end.AddSeconds(10); // if saturday, fast-forward to sunday if (start.DayOfWeek == DayOfWeek.Saturday) start = start.AddDays(1); end = start + timeSpanPerRequest; continue; } var lastBarTime = _currentBars[_currentBars.Count - 1].Time; if (lastBarTime < start) { // no more data available, exit loop break; } // add bars received totalBars.AddRange(_currentBars.Where(x => x.Time.Date <= endUtc.Date)); // calculate time span for next request start = lastBarTime.AddSeconds(10); end = start + timeSpanPerRequest; if (start >= DateTime.UtcNow) { // data in the future not available, exit loop break; } } Console.WriteLine("Logging out..."); // log out _gateway.logout(); // remove the message listeners _gateway.removeGenericMessageListener(this); _gateway.removeStatusMessageListener(this); switch (resolution) { case Resolution.Second: foreach (var bar in totalBars) yield return bar; break; case Resolution.Minute: case Resolution.Hour: case Resolution.Daily: foreach (var bar in AggregateBars(symbol, totalBars, resolution.ToTimeSpan())) yield return bar; break; } }
private TransactionResponse PayWithCreditCard(IGateway gateway, int? peopleId, Transaction transaction) { return gateway.PayWithCreditCard(peopleId ?? 0, AmtToPay ?? 0, CreditCard, DbUtil.NormalizeExpires(Expires).ToString2("MMyy"), Description, transaction.Id, CVV, Email, First, Last, Address, Address2, City, State, Country, Zip, Phone); }
public void Init(IGateway gateway, uOSSettings settings, string instanceId) { this.gateway = (UnityGateway)gateway; this.logger = this.gateway.logger; }
/// <summary> /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC). /// </summary> /// <param name="symbol">Symbol for the data we're looking for.</param> /// <param name="resolution">Resolution of the data request</param> /// <param name="startUtc">Start time of the data in UTC</param> /// <param name="endUtc">End time of the data in UTC</param> /// <returns>Enumerable of base data for this symbol</returns> public IEnumerable<BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc) { if (!_symbolMapper.IsKnownLeanSymbol(symbol)) throw new ArgumentException("Invalid symbol requested: " + symbol.Value); if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd) throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType); if (endUtc <= startUtc) throw new ArgumentException("The end date must be greater than the start date."); Console.WriteLine("Logging in..."); // create the gateway _gateway = GatewayFactory.createGateway(); // register the message listeners with the gateway _gateway.registerGenericMessageListener(this); _gateway.registerStatusMessageListener(this); // create local login properties var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server); // log in _gateway.login(loginProperties); // initialize session RequestTradingSessionStatus(); Console.WriteLine("Downloading {0} data from {1} to {2}...", resolution, startUtc.ToString("yyyyMMdd HH:mm:ss"), endUtc.ToString("yyyyMMdd HH:mm:ss")); // Find best FXCM parameters var interval = FxcmBrokerage.ToFxcmInterval(resolution); var totalTicks = (endUtc - startUtc).Ticks; // download data var totalBaseData = new List<BaseData>(); var end = endUtc; do // { //show progress progressBar(Math.Abs((end - endUtc).Ticks), totalTicks, Console.WindowWidth / 2,'█'); _currentBaseData.Clear(); var mdr = new MarketDataRequest(); mdr.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT); mdr.setResponseFormat(IFixMsgTypeDefs.__Fields.MSGTYPE_FXCMRESPONSE); mdr.setFXCMTimingInterval(interval); mdr.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL); mdr.setFXCMStartDate(new UTCDate(FxcmBrokerage.ToJavaDateUtc(startUtc))); mdr.setFXCMStartTime(new UTCTimeOnly(FxcmBrokerage.ToJavaDateUtc(startUtc))); mdr.setFXCMEndDate(new UTCDate(FxcmBrokerage.ToJavaDateUtc(end))); mdr.setFXCMEndTime(new UTCTimeOnly(FxcmBrokerage.ToJavaDateUtc(end))); mdr.addRelatedSymbol(_fxcmInstruments[_symbolMapper.GetBrokerageSymbol(symbol)]); AutoResetEvent autoResetEvent; lock (_locker) { _currentRequest = _gateway.sendMessage(mdr); autoResetEvent = new AutoResetEvent(false); _mapRequestsToAutoResetEvents[_currentRequest] = autoResetEvent; } if (!autoResetEvent.WaitOne(1000 * 5)) { // no response, exit break; } // Add data totalBaseData.InsertRange(0, _currentBaseData.Where(x => x.Time.Date >= startUtc.Date)); if (end != _currentBaseData[0].Time) { // new end date = first datapoint date. end = _currentBaseData[0].Time; } else { break; } } while (end > startUtc); Console.WriteLine("\nLogging out..."); // log out _gateway.logout(); // remove the message listeners _gateway.removeGenericMessageListener(this); _gateway.removeStatusMessageListener(this); return totalBaseData.ToList(); }
public ClassWithMultipleConstructors(IGateway gateway, IService service) { CtorUsed = "Two Args"; }
public LifecycleTarget(IGateway gateway) { _gateway = gateway; }
public ClassWithMultipleConstructors(IGateway gateway) { CtorUsed = "One Arg"; }
public UsesGateways(IGateway[] gateways) { _gateways = gateways; }
public void Init(IGateway gateway, uOSSettings settings, string instanceId) { this.gateway = (UnityGateway)gateway; this.instanceId = instanceId; pins.Clear(); driverListeners.Clear(); gateway.Register(this, null, DRIVER_NAME, null, UPDATE_EVENT_NAME); }
public void Init(IGateway gateway, uOSSettings settings) { }
/// Perform a $1 authorization... the amount is randomized because some gateways will reject identical, subsequent amounts /// within a short period of time. private void VerifyCardWithAuth(ModelStateDictionary modelState, IGateway gateway, int peopleId) { if (Type != PaymentType.CreditCard) return; if (CreditCard.StartsWith("X")) return; var random = new Random(); var dollarAmt = (decimal) random.Next(100, 199)/100; var transactionResponse = gateway.AuthCreditCard(peopleId, dollarAmt, CreditCard, DbUtil.NormalizeExpires(Expires).ToString2("MMyy"), "One Time Auth", 0, CVV, string.Empty, First, Last, Address, Address2, City, State, Country, Zip, Phone); if (!transactionResponse.Approved) modelState.AddModelError("form", transactionResponse.Message); // if we got this far that means the auth worked so now let's do a void for that auth. var voidResponse = gateway.VoidCreditCardTransaction(transactionResponse.TransactionId); }
private TransactionResponse PayWithCheck(IGateway gw, int? pid, Transaction ti) { return gw.PayWithCheck(pid ?? 0, AmtToPay ?? 0, Routing, Account, Description, ti.Id, Email, First, MiddleInitial, Last, Suffix, Address, Address2, City, State, Country, Zip, Phone); }
public GuyWhoUsesGateway(IGateway gateway) { _gateway = gateway; }
public FilledTarget(IGateway gateway, Rule rule) { _gateway = gateway; _rule = rule; }
public CycleModelService(IGateway gateway) { _gateway = gateway; AutoMapper.Mapper.CreateMap<Cycle, CycleModel>(); }
public GatewayArrayUser(IGateway[] gateways) { _gateways = gateways; }