Created
July 23, 2019 20:22
-
-
Save ttt733/fac6da2d3d191f1f08c477c0cc5c1cc0 to your computer and use it in GitHub Desktop.
Shorting with the Alpaca API in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Alpaca.Markets; | |
using System; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
// With the Alpaca API, you can open a short position by submitting a sell | |
// order for a security that you have no open long position with. | |
namespace ShortingExample | |
{ | |
internal class ShortProgram | |
{ | |
private static string API_KEY = "your_api_key"; | |
private static string API_SECRET = "your_secret_key"; | |
private static string API_URL = "https://paper-api.alpaca.markets"; | |
// The security we'll be shorting | |
private static string symbol = "TSLA"; | |
private static RestClient restClient; | |
public static async Task Main(string[] args) | |
{ | |
// First, open the API connection | |
restClient = new RestClient(API_KEY, API_SECRET, API_URL, apiVersion: 2); | |
// Submit a market order to open a short position of one share | |
var order = await restClient.PostOrderAsync(symbol, 1, OrderSide.Sell, OrderType.Market, TimeInForce.Day); | |
Console.WriteLine("Market order submitted."); | |
// Submit a limit order to attempt to grow our short position | |
// First, get an up-to-date price for our security | |
var barSet = await restClient.GetBarSetAsync(new[] { symbol }, TimeFrame.Minute, 1); | |
var bars = barSet[symbol].ToList(); | |
var price = bars[0].Close; | |
// Submit another order for one share at that price | |
order = await restClient.PostOrderAsync(symbol, 1, OrderSide.Sell, OrderType.Limit, TimeInForce.Day, price); | |
Console.WriteLine($"Limit order submitted. Limit price = {order.LimitPrice}"); | |
// Wait a few seconds for our orders to fill... | |
Thread.Sleep(2000); | |
// Check on our position | |
var position = await restClient.GetPositionAsync(symbol); | |
if (position.Quantity < 0) | |
{ | |
Console.WriteLine($"Short position open for {symbol}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment