示例#1
0
        public static async Task <bool> TryRenewToken(CTraderAccount account)
        {
            throw new NotImplementedException("TODO: get client id/secret");

            ////account.Template.
            //var redirectUri = "http://lionfire.software";
            //var renewUri = $"https://connect.spotware.com/apps/token?grant_type=refresh_token&refresh_token={account.Template.AccessToken}&redirect_uri={redirectUri}&client_id={clientId}&client_secret={clientSecret}";

            //var client = NewHttpClient();

            //var uri = SpotwareAccountApi.PositionsUri;
            //uri = uri
            //    .Replace("{id}", account.Template.AccountId.ToString())
            //    .Replace("{access_token}", account.Template.AccessToken)
            //    .Replace("{limit}", "10000")  // HARDCODE REVIEW
            //    ;
            ////UpdateProgress(0.11, "Sending request");
            //var response = await client.GetAsync(uri).ConfigureAwait(false);

            //var receiveStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
            //System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8);
            //var json = readStream.ReadToEnd();
            //var data = Newtonsoft.Json.JsonConvert.DeserializeObject<SpotwareRenewTokenResult>(json);

            //if(data.errorCode == null && !string.IsNullOrEmpty(data.accessToken))
            //{
            //    account.Template.AccessToken = data.accessToken;
            //    account.Template.RefreshToken = data.refreshToken;
            //    await account.Template.Save();
            //    throw new NotImplementedException("UNTESTED -- did it work?");
            //    //return true;

            //}
            //return false;
        }
示例#2
0
        public static async Task <bool> TryRenewToken(CTraderAccount account)
        {
            var connectAppInfo = Defaults.TryGet <ISpotwareConnectAppInfo>();

            if (connectAppInfo == null)
            {
                throw new ArgumentNullException("ISpotwareConnectAppInfo is not set in defaults.");
            }

            var renewUri = $"https://connect.spotware.com/apps/token?grant_type=refresh_token&refresh_token={account.Template.RefreshToken}&client_id={connectAppInfo.ClientPublicId}&client_secret={connectAppInfo.ClientSecret}";

            var client = NewHttpClient(isJson: true);

            var uri = renewUri;

            var response = await client.GetAsync(uri).ConfigureAwait(false);


            var receiveStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

            System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8);
            var json = readStream.ReadToEnd();
            var data = Newtonsoft.Json.JsonConvert.DeserializeObject <SpotwareRenewTokenResult>(json);

            if (!response.IsSuccessStatusCode || data.errorCode != null)
            {
                Debug.WriteLine("Failed refresh response: " + json);
            }

            if (!response.IsSuccessStatusCode)
            {
                switch (response.StatusCode)
                {
                case System.Net.HttpStatusCode.NotFound:

                default:
                    throw new Exception("Refresh failed with HTTP status code: " + response.StatusCode + " " + response.ReasonPhrase);
                }
            }

            if (data.errorCode == null && !string.IsNullOrEmpty(data.accessToken))
            {
                account.Template.AccessToken  = data.accessToken;
                account.Template.RefreshToken = data.refreshToken;
                throw new NotImplementedException("TODO: Sort out the Save call");
                //await account.Template.Save(new PersistenceContext { AllowInstantiator = false});
                //return true;
            }
            return(false);
        }
示例#3
0
        public IAccount GetMarket(string configName)
        {
            var split = configName.Split(':');

            if (split.Length < 1)
            {
                throw new ArgumentException("Format: urischeme:<...>");
            }
            if (split[0].ToLowerInvariant() != "ctrader")
            {
                throw new ArgumentException("Only accepts urls with scheme 'ctrader'");
            }

#if NET462
            var market = new CTraderAccount();
            //market.ConfigName = configName;
            return(market);
#else
            throw new NotImplementedException("Only implemented for .NET Framework");
#endif
        }
示例#4
0
        public static readonly int PositionsPageSize = 500;  // HARDCONST  REVIEW
        public async static Task <List <Position> > GetPositions(CTraderAccount account)
        {
again:
            List <Position> Result = new List <Position>();

            var apiInfo = Defaults.TryGet <ISpotwareConnectAppInfo>();
            var client  = NewHttpClient();

            var uri = SpotwareAccountApi.PositionsUri;

            uri = uri
                  .Replace("{id}", account.Template.AccountId)
                  .Replace("{access_token}", System.Uri.EscapeDataString(account.Template.AccessToken))
                  .Replace("{limit}", PositionsPageSize.ToString()) // TODO: Paging if there are more positions, and cache
            ;
            //UpdateProgress(0.11, "Sending request");
            var response = await client.GetAsyncWithRetries(uri).ConfigureAwait(false);

            //UpdateProgress(0.12, "Receiving response");

            var receiveStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

            System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8);
            var json = readStream.ReadToEnd();

            //UpdateProgress(0.95, "Deserializing");
            //var error = Newtonsoft.Json.JsonConvert.DeserializeObject<SpotwareErrorContainer>(json);
            //if (error?.error != null)
            //{
            //    throw new Exception($"API returned error: {error.error.errorCode} - '{error.error.description}'");
            //}

            var data = Newtonsoft.Json.JsonConvert.DeserializeObject <SpotwarePositionsResult>(json);

            //UpdateProgress(0.98, "Processing data");

            if (data?.data != null)
            {
                foreach (var pos in data.data)
                {
                    var position = new Position()
                    {
                        Id          = pos.positionId,
                        EntryPrice  = pos.entryPrice,
                        EntryTime   = pos.entryTimestamp.ToDateTime(),
                        GrossProfit = pos.profit,
                        Label       = pos.label,
                        Pips        = pos.profitInPips,
                        StopLoss    = pos.stopLoss,
                        Swap        = pos.swap,
                        TakeProfit  = pos.takeProfit,
                        TradeType   = pos.tradeSide.ToTradeType(),
                        Volume      = pos.volume,
                        SymbolCode  = pos.symbolName,
                        Symbol      = account.GetSymbol(pos.symbolName),
                        Commissions = pos.commission,
                        Comment     = pos.comment,
                    };

                    Result.Add(position);
                }
            }
            else
            {
                var error = Newtonsoft.Json.JsonConvert.DeserializeObject <SpotwareErrorContainer>(json);
                if (json.Contains("CH_ACCESS_TOKEN_INVALID"))
                {
                    // TODO: Refactor to a reusable place
                    bool renewResult = await TryRenewToken(account);

                    if (renewResult)
                    {
                        goto again;
                    }
                    else
                    {
                        throw new AccessTokenInvalidException();
                    }
                }
                else
                {
                    throw new Exception("GetPositions: got no data from json response: " + json);
                }
            }

            //UpdateProgress(1, "Done");
            return(Result);
        }
示例#5
0
 public static Task <string> RefreshToken(CTraderAccount account)
 {
     return(Task.FromResult("Not implemented"));
 }