IB Gateway Auto Restart: Keep Your IBKR Bot Running 24/7 on a VPS
IB Gateway shuts down or restarts once a day, and by default that stops any trading bot connected to it. To keep an IBKR bot running unattended you need three things: the auto restart setting in Gateway, a tool that logs Gateway in again when a full login is required, and bot code that reconnects on its own. This guide covers each one for a Linux VPS.
Why IB Gateway restarts every day
Interactive Brokers requires TWS and IB Gateway to restart daily, and its servers also have a nightly maintenance window during which connections drop. On top of that, a full login with your credentials is required again about once a week. A bot that assumes the connection stays up forever will fail on the first night.
Step 1: Turn on auto restart in IB Gateway
In IB Gateway open Configure, then Settings, then Lock and Exit. Choose Auto restart instead of auto log off, and set the time to a quiet period outside your trading hours.
With auto restart, Gateway restarts itself at that time and comes back without asking for your password, so the bot only sees a short disconnect. This works for the daily restart during the week. It does not remove the weekly full login.
While you are in the settings, check the API section too:
- Enable socket clients, and turn off Read-Only API if the bot places orders.
- Note the socket port:
4002for paper and4001for live by default. - Allow connections from localhost only, unless the bot runs on another machine.
Step 2: Automate the login with IBC
IB Gateway is a desktop application. It cannot be started with a username and password from the command line on its own. IBC is a widely used open source tool that starts Gateway, fills in the login, and handles the dialogs that would otherwise wait for a click.
On a headless Linux server the usual setup is:
- Install IB Gateway (the offline or stable version) and Java as required by the installer.
- Install a virtual display such as
Xvfb, because Gateway needs a screen to draw on even when nobody is watching. - Download IBC and edit its
config.ini. - Start Gateway through IBC's start script instead of the normal launcher.
The settings that matter most in config.ini:
IbLoginId=your_username
IbPassword=your_password
TradingMode=paper
AutoRestartTime=11:45 PM
AcceptIncomingConnectionAction=accept
ExistingSessionDetectedAction=primary
Setting names can change between IBC versions, so check them against the user guide that ships with the version you download. Because the file holds your password, restrict its permissions so only the bot's user can read it:
chmod 600 ~/ibc/config.ini
Step 3: Handle two-factor authentication
Live accounts use two-factor authentication through the IBKR Mobile app. IBC cannot approve that for you. In practice:
- With auto restart enabled, you approve the login on your phone about once a week, usually after the weekend.
- Paper accounts log in without the second factor, which makes them easy to automate fully.
- Plan the weekly login for a time when you are available, and have the bot alert you if Gateway is waiting.
Step 4: Run it as a service
Use systemd so Gateway starts on boot and is started again if it crashes.
[Unit]
Description=IB Gateway via IBC
After=network-online.target
[Service]
User=trader
ExecStart=/usr/bin/xvfb-run -a /home/trader/ibc/gatewaystart.sh -inline
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target
Treat this as a starting point. xvfb-run starts the virtual display and Gateway together, and the paths depend on where you installed IBC. Run the bot as a second service that starts after this one.
Step 5: Make the bot reconnect
Even with everything above, the bot will lose its connection for a short time every day. It has to wait and reconnect instead of crashing.
import time
from ib_async import IB
ib = IB()
def ensure_connected():
while not ib.isConnected():
try:
ib.connect("127.0.0.1", 4002, clientId=1, timeout=20)
print("Connected to IB Gateway")
except Exception as e:
print("Gateway not ready:", e)
time.sleep(30)
while True:
ensure_connected()
try:
run_one_cycle(ib) # your strategy logic
except ConnectionError:
pass # loop back and reconnect
ib.sleep(60)
After every reconnect, do three things before trading again:
- Re-subscribe to market data. Streaming subscriptions do not survive a restart.
- Read positions and open orders from IBKR. Do not trust what the script remembered.
- Check that data is fresh. Wait for a new tick or bar before acting on prices.
Step 6: Know when it breaks
- Send a Telegram or email alert when the bot has been disconnected for more than a few minutes.
- Log every disconnect and reconnect with a timestamp.
- Send a short daily message that the bot is alive. Silence then tells you something is wrong.
Common problems
- Error 502, couldn't connect. Gateway is still starting, or the port in the bot does not match the port in Gateway.
- Errors 1100 and 1102. Connection to IBKR lost and restored. Normal during the nightly maintenance window.
- Gateway stuck at the login screen. Usually a waiting two-factor request or wrong credentials in
config.ini. - "Existing session detected". You logged in to TWS or the mobile app with the same username. Use a second username for the bot if you want to be logged in elsewhere at the same time.
- Bot connects but gets no data. The subscriptions were not requested again after the restart.
Frequently asked questions
Can IB Gateway run for weeks without any manual step?
On a paper account, yes. On a live account you still need to approve the two-factor login about once a week.
Should I use TWS or IB Gateway on a VPS?
IB Gateway. It uses less memory and has no charts or trading screens to keep running.
Is it safe to store my password in a config file?
It is a risk you should manage: lock down file permissions, keep the server patched, restrict SSH access, and consider a separate IBKR username for the bot.
Want this set up for you?
VPS deployment with automatic restarts is part of the bots we deliver. See IBKR trading bot development, or IBKR API development if you already have a bot that keeps disconnecting. Related: how to build an IBKR trading bot in Python.