Coins: 17,549
Exchanges: 1,472
Market Cap: $2.626T 0.5%
24h Vol: $99.25B
Gas: 0.214 GWEI
Upgrade to Premium
API
TABLE OF CONTENTS

How to Build a Crypto Dollar Cost Averaging (DCA) Bot in Python

5.0
| by
Roxait
|
Edited by
Brian Lee
-

Dollar cost averaging is one of the simplest automated trading strategies. You set a fixed amount, buy on a schedule, and let time do the heavy lifting. 

In this guide, we will build a minimal crypto dollar cost averaging (DCA) bot in Python that pulls prices from CoinGecko API, simulates buy orders, logs them to SQLite, and optionally adds a smarter rule based on moving averages. The resulting script is short, practical, and fully runnable, leaving a little room for you to tinker and expand its capabilities.

How to Build a Crypto Dollar Cost Averaging (DCA) Bot in Python | CoinGecko API


What Is a Crypto DCA Bot?

A crypto DCA bot is an automated trading tool that invests a fixed amount of money at regular intervals, regardless of market price. Instead of trying to time tops and bottoms, you buy a little bit every day, week, or month. Over time this tends to smooth out your average entry price, which is why DCA is popular with long-term investors and casual hobbyists.

The keyword here is automation. A bot removes the "should I buy today?" decision. It always executes the same rule, which helps avoid emotional swings and the common trap of buying only when the chart looks good. It also makes the process boring in a good way. That consistency is what makes DCA attractive for people who want exposure to Bitcoin or Ethereum without watching charts all day.

In this tutorial, we will build a personal tool for simulating a Dollar Cost Averaging (DCA) strategy. The tool does not connect to an exchange; it calculates potential buys and logs them, effectively operating as a paper trading system. This approach is ideal for beginners to safely simulate trades and test the logic. If you later choose to engage in live trading, you can connect the same core logic to an exchange's API.


Prerequisites

You do not need a huge stack for this. Keep it light and runnable.

  • Python 3.10+ installed

  • A CoinGecko API key. If you do not have one yet, follow this guide to get your free Demo API key. A Demo API key is sufficient for everything in this tutorial.

  • Basic familiarity with requests, environment variables, and scheduling

  • These packages installed:

pip install requests apscheduler python-dotenv

We will store your API key in a .env file (already in crypto_dollar_cost/.env) and load it securely at runtime. The full script we build is saved as dca_bot.py so you can run it immediately.

The script is designed to check for a Pro API Key first, and it falls back to your Demo key if necessary. Because both are loaded from the same .env file, you can smoothly upgrade your plan and handle higher volume requests without changing any underlying code.


Step 1: How to Fetch Real-Time Crypto Prices for Your DCA Bot

CoinGecko API uses coin IDs like bitcoin and ethereum instead of ticker symbols like BTC and ETH. That is why we start with a simple ID lookup. Then we call the /simple/price endpoint to pull current prices for multiple coins in one request. You can also request the 24-hour change in the same call, which will be useful later for "smart DCA" ideas.

Here is the minimal price fetcher. It resolves symbols to IDs using /coins/list, then calls /simple/price in a single request.

In the full script, the price map output is not just for debugging. It is also used to calculate units for each coin and decide whether to proceed or skip if a price is missing, making the bot resilient against wrong coin IDs or empty API data.

The only difference between the Demo and Pro API is the base URL and header name. The Demo plan uses the public base URL and a demo key header, while paid API plans require the Pro API base URL and a paid API Key. The core logic remains unchanged. We hide this configuration detail behind a simple switch in the final script, allowing you to follow the tutorial for free while supporting a production upgrade later. This "upgrade path" is beneficial if you scale the bot to handle multiple coins or higher frequency schedules.

In addition, there are two practical tips to keep in mind:

  1. For faster execution, you can skip the symbol lookup and use CoinGecko IDs directly once you know them.

  2. You should always request multiple coins in a single API call using a comma-separated list, as this safely keeps you under rate limits and simplifies your scheduling logic.

