[BUG]: NullReferenceException when placing Order in Alpaca SDK
See original GitHub issueIs there an existing issue for this?
- I have searched the existing issues
Current Behavior
Our trading strategy is implemented in a .NET Core application and uses the Alpaca SDK to place Buy/Sell orders on Alpaca’s Paper Trading environment. On June 23, 2023, while running our strategy, we encountered 9 NullReferenceExceptions. The exceptions occurred while trying to place orders for different stocks. The exceptions were thrown within the Alpaca SDK. Attached a sample stack trace from one of the exceptions
Expected Behavior
We expected the Alpaca SDK to handle our Buy/Sell orders without throwing any exceptions. If there was a problem with a specific order, we expected an error message related to the specifics of that order, not a NullReferenceException which suggests a programming error within the SDK.that
Steps To Reproduce
- Run our trading strategy on the Alpaca Paper Trading environment.
- The strategy attempts to place Buy/Sell orders for various stocks.
- Observe that NullReferenceExceptions are thrown from within the Alpaca SDK.
Environment
- SDK Version: 6.2.1 Latest
- OS (version, bitness): Windows 10 Pro
- .NET SDK (version): Asp Net Core 7
- target process .NET version/bitness:
Anything else?
Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at System.Net.Http.HttpConnection.WriteAsciiStringAsync(String s, Boolean async)
at System.Net.Http.HttpConnection.WriteHeadersAsync(HttpHeaders headers, String cookiesFromContainer, Boolean async)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at Alpaca.Markets.ThrottleParameters.CustomHttpHandler.sendAsyncWithTimeout(HttpRequestMessage request, CancellationToken cancellationToken)
at Polly.Retry.AsyncRetryEngine.ImplementationAsync[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Func`5 onRetryAsync, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider, Boolean continueOnCapturedContext)
at Polly.AsyncPolicy`1.ExecuteAsync(Func`3 action, Context context, CancellationToken cancellationToken, Boolean continueOnCapturedContext)
at Polly.Wrap.AsyncPolicyWrapEngine.<>c__DisplayClass2_0`1.<<ImplementationAsync>b__0>d.MoveNext()
--- End of stack trace from previous location ---
at Polly.Retry.AsyncRetryEngine.ImplementationAsync[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Func`5 onRetryAsync, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider, Boolean continueOnCapturedContext)
at Polly.AsyncPolicy.ExecuteAsync[TResult](Func`3 action, Context context, CancellationToken cancellationToken, Boolean continueOnCapturedContext)
at Polly.Wrap.AsyncPolicyWrapEngine.ImplementationAsync[TResult](Func`3 func, Context context, CancellationToken cancellationToken, Boolean continueOnCapturedContext, IAsyncPolicy outerPolicy, IAsyncPolicy`1 innerPolicy)
at Polly.AsyncPolicy`1.ExecuteAsync(Func`3 action, Context context, CancellationToken cancellationToken, Boolean continueOnCapturedContext)
at Alpaca.Markets.ThrottleParameters.CustomHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.<SendAsync>g__Core|5_0(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.<SendAsync>g__Core|5_0(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Alpaca.Markets.HttpClientExtensions.callAndDeserializeAsync[TApi,TJson](HttpClient httpClient, HttpRequestMessage request, CancellationToken cancellationToken)
at Alpaca.Markets.HttpClientExtensions.callAndDeserializeAsync[TApi,TJson,TContent](HttpClient httpClient, HttpMethod method, Uri endpointUri, TContent content, CancellationToken cancellationToken)
at AlpacaStockTrader.<>c__DisplayClass7_0.<<PostOrderAsync>b__0>d.MoveNext() in
--- End of stack trace from previous location ---
at Polly.Retry.AsyncRetryEngine.ImplementationAsync[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Func`5 onRetryAsync, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider, Boolean continueOnCapturedContext)
at Polly.AsyncPolicy.ExecuteAsync[TResult](Func`3 action, Context context, CancellationToken cancellationToken, Boolean continueOnCapturedContext)
at AlpacaStockTrader.PostOrderAsync(Guid tradeActionId, StockId stockId, Decimal units, OrderActionType orderActionType) in
Issue Analytics
- State:
- Created 3 months ago
- Comments:6
Top Results From Across the Web
Market Buy Order Accpted but never Filled, Sell order as new ...
Hi Today while using my paper account, all of market orders were going as Accepted,but never filled up. For sell orders had the...
Read more >python - alpaca-py StopOrderRequest bug related to status ...
Using the alpaca-py library, I am trying to create a new order using the StopOrderRequest with brackets. The result is this error message:...
Read more >Trailing stop order triggers error · Issue #396
Following the Submit Trailing Stop Orders section from here I get the error alpaca_trade_api.rest.APIError: cannot open a short sell while a ...
Read more >Alpaca Close order missing - Issues
Whilst testing paper trading on Apaca, I noticed that there's a mismatch between what QR thinks is the case and what Alpaca thinks....
Read more >Alpaca Trading API Guide - A Step-by-step Guide
It is an interface that allows you to trade automatically with the stock broker Alpaca. More specifically, the trading API allows you to...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Hi @OlegRa , thanks a lot for your reply
I was monitoring the app last week and it seems the exception wasn’t thrown anymore “Not sure why since nothing changed”
I’ll monitor it next week and confirm if the issue still exists then we try the approach you mentioned otherwise will close the issue
Thank you
@ObaidaAlhaasan, thanks a lot for your prompt answers. Unfortunately, I didn’t find anything related to this problem in .NET and Polly issue trackers. But I still believe that the problem’s root cause is in the SDK retry policy although I can’t confirm that right now.
My suggestion is to build a pre-release version of SDK with a single change - the retry policy will work only for the HTTP
GET
request. In all other cases (PUT
,POST
,PATCH
,DELETE
) any error returned by the server will be immediately reported to the caller side.This change is backward compatible at the API level but will change the behavior of existing code and I don’t want to make it widely available until I’ll be sure it helps in your case. The main difference will be in error handling - you should implement a retry policy (if you need it) and service-unavailable conditions handling on the caller side.
If you are OK with this approach and have time/ability to test this pre-release version using your application I can make this release later today.