I am trying to run the c# example to “View Open Positions”. Following is the section of code:
var positions = restClient.ListPositionsAsync();
foreach (var position in positions)
{
Console.WriteLine($"{position.Quantity} shares of {position.Symbol}.");
}
I get the error message in Visual Studio that: "foreach statement cannot operate on variables of type ‘Task<IReadOnlyList>’ because ‘Task<IReadOnlyList>’ does not contain a public instance definition for ‘GetEnumerator’
Any suggestions for why the foreach loop is not working.
@Brian67 thanks for the reply. When I run the example as it is, it works. I am trying to create a program on the “Windows Forms App (NET Framework)”. “await” and “async” kewords give me error. I have given the program listing (Form1.cs) below . Only error is at positions in the foreach loop. Please let me know what I should change. Thanks.
using Alpaca.Markets;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test01_748
{
public partial class Form1 : Form
{
private RestClient restClient;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var restClient = new RestClient("XXXXXXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "https://api.alpaca.markets", apiVersion: 2);
// Get a list of all of our orders.
var positions = restClient.ListPositionsAsync();
// Print the quantity of shares for each position.
foreach (var position in positions)
{
Console.WriteLine($"{position.Quantity} shares of {position.Symbol}.");
}
}
}
All I can tell you is that you need await and async. I don’t have any open positions but I tested with ListAccountActivities. Put the async call into a separate function like this and then call that function. You need “async” and “await restClient.ListPositionsAsync();”; This will work. These are asynchronous calls and you MUST HAVE those keywords to get data back.
private async void getPositions()
{
var restClient = new RestClient("xxx", "xxx", "https://api.alpaca.markets");
var positions = await restClient.ListPositionsAsync();
foreach (var position in positions)
{
Console.WriteLine($"{position.Quantity} shares of {position.Symbol}.");
}
}