Skip to main content

Exploring dynamic position sizing using Amibroker and the Anti-Martingale Trading system based on reader requests. Dynamic position sizing adapts position size for each trade, enhancing system performance. For example, if a system struggles in Q4 but excels in other quarters, it can automatically decrease position size in Q4 and increase it in Q1, Q2, and Q3. Precise position sizing is critical for trading success.

Exploring the Anti-Martingale System with Dynamic Position Sizing

The Martingale and Anti-Martingale systems, widely recognized in the casino world, find application in trading systems. Martingale involves doubling bets after losses to recoup with one win, while Anti-Martingale increases bets after profits and decreases them on losses. The Anti-Martingale approach assumes that gains from winning trades outweigh losses, making it effective in trending markets. Statistical evidence supports Anti-Martingale’s long-term superiority over Martingale in trading. This system capitalizes on prudent risk management and favorable market trends, making it a valuable strategy for traders.

Amibroker offers dynamic position sizing capabilities, enabling the creation and backtesting of the Anti-Martingale strategy. In Amibroker’s terminology, increasing your position size is referred to as “Scaling in,” while decreasing it is known as “Scaling-Out.” Two special constants, sigScaleIn and sigScaleOut, provide the means to instruct the backtester when to scale in or out.

To adjust the position size, follow these steps:

  • Assign sigScaleIn to the BUY/SHORT variable if you wish to scale in (increase the size of) LONG/SHORT positions.
  • Assign sigScaleOut to the BUY/SHORT variable if you intend to scale out (decrease the size of) LONG/SHORT positions.

For in-depth learning about AFL coding and creating your trading systems, click here.

AFL Overview

Preferred TimeframeNo Constraint
Indicators UsedMACD, Signal
PositionsLong only
Buy ConditionMACD crosses above the Signal line
Sell ConditionMACD crosses below the Signal line
Stop LossNo fixed Stoploss
TargetsNo fixed target
Position Size– Initial Position size (150 fixed)
– Increase position size by 150 with every 100 points gain since Buy.
– Decrease position size by 75 with every 50 points loss since Buy.
Initial Equity100,000
Brokerage50 per order

AFL Code

//  Formula Name:    Anti-Martingale Trading system
//  Website:

_SECTION_BEGIN("Anti Martingale Trading Syatem");

SetTradeDelays( 1, 1, 1, 1 );
SetOption( "InitialEquity", 100000);
SetOption("FuturesMode" ,True);
SetOption( "AllowPositionShrinking", True );

//Specify ScaleIn and ScaleOut parameters

//Buy and Sell Condition
Buy = Cross( MACD(), Signal() );
Sell = Cross( Signal(), MACD() );


for( i = 1; i < BarCount; i++ ) { Profit[i]=Close[i]-BuyPrice[i]>=ScaleInPoints;

InTrade = Flip( Buy, Sell );

DoScaleIn = InTrade AND Profit;
DoScaleOut= InTrade AND Loss;

Buy = Buy + sigScaleIn * DoScaleIn + sigScaleOut * DoScaleOut;

PositionSize = IIf( DoScaleOut,ScaleOutSize, ScaleInSize); 

Plot( Close, "Price", colorWhite, styleCandle );


PlotShapes(IIf(Cross( MACD(), Signal() ), shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Cross( MACD(), Signal() ), shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Cross( MACD(), Signal() ), shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Cross( Signal(), MACD() ), shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Cross( Signal(), MACD() ), shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Cross( Signal(), MACD() ), shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(IIf(DoScaleIn, shapeSmallUpTriangle, shapeNone),colorBlue, 0, L, Offset=-45);
PlotShapes(IIf(DoScaleOut, shapeSmallDownTriangle, shapeNone),colorBlue, 0, H, Offset=-45);

AFL Screenshot

The AFL screenshot depicts Buy and Sell signals using up and down arrows, respectively. A blue up triangle represents Scale-In, while a blue down triangle signifies Scale-Out.

Witness how the position gradually increases for profitable trades:

AFL Screenshot and Backtest Report

Observe the gradual decrease in position size for loss-making trades:


Backtest Report

Here’s the backtest report for this strategy. Note that the back tester treats trades involving scaling in or out as a SINGLE trade, resulting in a single row in the trade list. The key difference from regular trades is that it calculates average entry and exit prices based on all partial entries and exits, displaying these averages in the respective fields. Commissions are correctly applied to each (partial) entry or exit based on the partial buy/sell size. To delve deeper into the details of scaling, run the backtest in “DETAIL LOG” mode to observe how scaling-in and scaling-out work, along with the calculation of average prices.

NSE Nifty
Initial Capital100,000
Final Capital1,752,936.03
Backtest Period11-Apr-2000 to 23-Feb-2016
Net Profit %1652.94%
Annual Return %19.39%
Number of Trades146
Winning Trade %43.56%
Average Holding Period14.89 periods
Max Consecutive Losses8
Max System % Drawdown-65.87%
Max Trade % Drawdown-85.83%

You can download the detailed backtest report here.

Please note that even better results can be expected if you allow compounding of your returns.

Equity Curve


Additional Amibroker Settings for Backtesting

To specify the lot size and margin requirement, go to Symbol → Information. The screenshot below shows a lot size of 75 and a margin requirement of 10% for NSE Nifty:

Symbol Info Nifty

Leave a Reply