In the final script (dca_bot.py) we include the same logic with a retry wrapper and support for both Demo and Pro API keys.

Subscribe to CoinGecko API


Step 2: How to Implement the DCA Bot Buy Logic

Now that we can fetch prices, the buy logic is simple. Define your DCA parameters, calculate units, and simulate a buy. That is it. We are not placing real orders in this tutorial, which keeps the code safe, testable, and free from exchange-specific requirements.

Key parameters:

  • INVESTMENT_AMOUNT_USD: fixed amount per interval (example: $50)

  • TARGET_COINS: coin IDs (example: bitcoin, ethereum)

  • INTERVAL: daily or weekly schedule

The calculation is straightforward. The number of units equals the INVESTMENT_AMOUNT_USD divided by the current_price. Following this, we print a simulated order and record it to SQLite in Step 4.

As you build out your strategy, you will need to map out your design choices and decide whether the fixed investment amount should be applied per coin or per portfolio. In the snippet above, the bot spends the full INVESTMENT_AMOUNT_USD on each coin, which is simple and mirrors a "fixed-per-asset" DCA. If you prefer a "fixed total budget" per interval, you can split the amount across coins (for example, divide by the number of targets or apply weights like 70/30 for BTC/ETH). Both are valid. The important part is to pick one rule and stick to it consistently.

As a necessary reminder, this code is purely educational and does not constitute financial advice. This tutorial simulates orders and does not execute real trades. To transition to live trading, you would need to integrate with an exchange API and manage essential considerations like authentication, account balances, slippage, and order routing.


Step 3: How to Schedule Automated DCA Purchases

Automation is the whole point. For scheduling, APScheduler gives you a clean, cron-like interface without running a separate system service. You can schedule daily or weekly buys with a couple of lines.

Below is a simple scheduler setup that shows both daily and weekly options. In the full script, you can enable one schedule via the --schedule flag.

You probably only want one schedule in practice, but it is useful to see both patterns. The full script defaults to a single immediate run (so you can test without waiting), and you can switch to scheduled mode like this:

python dca_bot.py --schedule daily

Run example

From the repo root:

python crypto_dollar_cost/dca_bot.py

Expected output (example):

DCA Expected output (example):

The numbers will change, but the flow should match. If you want it to keep running on a schedule, use the --schedule flag as shown above.

If you want something more visual, run python crypto_dollar_cost/dca_bot.py --once --report to generate crypto_dollar_cost/dca_report.html and a matching screenshot at crypto_dollar_cost/dca_report.png.

crypto_dollar_cost Web Output

💡 Pro tip: When deploying your bot, take note of time zones, as cron schedules depend on the execution machine's local time (which may differ if on a cloud server). To ensure a specific buy time (e.g., after waking up), explicitly set the server's time zone or run the bot locally. Use the --once flag during testing to prevent accidental background scheduler execution.

Step 4: Logging The Transaction Histories

A DCA bot is not very useful if you cannot track what you bought. We keep it simple with SQLite. It gives you a local database file, zero setup, and easy queries later.

We store each buy with the timestamp, coin ID, price, units, and USD amount. Then we can compute total invested, total units, average cost basis, and even unrealized PnL by comparing to the current price.

Here is a lightweight SQLite helper (adapted from the full script):

Now add a quick summary query and a basic unrealized PnL calculation using the /simple/price endpoint again:

In the full program, this runs right after each scheduled buy. Every execution appends a row per coin to transactions, then reads the table back to compute totals, average cost, and a quick unrealized PnL snapshot using the latest prices. The database is local, so your history stays in your control, and the design stays simple (one table, one insert per buy, one summary query). If the price API hiccups, the saved history is still intact.

