dYdX Chain / Stage your entries

Martingale bot.

Define a sequence of entry sizes and price deviations, then manage a reduce-only take-profit order against the quantity-weighted average entry.

UNDERSTAND THE BOT

The strategy
in detail.

How staged entries work

Martingale manages a sequence of explicitly sized entries and a take-profit exit. You choose a long or short direction, price deviations and every entry quantity. Increasing quantities is optional; the bot does not require the classic doubling progression.

The anchor comes from your starting price or the order-book midpoint. Each completed entry updates the quantity-weighted average entry price. The bot cancels the previous take-profit order, confirms cancellation, places a reduce-only exit for the accumulated position and proceeds to the next entry. After the final entry, only the take-profit order remains. A completed take profit ends the cycle.

Understand the average

If one unit fills at 100 and three units fill at 90, the combined average is 92.5 for four units, before fees. It is not the simple average of the two prices. The take-profit calculation uses the accumulated position and the configured fractional target. Fees, funding and network costs still affect the account result.

What to monitor

Calculate the sum of all entry sizes before starting. Increasing size during an adverse move increases the collateral needed and the potential loss. A take-profit order does not limit losses, and this implementation has no automatic stop-loss.

Partially filled entries, partially executed exits during resizing and an entry racing a completed exit stop execution for reconciliation. Check positions and orders before resuming. The bot does not assume that cancellation means an order never traded.

Get it running

You need Git, Docker with Compose, and a funded dYdX Chain testnet wallet to use the supplied example. The bot needs the wallet's mnemonic and a matching Chain address. Old v3 API keys, STARK keys and v3 state do not work here.

  1. Clone the repository and create your environment file:
git clone https://github.com/akilibots/akili-martingale.git
cd akili-martingale
cp .env.example .env
  1. Edit .env. Set DYDX_MNEMONIC to your Chain wallet's mnemonic, in quotes. Leave the Telegram values empty if you do not want notifications.

  2. Edit data/strategy.json. Set exchange.address to that wallet's address, check its subaccount and review the strategy quantities and prices. The sample endpoints select testnet.

  3. Build and start the bot:

docker compose up --build -d
docker compose logs -f

To stop it:

docker compose down

Stopping the process leaves its exchange orders in place. Check and cancel those orders separately when needed. Do not run two instances from the same data folder.

How it works

main.direction is long or short. Each item in orders defines an entry's base-asset size, fractional price deviation from the initial anchor and fractional profit target. Sizes are explicit and do not have to double. A zero start.price chooses the midpoint. start.follow is a fractional movement threshold for abandoning an entirely unfilled initial entry.

Each completed entry updates the quantity-weighted average entry price. The bot cancels the previous take-profit order, confirms cancellation, and places a reduce-only exit for the accumulated position. It then places the next entry. The final entry leaves only the take-profit order. A completed take profit stops the cycle and persists its actual price-and-fee result, including across restarts.

Partially filled entries, partially executed exits during resizing, and a new entry racing a completed exit stop the bot for reconciliation. These cases do not trigger automatic new exposure. Reconcile the wallet and saved orders before restarting. stop.price must be zero; an automatic stop-loss is not implemented.

Configuration notes

Setting What to check
main.market The perpetual market, such as BTC-USD
exchange.address The Chain address matching DYDX_MNEMONIC
exchange.subaccount A cross-margin subaccount from 0 to 127, with collateral
exchange.network testnet or mainnet
exchange.indexer, websocket, node Endpoints for the same selected network
exchange.poll_seconds Seconds between status checks for the strategy loops

The node value is a TLS gRPC host and port, without http:// or https://. Review market sizes and prices before running any sample. Quantities are in the base asset, not a dollar budget. To use mainnet, change the network and all its endpoints together and configure the corresponding wallet and collateral.

You can supply JSON5 through the strategy environment variable instead of the strategy file. Settings are tied to saved strategy state; reconcile existing orders before changing an active strategy. Telegram notifications use TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID in .env.

Restarting and recovery

Compose mounts ./data, so state survives a container replacement. data/state.json records progress and data/exchange.json records client IDs before order submission. Keep them together and keep them out of Git.

An uncertain submission is checked using its existing client ID. The bot does not turn a timeout into a second trade. If it cannot reconcile an order, it stops so you can inspect the exchange and saved state. Do not delete state to bypass an error. Partial-fill and cancellation handling is described above.

For a v3 migration, reconcile old orders and positions first, archive the old state, then start with a fresh data folder. Use a separate data folder and subaccount for each strategy. Never commit wallet mnemonics or .env.

Limit orders use Chain long-term orders with a default 24-hour expiry. Prices follow market ticks and sizes must be exact multiples of stepSize. Market orders use short-term IOC orders with a slippage bound. Profit figures, where reported, include actual fill prices and trading fees, but exclude funding, network transaction fees and unrealised positions.

Test it yourself

docker build --target test -t bot-test .
docker run --rm --network none bot-test

The suite uses simulated exchange responses with networking disabled. It covers order handling and recovery; SDK checks also build and sign transactions locally. Passing tests is not a promise of live execution or profitable trading.

Running directly with Python

Use Python 3.15.2 and install the native C/C++ and Rust build tools required by the wallet dependencies. Docker includes these prerequisites in its build stage.

python3 -m venv .venv
. .venv/bin/activate
PIP_BUILD_CONSTRAINT="$PWD/build-constraints.txt" python3 -m pip install -r requirements-dev.txt
python3 -m pip check

Export the values from .env into your shell, then run python3 run.py. The direct Python entrypoint does not automatically read .env. The dYdX SDK constrains some signing packages to older compatible versions; build-constraints.txt supplies the build tools those packages require.

Use Martingale in your workspace

Manage your Martingale strategy through the Akilibots app. Keep the bot configuration, exchange connection and execution history together.

Set up your account and exchange

  1. Create your account and sign in to your workspace.
  2. Open exchange connections and add your dYdX Chain account and select the correct network and subaccount.
  3. Check that the connection uses the intended account and has the funds needed for the strategy. Use testnet to check the configuration first.
  4. Create a bot and select Martingale.

Configure the strategy

  1. Choose the market and long or short direction.
  2. Set the anchor price, or use the order-book midpoint.
  3. Define every entry size, price deviation and profit target explicitly.
  4. Review the maximum cumulative position and available collateral.

Review and run

  1. Review the market, network, order quantities and maximum exposure. Save the configuration.
  2. Start the bot, then check the first action against the exchange account.
  3. Use the bot detail view to monitor orders, executions, logs and errors. A queued request or submitted order is not a confirmed fill.
  4. Pause the bot before changing its strategy. Check the exchange for open orders and positions; stopping a bot does not itself close a position.
  5. If execution stops with a reconciliation error, compare the saved bot state with exchange orders and fills before resuming.

Commercial access

For account access and deployment enquiries, contact Akilibots. Never include wallet mnemonics, private keys or API secrets in an email.

Commercial service guide