/// <summary> /// установить соединение сервером Oanda /// </summary> public void Connect(string id, string token, bool isJuniorConnect) { if (isJuniorConnect) { _environment = EEnvironment.Practice; } else { _environment = EEnvironment.Trade; } if (string.IsNullOrEmpty(token)) { SendLogMessage(OsLocalization.Market.Message77 + " https://www.oanda.com/account/tpa/personal_token", LogMessageType.Error); return; } Credentials.SetCredentials(_environment, token, id); if (Credentials.GetDefaultCredentials().HasServer(EServer.Account)) { _isConnected = true; if (ConnectionSucsess != null) { ConnectionSucsess(); } } }
/// <summary> /// установить соединение сервером Oanda /// </summary> public void Connect(string id, string token, bool isJuniorConnect) { if (isJuniorConnect) { _environment = EEnvironment.Practice; } else { _environment = EEnvironment.Trade; } if (string.IsNullOrEmpty(token)) { SendLogMessage("Токен не может быть пустым! Получите уникальный ключ доступа по адресу: https://www.oanda.com/account/tpa/personal_token", LogMessageType.Error); return; } Credentials.SetCredentials(_environment, token, id); if (Credentials.GetDefaultCredentials().HasServer(EServer.Account)) { _isConnected = true; if (ConnectionSucsess != null) { ConnectionSucsess(); } } }
/// <summary> /// 加载配置 /// </summary> /// <param name="configBuilder"></param> /// <param name="configFiles"></param> /// <returns></returns> public static IConfigurationBuilder LoadConfiguration(this IConfigurationBuilder configBuilder, params string[] configFiles) { var envName = EEnvironment.ToString(); Printor.PrintText("环境变量:" + envName); configBuilder .SetBasePath(RootPath) .AddJsonFile($"appsettings.json", true, false); if (!envName.IsEmptyString()) { configBuilder.AddJsonFile($"appsettings.{envName}.json", true, false); } if (configFiles != null) { foreach (var file in configFiles) { configBuilder.AddJsonFile(file, true, false); } } return(configBuilder); }
public static void SetCredentials(EEnvironment environment, string accessToken, int defaultAccount = 0) { _instance = new Credentials { Environment = environment, AccessToken = accessToken, DefaultAccountId = defaultAccount }; }
public LogError(int userId, string title, string details, string source, ELevel level, EEnvironment environment) : this() { UserId = userId; this.Title = !string.IsNullOrWhiteSpace(title) ? title : throw new ArgumentNullException(nameof(title)); Details = details; Source = source; Level = level; Environment = environment; }
public static void SetCredentials(EEnvironment environment, string accessToken, string defaultAccount = "0") { m_DefaultCredentials = new Credentials { Environment = environment, AccessToken = accessToken, DefaultAccountId = defaultAccount }; }
public ListLogErrorsViewModel(int userId, string title, ELevel level, EEnvironment environment, string source, string details, int events, bool filed, int id) { UserId = userId; Title = title; Level = level; Source = source; Details = details; Events = events; Environment = environment; Filed = filed; Id = id; }
public override async Task RunTest(EEnvironment environment, string token, int account) { await base.RunTest(environment, token, account); // check for failures foreach (var message in _results.Messages) { if (message.Value.IndexOf("False").Equals(0)) { _failedTests++; } } // only if no failures //if (_failedTests.Equals(0)) // await new DinapoliTests(_results).RunTests(); }
public static string ToFriendlyString(this EEnvironment environment) { switch (environment) { case EEnvironment.Development: return("Development"); case EEnvironment.Homologation: return("Homologation"); case EEnvironment.Production: return("Production"); default: return(null); } }
/// <summary> /// Loads and overwrites our configuration parameters. /// </summary> public static void ReloadConfiguration() { Log("Loading configuration."); string configFileContents; try { configFileContents = File.ReadAllText("bot-config.json"); } catch (Exception e) { Log($"Could not load the configuration file. Exception: {e.Message}"); throw e; } try { // Set configuration parameters var config = JsonConvert.DeserializeObject <JObject>(configFileContents); // Telegram _telegramBotApiToken = config["telegram-bot-api-token"].ToString(); // QuantConnect _qcJobUserId = config["quantconnect-job-user-id"].ToObject <int>(); _qcApiAccessToken = config["quantconnect-api-access-token"].ToString(); _qcProjectId = config["quantconnect-project-id"].ToObject <int>(); _qcDeploymentId = config["quantconnect-deployment-id"].ToString(); // OANDA _oandaApiToken = config["oanda-api-token"].ToString(); _oandaAccountId = config["oanda-account-id"].ToString(); _oandaAccountMode = config["oanda-account-mode"].ToString() == "trade" ? EEnvironment.Trade : (config["oanda-account-mode"].ToString() == "practice" ? EEnvironment.Practice : throw new Exception("Invalid OANDA account mode.") ); _oandaCI = new CultureInfo(config["oanda-cultureinfo"].ToString()); _authedUsers = config["authed-users"].ToObject <List <string> >(); } catch (Exception e) { Log($"Could not extract required configuration parameters. Please check the config file is not malformed. Exception: {e.Message}"); } Log("Configuration (re)loaded successfully."); }
public static async Task StartRatesStreamAsync(EEnvironment environment, string token, int account, List <string> instruments, StreamSession <RateStreamResponse> .DataHandler dataHandler, RatesSession.SessionStatusHandler statusHandler) { if (Credentials.GetDefaultCredentials() == null) { Credentials.SetCredentials(environment, token, account); } if (!_rateStreamStarted) { var oandaInstruments = await Rest.GetInstrumentsAsync(account, null, instruments); _ratesSession = new MarketMinerRatesSession(account, oandaInstruments); if (dataHandler != null) { _ratesSession.DataReceived += dataHandler; } // register fault handlers .. yes, the order matters _ratesSession.SessionStatusChanged += (s, e) => _rateStreamStarted = false; if (statusHandler != null) { _ratesSession.SessionStatusChanged += statusHandler; } _tickReceived = new Semaphore(0, 100); _ratesSession.StartSession(); if (!_ratesSession.Stopped()) { // good start _tickReceived.WaitOne(10000); _rateStreamStarted = true; } } else { _ratesSession.DataReceived += dataHandler; } }
private static ListLogErrorsViewModel CreateListLogErrorsViewModel(int userId, string title, EEnvironment environment, ELevel level, string source, string details, int events, bool filed, int id) { return(new ListLogErrorsViewModel( userId: userId, title: title, filed: filed, environment: environment, level: level, source: source, details: details, events: events, id: id )); }
public async void Get_all_log_errors(int userId, string title, EEnvironment environment, ELevel level, string source, string details, int events, bool filed, int id) { //Arrange List <ListLogErrorsViewModel> listLogErrorsViewModel = new List <ListLogErrorsViewModel>(); listLogErrorsViewModel.Add( new ListLogErrorsViewModel( userId: userId, filed: filed, title: title, environment: environment, level: level, source: source, details: details, events: events, id: id )); Response <List <ListLogErrorsViewModel> > response = new Response <List <ListLogErrorsViewModel> >(data: listLogErrorsViewModel, success: true, errors: null); _logErrorServiceMock.Setup(x => x.Get(null)) .Returns(Task.FromResult(response)); //Act var logErrorController = new LogErrorsController(_logErrorServiceMock.Object, _loggerMock.Object); var actionResult = await logErrorController.GetAll(); var result = actionResult.Result as OkObjectResult; // Assert result.StatusCode.Should() .Be((int)HttpStatusCode.OK); var obtainedResponse = result.Value as Response <List <ListLogErrorsViewModel> >; obtainedResponse.Should() .BeEquivalentTo(response); }
public static async Task StartEventsStreamAsync(EEnvironment environment, string token, int account, StreamSession <Event> .DataHandler dataHandler, EventsSession.SessionStatusHandler faultHandler) { if (Credentials.GetDefaultCredentials() == null) { Credentials.SetCredentials(environment, token, account); } if (!_eventsStreamStarted) { _eventsSession = new MarketMinerEventsSession(account); if (dataHandler != null) { _eventsSession.DataReceived += dataHandler; } // register fault handlers .. yes, the order matters _eventsSession.SessionStatusChanged += (s, e) => _eventsStreamStarted = false; if (faultHandler != null) { _eventsSession.SessionStatusChanged += faultHandler; } _eventReceived = new Semaphore(0, 100); _eventsSession.StartSession(); if (!_eventsSession.Stopped()) { // good start _eventReceived.WaitOne(10000); _eventsStreamStarted = true; } } else { _eventsSession.DataReceived += dataHandler; } }
public void TestToFriendlyString(EEnvironment environment, string text) { environment.ToFriendlyString().Should().Be(text); }
//--------------------------------------------------------------------------------------------------- #region Public methods public virtual async Task RunTest(EEnvironment environment, string token, int account) { try { Credentials.SetCredentials(environment, token, account); ///// if (Credentials.GetDefaultCredentials() == null) { throw new Exception("Exception: RestTest - Credentials must be defined to run this test"); } // if run against sandbox, with no account, then autogenerate an account if (Credentials.GetDefaultCredentials().IsSandbox&& Credentials.GetDefaultCredentials().DefaultAccountId == 0) { // Create a test account var response = await Rest.CreateAccount(); Credentials.GetDefaultCredentials().DefaultAccountId = response.accountId; Credentials.GetDefaultCredentials().Username = response.username; } if (Credentials.GetDefaultCredentials().HasServer(EServer.Rates)) { await RunInstrumentListTest(); _marketHalted = await IsMarketHalted(); if (_marketHalted) { _results.Add("***** Market is halted! *****\n"); } // Rates await RunRatesTest(); } if (Credentials.GetDefaultCredentials().HasServer(EServer.Labs)) { var labs = new LabsTest(_results); await labs.Run(); } Task eventsCheck = null; if (Credentials.GetDefaultCredentials().HasServer(EServer.StreamingEvents)) { // Streaming Notifications eventsCheck = RunStreamingNotificationsTest(); // start notifications session } if (Credentials.GetDefaultCredentials().HasServer(EServer.Account)) { // Accounts await RunAccountsTest(); // the following should generate notifications // Orders await RunOrdersTest(); // Trades await RunTradesTest(); // Positions await RunPositionsTest(); // Transaction History await RunTransactionsTest(); } if (Credentials.GetDefaultCredentials().HasServer(EServer.StreamingRates)) { // Streaming Rates RunStreamingRatesTest(); } if (eventsCheck != null) { await eventsCheck; // stop notifications session } } catch (Exception ex) { _results.Add(ex.Message); } }
public void SetEnvironment(EEnvironment value) { _temp_settings[ENVIRONMENT] = value; }
public static async Task StartRatesStreamAsync(EEnvironment environment, string token, int account, List <string> instruments, StreamSession <RateStreamResponse> .DataHandler handler) { await MAOE.Utilities.StartRatesStreamAsync(environment, token, account, instruments, handler, OnRatesSessionStatusChanged); }
////////////////////////////////////////////////////////// /// <summary> /// OandaAPIによる現在値取得スレッド /// </summary> private async void StartOandaAPIThread(IConfiguration config) { var source = "OandaAPI"; OandaAPI_AccountID = config["OandaAPI:AccountID"]; OandaAPI_Token = config["OandaAPI:Token"]; OandaAPI_Environment = config["OandaAPI:Environment"]; //////////////////////////////////////////// // OandaAPI初期化 //////////////////////////////////////////// EEnvironment env = EEnvironment.Practice; if (OandaAPI_Environment == "Trade") { env = EEnvironment.Trade; } Credentials.SetCredentials(env, OandaAPI_Token, OandaAPI_AccountID); //////////////////////////////////////////// // 取得通貨を設定する //////////////////////////////////////////// var param = new PricingParameters(); param.instruments = new List <string> { "USD_JPY", "GBP_JPY", "GBP_USD", "EUR_JPY", "EUR_USD" }; //////////////////////////////////////////// // 辞書の初期化 //////////////////////////////////////////// OandaPrice.TryAdd(USDJPY, new Price(source, TradeEngine.USDJPY)); OandaPrice.TryAdd(GBPJPY, new Price(source, TradeEngine.GBPJPY)); OandaPrice.TryAdd(GBPUSD, new Price(source, TradeEngine.GBPUSD)); OandaPrice.TryAdd(EURJPY, new Price(source, TradeEngine.EURJPY)); OandaPrice.TryAdd(EURUSD, new Price(source, TradeEngine.EURUSD)); Log("[Oanda] Server Started"); //////////////////////////////////////////// // 現在値取得ループ //////////////////////////////////////////// for (; ;) { try { var list = await GetPricingAsync(OandaAPI_AccountID, param); if (list == null) { Log("[Oanda] Communication error"); continue; } foreach (var p in list) { if (p.instrument == "USD_JPY") { var price = OandaPrice[TradeEngine.USDJPY]; price.Ask = (double)p.closeoutAsk; price.Bid = (double)p.closeoutBid; price.Time = DateTime.Now; if (price.IsPriceChanged()) { OnPriceChanged(price); } } if (p.instrument == "GBP_JPY") { var price = OandaPrice[TradeEngine.GBPJPY]; price.Ask = (double)p.closeoutAsk; price.Bid = (double)p.closeoutBid; price.Time = DateTime.Now; if (price.IsPriceChanged()) { OnPriceChanged(price); } } if (p.instrument == "GBP_USD") { var price = OandaPrice[TradeEngine.GBPUSD]; price.Ask = (double)p.closeoutAsk; price.Bid = (double)p.closeoutBid; price.Time = DateTime.Now; if (price.IsPriceChanged()) { OnPriceChanged(price); } } if (p.instrument == "EUR_JPY") { var price = OandaPrice[TradeEngine.EURJPY]; price.Ask = (double)p.closeoutAsk; price.Bid = (double)p.closeoutBid; price.Time = DateTime.Now; if (price.IsPriceChanged()) { OnPriceChanged(price); } } if (p.instrument == "EUR_USD") { var price = OandaPrice[TradeEngine.EURUSD]; price.Ask = (double)p.closeoutAsk; price.Bid = (double)p.closeoutBid; price.Time = DateTime.Now; if (price.IsPriceChanged()) { OnPriceChanged(price); } } } } catch (Exception e) { Log($"[Oanda] {e.Message}"); continue; } } }
public async Task <IList <LogError> > GetByEnvironmentAsync(EEnvironment environment) { return(await _context.LogErrors.Where(x => x.Environment == environment && x.Filed == false).ToListAsync()); }
public static async Task StartEventsStreamAsync(EEnvironment environment, string token, int account, StreamSession <Event> .DataHandler handler) { await MAOE.Utilities.StartEventsStreamAsync(environment, token, account, handler, OnEventsSessionStatusChanged); }