Sviluppo TradingBot
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
using Alpaca.Markets;
|
||||
|
||||
public class AlpacaTradingService
|
||||
{
|
||||
private IAlpacaTradingClient _tradingClient;
|
||||
private IAlpacaDataClient _dataClient;
|
||||
|
||||
public void Initialize(string apiKey, string apiSecret, bool isPaper)
|
||||
{
|
||||
// Seleziona l'ambiente corretto
|
||||
var environments = isPaper ? Environments.Paper : Environments.Live;
|
||||
|
||||
// Inizializza il client per il trading (ordini, posizioni, conto)
|
||||
_tradingClient = environments.GetAlpacaTradingClient(new SecretKey(apiKey, apiSecret));
|
||||
|
||||
// Inizializza il client per i dati di mercato (prezzi, candele)
|
||||
_dataClient = environments.GetAlpacaDataClient(new SecretKey(apiKey, apiSecret));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
public async Task<decimal> GetAvailableEquityAsync()
|
||||
{
|
||||
// Recupera le informazioni del conto
|
||||
IAccount account = await _tradingClient.GetAccountAsync();
|
||||
|
||||
// Ritorna il valore totale del portafoglio o la liquidità disponibile
|
||||
return account.Equity;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
public async Task<List<IBar>> GetHistoricalBarsAsync(string symbol)
|
||||
{
|
||||
var request = new HistoricalBarsRequest(symbol, BarTimeFrame.Hour, Into.Past(TimeSpan.FromDays(7)))
|
||||
{
|
||||
// Limitiamo i dati per mantenere l'app leggera
|
||||
PageSize = 50
|
||||
};
|
||||
|
||||
IMultiPage<IBar> barsPage = await _dataClient.ListHistoricalBarsAsync(request);
|
||||
|
||||
// Restituisce la lista di candele per il simbolo specificato
|
||||
return barsPage.Items[symbol].ToList();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
public async Task PlaceBracketOrderAsync(string symbol, int quantity, decimal entryPrice, decimal takeProfitPrice, decimal stopLossPrice)
|
||||
{
|
||||
// 1. Ordine principale di acquisto (Buy) a mercato o limite
|
||||
var entryOrder = MarketOrder.Buy(symbol, quantity);
|
||||
|
||||
// 2. Configura il Bracket Order inserendo Take Profit e Stop Loss
|
||||
var bracketOrder = entryOrder.TakeProfit(takeProfitPrice).StopLoss(stopLossPrice);
|
||||
|
||||
// 3. Invia l'ordine ad Alpaca
|
||||
IOrder order = await _tradingClient.PostOrderAsync(bracketOrder);
|
||||
|
||||
Console.WriteLine($"Ordine inviato con successo. ID: {order.OrderId}");
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
public async Task<bool> HasOpenPositionAsync(string symbol)
|
||||
{
|
||||
try
|
||||
{
|
||||
IPosition position = await _tradingClient.GetPositionAsync(symbol);
|
||||
return position != null && position.Quantity > 0;
|
||||
}
|
||||
catch (AlpacaRestException ex) when (ex.ErrorCode == 40410000)
|
||||
{
|
||||
// Il codice 40410000 indica che non ci sono posizioni aperte per quel simbolo
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user