alpacahq / alpaca-trade-api-go

Go client for Alpaca's trade API
Apache License 2.0
328 stars 93 forks source link

'Close position and Sleep until market close' doesn't run #264

Closed nickforce closed 11 months ago

nickforce commented 11 months ago

Hi, I'm testing with the mean-reversion example - the logic to close position and sleep until market close (lines 129-140) doesn't seem to be triggered. Having trouble debugging this- I'm using the exact mean-reversion example code also. Thanks for taking a look!

        clock, err := algo.tradeClient.GetClock()
        if err != nil {
            log.Fatalf("Failed to get clock: %v", err)
        }
        untilClose := clock.NextClose.Sub(clock.Timestamp.Add(-15 * time.Minute))
        time.Sleep(untilClose)

        fmt.Println("Market closing soon. Closing position.")
        if _, err := algo.tradeClient.ClosePosition(algo.stock, alpaca.ClosePositionRequest{}); err != nil {
            log.Fatalf("Failed to close position: %v", algo.stock)
        }
        fmt.Println("Position closed.")
gnvk commented 11 months ago

What do you mean exactly by "doesn't seem to be triggered"? I'd recommend adding a log line before the sleep, e.g.

fmt.Printf("Market closing at %s. Waiting for %s...\n", clock.NextClose, untilClose)

Then you'll see exactly how much the algo sleeps before market close.

nickforce commented 11 months ago

@gnvk I mean it just keeps placing orders into the market close. I would expect the code to close all positions and sleep at 15minutes before market close

nickforce commented 11 months ago

The log line helped clear up the order the sleep was happening. Thank you! @gnvk

gnvk commented 11 months ago

@nickforce I still think there's an issue here.

I mean it just keeps placing orders into the market close. I would expect the code to close all positions and sleep at 15minutes before market close

This is true. Since the rebalancing happens on a separate goroutine, I think we still send orders after closing all positions 15 minutes before the market closes. Isn't that the case?

nickforce commented 11 months ago

@gnvk Yes, from what I have seen it is intermittent. But I do see orders happening even after the 15 minutes prior to market close/sleep logic runs.