While this does not provide a robust portfolio tracker, it answers the two most common questions that arise after a few weeks of utilizing a DCA strategy. It clarifies exactly how much capital you have invested and what your average cost basis is. From there you can expand into CSV exports, charts, or a lightweight dashboard.


Further Enhancements

The core bot logic above is intentionally simple. But once you have a baseline DCA running, you can experiment with "smart" adjustments. A popular, beginner-friendly strategy involves writing a dip-buying rule utilizing a moving average. For example, if the current market price drops a specific percentage below the 7-day Simple Moving Average (SMA), your bot could programmatically increase the buy size.

CoinGecko API offers various endpoints for accessing historical crypto data, including the historical price data available through the /coins/{id}/market_chart endpoint. An example of how to use this endpoint is:

https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=30

This endpoint returns a list of [timestamp, price] pairs. Here is a minimal moving-average helper using only Python lists:

You can explore other strategies without changing the core architecture. With value averaging, you can increase buys when your portfolio falls below a target curve. If you want to manage exposure, you can set risk bands to reduce buys when volatility spikes or the 24-hour change is extreme. Finally, you can implement multi-coin balancing by splitting the fixed amount according to target weights instead of an equal allocation.

Note that these are optional and the core DCA flow works without any of these extras.


Get the Full Source Code

The complete, ready-to-run DCA bot is available in this GitHub repository.

To get started quickly, simply clone the repo, add your CoinGecko API key to a .env file, and start paper trading in minutes. The script includes all the features covered in this tutorial: price fetching, buy simulation, SQLite logging, scheduling, and the optional smart DCA logic.


Conclusion

You now have a working Dollar Cost Averaging bot in Python. It includes real price data, simulated buys, a scheduler, and a local transaction log. While simple, it covers all the core fundamentals such as fetching prices, calculating units, recording history, and evaluating performance over time. This is enough for a personal Dollar Cost Averaging system and provides a strong foundation for future automation.

If you want to take it one step further, build a lightweight portfolio tracker on top of the same SQLite data, or hook the bot into an exchange API for live trading. As your personal DCA bot usage scales, consider upgrading to a paid CoinGecko API plan to unlock higher rate limits, deeper historical market data, and advanced endpoints necessary to support a reliable production trading system.

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Want to be the first to know about upcoming airdrops?
Subscribe to the CoinGecko Daily Newsletter!
Join 600,000+ crypto enthusiasts, traders, and degens in getting the latest crypto news, articles, videos, and reports by subscribing to our FREE newsletter.
Tell us how much you like this article!
Vote count: 3
Roxait
Roxait
With 18 years of pioneering experience in the crypto space, Roxait excels in technical collaborations to develop cutting-edge decentralized solutions. Our commitment to innovation and expertise in blockchain technology has made us a trusted partner in driving the future of decentralized systems. Follow the author on Twitter @roxaittech

More Articles

New Portfolio
Icon & name
Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
SOL
Solana
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT-BR
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Welcome to CoinGecko
Welcome back!
Login or Sign up in seconds
or
Sign in with . Not you?
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
By continuing, you acknowledge that you've read and agree fully to our Terms of Service and Privacy Policy.
Get Price Alerts with CoinGecko App
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores
Add NFT
Track wallet address
Paste
We only display assets from supported networks.
Ethereum Mainnet
Base Mainnet
BNB Smart Chain
Arbitrum
Avalanche
Fantom
Flare
Gnosis
Linea
Optimism
Polygon
Polygon zkEVM
Scroll
Stellar
Story
Syscoin
Telos
X Layer
Xai
Read-only access
We only fetch public data. No private keys, no signing, and we can't make any changes to your wallet.
Create Portfolio
Select icon
💎
🔥
👀
🚀
💰
🦍
🌱
💩
🌙
🪂
💚
CoinGecko
Better on the app
Real-time price alerts and a faster, smoother experience.
You’ve reached the limit.
Guest portfolios are limited to 10 coins. Sign up or log in to keep the coins listed below.