Skip to content

2016–2025 · Five markets · $100,000 starting equity

The Original Turtle Trading Rules

Both original Turtle systems lost money on the four CFD markets tested. The FTMO portfolio replay produced 0 passes across 144 complete windows. Adding a synthetic two-sided Bitcoin leg produced maximum drawdowns of at least 78.2% across the two systems.

There are two original entry systems

We tested the original rules published by Curtis Faith. System 1 and System 2 use standard 2N stops and manage long and short positions. The separately published Whipsaw stop is outside this comparison. Each system receives the full starting balance in its own simulation because the source leaves allocation between the two systems to the trader. Original Turtle Rules

  1. System 1. Enter one tick outside the preceding 20-session range after the last completed theoretical 20-session breakout in that market was a loser. Evaluate that previous breakout even when no position was taken, and use the same market's last outcome regardless of its direction. A winner reaches a profitable opposite 10-session exit before a move of 2N against the position. When the filter skips the 20-session entry, use the 55-session failsafe. Exit on an opposite 10-session breakout. System 1 filter clarification
  2. System 2. Enter every eligible break of the preceding 55-session range, one tick beyond the channel. Exit on an opposite 20-session breakout. Gap fills use the opening quote.
  3. Size by volatility. Calculate N from true range with a 20-session seed and Wilder smoothing. One N per unit targets 1% of the sizing allocation before rounding. The simulation locks completed N for the week, preserves the entry week's N for each campaign's stops and adds, and rounds down to the contract increment.
  4. Pyramid and move the stops. Add a unit every favorable 0.5N from the previous fill, up to four. Put a stop 2N from each fill and move older stops 0.5N toward profit with each add. Stops can diverge after gaps. Four evenly spaced units can lose about 5% of sizing capital from their fills to their stops before costs and gaps.
  5. Cap positions by direction. Allow four units per market, six in a closely correlated group, ten in a loosely correlated group and twelve in total. Gold/silver and the two US indices are close groups in the replay. In the five-market diagnostic, both indices plus BTC are one loose group. When entries coincide, rank same-time candidates by breakout distance in N.

The sizing ledger uses the 20% notional cut after a 10% loss, then another cut after each additional loss equal to 10% of the reduced allocation. It restores the base on recovery and estimates the discretionary annual renewal by starting each year at the previous marked equity. It evaluates these changes at the next strategy session. Open campaigns keep the lot size selected at entry. Curtis Faith, chapters 3–7

What happened to $100,000

On the four CFD proxies, System 1 finished at $20,754.52 and System 2 at $23,612.29. The largest modeled portfolio exposure was 12.71× equity for System 1. Drawdowns are shown at session close and along the assumed intrabar path.

Ten-year $100,000 portfolio outcomes
Rules and marketsFinal equityTotal returnCAGRSession DDPath DDPeak gross exposure / equityClosed campaignsClosed units
System 1 · 4 CFDs$20,754.52-79.25%-14.56%-88.09%-88.72%12.71×4171117
System 2 · 4 CFDs$23,612.29-76.39%-13.45%-94.69%-94.98%11.85×232656
System 1 · CFDs + BTC proxy$289,360.99+189.36%+11.21%-80.68%-81.73%12.96×5061386
System 2 · CFDs + BTC proxy$2,017,126.74+1917.13%+35.04%-78.25%-78.74%8.67×305855

System 2 with BTC ended at $2,017,126.74 under base assumptions, $2,240,652.54 under the opposite intrabar path and $16,720.78 with twice the modeled costs. The result depends heavily on how hourly BTC candles are translated into intrabar fills and on the viability of borrowing BTC. A BTC short requires borrowing or a derivative. Coinbase spot margin eligibility and mechanics

Fills and cost sensitivity; entry and risk rules held fixed
Rules and marketsBase 10-year returnOpposite price path2× costs2022–20252022–2025 at 2× costsLate CAGR block range
System 1 · 4 CFDs-79.25%-72.50%-97.45%-25.57%-72.22%-40.72% to +41.31%
System 2 · 4 CFDs-76.39%-76.37%-97.75%+1.92%-51.09%-35.98% to +54.90%
System 1 · CFDs + BTC proxy+189.36%+124.29%-92.58%+102.94%-71.02%-31.34% to +125.74%
System 2 · CFDs + BTC proxy+1917.13%+2140.65%-83.28%+19.90%-61.35%-36.48% to +87.28%

The 2022–2025 slice starts flat with warmed indicators and a fully warmed System 1 hypothetical ledger. The block range is based on 1,000 resamples of 20-session blocks. This retrospective slice and its range describe sample sensitivity. The public JSON contains realized long and short contributions, trade campaign counts, profits, losses, cost and annual returns.

Personal account decision. Keep the $100,000 account out of this implementation with these markets and size rules. The two CFD results lost most of the starting capital. The BTC simulation adds dependence on borrowing, assumed fills and costs, with drawdowns of at least 78.2%.
Four panels. Both systems lose money on four CFDs but finish higher with BTC included. Both universes show deep session drawdowns; the equity chart uses a log scale.
Equity and drawdown. Four-CFD and BTC-inclusive equity, matched buy-and-hold benchmarks and session drawdowns. All paths use the published primary OHLC sequencing assumption. Download PNG
Grouped bars compare S1, S2 and buy and hold from 2016 to 2025. The passive benchmark has unusually large peaks when BTC is included.
Annual returns. Returns at calendar year-end, including the matched buy-and-hold comparison. Panels have separate scales. Download PNG
Heatmap. All full runs are negative with costs doubled. Switching the assumed OHLC order changes the magnitude of the BTC-inclusive results.
Sensitivity to costs and fills. Net total returns across primary, fresh late period, cost stress and opposite OHLC path when available. Download PNG
Grouped columns show long and short realized P&L for each instrument. BTC makes a large contribution in the mixed-market tests. The four-CFD runs contain sizable short-side losses.
P&L by market and direction. Net P&L from closed unit legs in USD by instrument and side. The open positions at the horizon are excluded. Download PNG
Stacked bars for two systems and both FTMO evaluation types. Most attempts breached daily loss, and neither system passed the full evaluation.
FTMO outcomes. First terminal evaluation outcome by quarterly start. Includes cohorts shortened by the end of available data. Download PNG

FTMO portfolio replay

The simulator restarted each system flat at every quarterly start, with $100,000 and the same original risk settings. It applied the current 1-Step and 2-Step international CFD objectives to the four CFD proxies. Of 144 complete one-year windows, 0 passed and 144 breached. The 365 days are a study horizon. The model checks equity on the M5 price path, with daily limits reset at Prague midnight. Verification starts with fresh starting capital at the next Prague midnight. The 1-Step screen includes the Consistency rule for new orders after the October 2026 update. FTMO trading objectives

Portfolio objective outcomes, $100,000 USD
SystemFTMO trackQuarterly startsFull windowsPassedBreachedOpen at day 365Median days to breachChallenge passes, all starts
System 11-Step4036036010.70
System 12-Step4036036021.71
System 21-Step4036036011.90
System 22-Step4036036024.11

Peak gross exposure shows that broker margin could reject orders in some portfolios. The replay applies modeled spreads, funding and commissions and uses no broker margin admission or liquidation. Definitive results require FTMO ticks, symbol terms and order rules. The Swing account is available through 2-Step and permits overnight and weekend holds subject to the other conditions. Instrument specifications · FTMO Swing rules

Data and test assumptions

Gold, silver, US 500 and Nasdaq 100 use five-minute Dukascopy bid/ask OHLC via EV Trading Labs. BTC uses hourly Coinbase Exchange trade OHLC with a modeled 10 bp spread. The index series have shorter observation hours early in the sample. Session labels close at 17:00 New York, with earlier dates used to warm up signals. The historical instruments are proxies for modern execution. There is no futures contract roll series, exchange margin series, dividend adjustment or cash interest. The passive comparison tracks the unlevered equal-initial-weight price series.

Historical input coverage
MarketFirst sessionLast sessionBar minutesBarsSpread
XAUUSD2016-01-042025-12-315708,764Observed
XAGUSD2016-01-042025-12-315707,686Observed
USA500IDXUSD2016-01-042025-12-315625,785Observed
USATECHIDXUSD2016-01-042025-12-315626,000Observed
BTCUSD2016-01-012025-12-316087,622Modeled

With OHLC bars the exact sequence of prices is unavailable. Base runs traverse open, low, high, close in each bar. The sensitivity run traverses open, high, low, close. Trade ledgers use synthetic time offsets to preserve that order and cannot establish real tick times. Long and short fills add modeled slippage of 1 bp per side. CFD commissions use 0.5 bp per side, and BTC uses a 60 bp per-side Exchange taker fee scenario. Both directions incur a modeled funding debit of 2 bp of notional per elapsed calendar day. Real swap can be a debit or credit, and different jurisdictions and brokers have different borrowing and margin terms. EV Trading Labs · Coinbase candles · Coinbase Exchange fees

Free Python and MQL5 source

Python reproduces the shared-account research, tests, downloadable figures and FTMO screen. The MT5 EA runs on broker D1 candles and has its own broker execution and account setup. Follow its supplied instructions before testing. The published backtest numbers come from Python.

Read the full MQL5 source
#property strict
#property version "1.00"
#property description "Original Turtle rules research EA, based on Curtis Faith (2003)"

#include <Trade/Trade.mqh>

// https://www.tradingwithrayner.com/wp-content/uploads/2014/11/OriginalTurtleRules.pdf
enum TurtleSystem { System1 = 1, System2 = 2 };
input TurtleSystem InpSystem = System2;
input double InpUnitPercent = 1.0;       // One N, not the 2N protective stop.
input double InpAccountAllocation = 100.0;
input double InpYearNotional = 0.0;      // Account currency. Zero uses allocated first observed balance.
input bool InpReduceNotionalOnLoss = true;
input bool InpWeeklySizingSheet = true;  // Refresh N at first session of the broker week.
input int InpMaxUnits = 4;
input int InpMaxDirectionUnits = 12;
input string InpCloseGroup = "";         // Comma-separated exact broker symbols, excluding or including this one.
input string InpLooseGroup = "";
input ulong InpMagic = 83552001;
input double InpMaxSpreadN = 0.15;       // Zero disables spread cap.
input double InpMarginPctFree = 50.0;
input uint InpDeviationPoints = 10;
input bool InpAllowOrdersOutsideTester = false;

struct Bands
{
   double hi10, lo10, hi20, lo20, hi55, lo55;
};

CTrade g_trade;
Bands g_bands;
double g_tick_size, g_daily_n, g_sizing_n, g_previous, g_campaign_n, g_last_fill;
double g_shadow_price, g_shadow_n, g_year_balance, g_year_notional, g_worst_year_loss;
int g_shadow_side, g_campaign_side, g_used_units, g_year;
bool g_previous_winner, g_tester, g_chart_last, g_restored, g_exit_all;
datetime g_day, g_week;
string g_key, g_account_key, g_lock, g_close_group, g_loose_group;

string GroupKey(string group)
{
   StringReplace(group, " ", "");
   StringToUpper(group);
   return "," + group + ",";
}

uint NameHash(const string value)
{
   uint result = 2166136261;
   for(int i = 0; i < StringLen(value); ++i)
      result = (uint)((result ^ (uint)StringGetCharacter(value, i)) * 16777619);
   return result;
}

int OnInit()
{
   if(InpUnitPercent <= 0 || InpUnitPercent > 100 || InpAccountAllocation <= 0 || InpAccountAllocation > 100 ||
      InpYearNotional < 0 || InpMaxUnits < 1 || InpMaxUnits > 4 || InpMaxDirectionUnits < 1 ||
      InpMaxDirectionUnits > 12 || InpMagic == 0 || InpMaxSpreadN < 0 || InpMarginPctFree <= 0 || InpMarginPctFree > 100)
      return INIT_PARAMETERS_INCORRECT;
   if(AccountInfoInteger(ACCOUNT_MARGIN_MODE) != ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
   {
      Print("Original Turtles: select an MT5 hedging account for separate unit stops.");
      return INIT_FAILED;
   }
   g_tester = MQLInfoInteger(MQL_TESTER) != 0;
   g_chart_last = SymbolInfoInteger(_Symbol, SYMBOL_CHART_MODE) == SYMBOL_CHART_MODE_LAST;
   g_tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   g_close_group = GroupKey(InpCloseGroup);
   g_loose_group = GroupKey(InpLooseGroup);
   g_account_key = StringFormat("OT.%I64d.%I64u.%08X", AccountInfoInteger(ACCOUNT_LOGIN), InpMagic,
                                NameHash(AccountInfoString(ACCOUNT_SERVER)));
   g_lock = g_account_key + ".lock";
   g_key = g_account_key + StringFormat(".%08X", NameHash(_Symbol));
   g_trade.SetExpertMagicNumber(InpMagic);
   g_trade.SetDeviationInPoints(InpDeviationPoints);
   g_trade.SetAsyncMode(false);
   g_trade.SetMarginMode();
   if(g_tick_size <= 0 || _Point <= 0 || !g_trade.SetTypeFillingBySymbol(_Symbol))
      return INIT_FAILED;
   if(!g_tester && InpAllowOrdersOutsideTester && !GlobalVariableCheck(g_lock) && !GlobalVariableTemp(g_lock))
      return INIT_FAILED;
   Print("Original Turtles: uses completed broker D1 bars, one system per symbol and magic.");
   return INIT_SUCCEEDED;
}

bool TradingEnabled()
{
   return g_tester || (InpAllowOrdersOutsideTester && TerminalInfoInteger(TERMINAL_CONNECTED) &&
          TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED) &&
          AccountInfoInteger(ACCOUNT_TRADE_ALLOWED) && AccountInfoInteger(ACCOUNT_TRADE_EXPERT));
}

double TrueRange(const MqlRates &bar, const double previous_close)
{
   return MathMax(bar.high - bar.low, MathMax(bar.high - previous_close, previous_close - bar.low));
}

Bands PreviousBands(const MqlRates &bars[], const int end)
{
   Bands bands;
   bands.hi10 = bands.hi20 = bands.hi55 = bars[end-1].high;
   bands.lo10 = bands.lo20 = bands.lo55 = bars[end-1].low;
   for(int i = 2; i <= 55; ++i)
   {
      double hi = bars[end-i].high;
      double lo = bars[end-i].low;
      if(i <= 10)
      {
         bands.hi10 = MathMax(bands.hi10, hi);
         bands.lo10 = MathMin(bands.lo10, lo);
      }
      if(i <= 20)
      {
         bands.hi20 = MathMax(bands.hi20, hi);
         bands.lo20 = MathMin(bands.lo20, lo);
      }
      bands.hi55 = MathMax(bands.hi55, hi);
      bands.lo55 = MathMin(bands.lo55, lo);
   }
   return bands;
}

datetime WeekKey(const datetime day)
{
   MqlDateTime stamp = {};
   TimeToStruct(day, stamp);
   int after_monday = (stamp.day_of_week + 6) % 7;
   stamp.hour = stamp.min = stamp.sec = 0;
   return StructToTime(stamp) - after_monday * 86400;
}

double LongTrigger(const double high) { return high + g_tick_size; }
double ShortTrigger(const double low) { return low - g_tick_size; }
bool AtOrAbove(const double value, const double level) { return value >= level - g_tick_size * 1e-6; }
bool AtOrBelow(const double value, const double level) { return value <= level + g_tick_size * 1e-6; }

void SettleShadow(const bool winner)
{
   g_shadow_side = 0;
   g_previous_winner = winner;
}

void StartShadow(const int side, const double price, const double n)
{
   g_shadow_side = side;
   g_shadow_price = price;
   g_shadow_n = n;
}

void SeedShadowDay(const MqlRates &bar, const Bands &bands, const double n)
{
   if(g_shadow_side != 0)
   {
      double stop = g_shadow_price - g_shadow_side * 2.0 * g_shadow_n;
      if(g_shadow_side == 1)
      {
         double channel = ShortTrigger(bands.lo10);
         if(AtOrBelow(bar.open, MathMax(stop, channel)))
            SettleShadow(bar.open > g_shadow_price);
         else if(AtOrBelow(bar.low, MathMax(stop, channel)))
            SettleShadow(channel > g_shadow_price);
      }
      else
      {
         double channel = LongTrigger(bands.hi10);
         if(AtOrAbove(bar.open, MathMin(stop, channel)))
            SettleShadow(bar.open < g_shadow_price);
         else if(AtOrAbove(bar.high, MathMin(stop, channel)))
            SettleShadow(channel < g_shadow_price);
      }
      return;
   }
   double up = LongTrigger(bands.hi20), down = ShortTrigger(bands.lo20);
   bool hit_up = AtOrAbove(bar.high, up), hit_down = AtOrBelow(bar.low, down);
   // An opening gap establishes sequence. Otherwise skip a historical day with both breakouts.
   int side = AtOrAbove(bar.open, up) || (hit_up && !hit_down) ? 1 :
              (AtOrBelow(bar.open, down) || (hit_down && !hit_up) ? -1 : 0);
   if(side == 0)
      return;
   double entry = side == 1 ? MathMax(bar.open, up) : MathMin(bar.open, down);
   StartShadow(side, entry, n);
   // A same-day touch of the adverse barrier is assumed to follow the historical entry.
   if(side == 1 && AtOrBelow(bar.low, MathMax(entry-2*n, ShortTrigger(bands.lo10))))
      SettleShadow(false);
   if(side == -1 && AtOrAbove(bar.high, MathMin(entry+2*n, LongTrigger(bands.hi10))))
      SettleShadow(false);
}

bool RefreshLevels()
{
   datetime day = iTime(_Symbol, PERIOD_D1, 0);
   if(day == 0)
      return false;
   if(day == g_day)
      return true;
   MqlRates bars[];
   int requested = (g_day == 0 && InpSystem == System1) ? 850 : 260;
   int count = CopyRates(_Symbol, PERIOD_D1, 1, requested, bars);
   if(count < 55 || bars[count-1].time >= day || !SeriesInfoInteger(_Symbol, PERIOD_D1, SERIES_SYNCHRONIZED))
      return false;
   double n = 0, weekly_n = 0;
   datetime prior_week = 0;
   for(int i = 1; i < count; ++i)
   {
      datetime week = WeekKey(bars[i].time);
      if(week != prior_week)
      {
         prior_week = week;
         weekly_n = n;
      }
      if(g_day == 0 && InpSystem == System1 && i >= 55 && n > 0)
         SeedShadowDay(bars[i], PreviousBands(bars, i), InpWeeklySizingSheet && weekly_n > 0 ? weekly_n : n);
      double tr = TrueRange(bars[i], bars[i-1].close);
      n = i <= 20 ? n + tr / 20.0 : (19.0 * n + tr) / 20.0;
   }
   if(n <= 0)
      return false;
   if(g_day == 0 && g_tester)
      g_previous = bars[count-1].close;
   g_bands = PreviousBands(bars, count);
   g_day = day;
   g_daily_n = n;
   datetime week = WeekKey(day);
   if(g_week != week)
   {
      g_week = week;
      g_sizing_n = InpWeeklySizingSheet && week == prior_week && weekly_n > 0 ? weekly_n : n;
   }
   if(!InpWeeklySizingSheet)
      g_sizing_n = g_daily_n;
   return g_sizing_n > 0;
}

int Breakout(const double quote, const double previous, const double high, const double low)
{
   double up = LongTrigger(high), down = ShortTrigger(low);
   if(!AtOrAbove(previous, up) && AtOrAbove(quote, up))
      return 1;
   if(!AtOrBelow(previous, down) && AtOrBelow(quote, down))
      return -1;
   return 0;
}

int UpdateShadow(const double quote, const double previous)
{
   if(g_shadow_side == 1)
   {
      if(AtOrBelow(quote, MathMax(g_shadow_price-2*g_shadow_n, ShortTrigger(g_bands.lo10))))
         SettleShadow(quote > g_shadow_price);
      return 0;
   }
   if(g_shadow_side == -1)
   {
      if(AtOrAbove(quote, MathMin(g_shadow_price+2*g_shadow_n, LongTrigger(g_bands.hi10))))
         SettleShadow(quote < g_shadow_price);
      return 0;
   }
   if(previous <= 0)
      return 0;
   int signal = Breakout(quote, previous, g_bands.hi20, g_bands.lo20);
   if(signal != 0)
      StartShadow(signal, quote, g_sizing_n);
   return signal;
}

int SelectUnits(ulong &tickets[], int &side)
{
   ArrayResize(tickets, 0);
   side = 0;
   for(int i = PositionsTotal()-1; i >= 0; --i)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0 || PositionGetString(POSITION_SYMBOL) != _Symbol || (ulong)PositionGetInteger(POSITION_MAGIC) != InpMagic)
         continue;
      int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
      if(side != 0 && side != direction)
         return -1;
      side = direction;
      int size = ArraySize(tickets);
      ArrayResize(tickets, size+1);
      tickets[size] = ticket;
   }
   return ArraySize(tickets);
}

bool CheckCaps(const int side, const int active)
{
   if(active >= InpMaxUnits)
      return false;
   int direction_count = 0, close_count = 0, loose_count = 0;
   for(int i = PositionsTotal()-1; i >= 0; --i)
   {
      if(PositionGetTicket(i) == 0 || (ulong)PositionGetInteger(POSITION_MAGIC) != InpMagic)
         continue;
      int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
      if(direction != side)
         continue;
      direction_count++;
      string symbol = PositionGetString(POSITION_SYMBOL);
      if(symbol == _Symbol || StringFind(g_close_group, GroupKey(symbol)) >= 0)
         close_count++;
      if(symbol == _Symbol || StringFind(g_loose_group, GroupKey(symbol)) >= 0)
         loose_count++;
   }
   for(int i = OrdersTotal()-1; i >= 0; --i)
      if(OrderGetTicket(i) != 0 && (ulong)OrderGetInteger(ORDER_MAGIC) == InpMagic)
         return false;
   return direction_count < InpMaxDirectionUnits && close_count < 6 && loose_count < 10;
}

void UpdateYearlyLoss(const datetime now)
{
   MqlDateTime stamp = {};
   TimeToStruct(now, stamp);
   double balance = AccountInfoDouble(ACCOUNT_BALANCE);
   string year_key = g_account_key + StringFormat(".%d", stamp.year);
   if(g_year != stamp.year)
   {
      g_year = stamp.year;
      g_year_balance = balance;
      g_worst_year_loss = 0;
      if(!g_tester && !GlobalVariableGet(year_key+".bal", g_year_balance))
         GlobalVariableSet(year_key+".bal", g_year_balance = balance);
      g_year_notional = InpYearNotional > 0 ? InpYearNotional : g_year_balance * InpAccountAllocation / 100.0;
   }
   double prior = g_worst_year_loss;
   if(!g_tester)
      GlobalVariableGet(year_key+".loss", prior);
   double loss = g_year_balance-balance;
   g_worst_year_loss = loss <= 0 ? 0 : MathMax(prior, loss);
   if(!g_tester && prior != g_worst_year_loss)
      GlobalVariableSet(year_key+".loss", g_worst_year_loss);
}

double YearlyNotional()
{
   double notional = g_year_notional;
   if(!InpReduceNotionalOnLoss)
      return notional;
   double threshold = 0;
   for(int i = 0; i < 50 && notional > 0; ++i)
   {
      threshold += .1 * notional;
      if(g_worst_year_loss < threshold)
         return notional;
      notional *= .8;
   }
   return 0;
}

double RoundStop(const double price, const int side)
{
   double ticks = price / g_tick_size;
   return NormalizeDouble((side == 1 ? MathFloor(ticks+1e-9) : MathCeil(ticks-1e-9)) * g_tick_size, _Digits);
}

bool ValidStop(const double stop, const int side, const MqlTick &tick, const bool modifies)
{
   long points = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   if(modifies)
      points = (long)MathMax(points, SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL));
   double distance = side == 1 ? tick.bid-stop : stop-tick.ask;
   return stop > 0 && distance > 0 && distance >= points*_Point;
}

double UnitLots(const int side, const double n, const double quote)
{
   ENUM_ORDER_TYPE order = side == 1 ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   double minimum = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maximum = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double target = YearlyNotional() * InpUnitPercent / 100.0;
   double free = AccountInfoDouble(ACCOUNT_MARGIN_FREE) * InpMarginPctFree / 100.0;
   double loss = 0, margin = 0;
   double adverse = quote - side*n;
   if(minimum <= 0 || step <= 0 || target <= 0 || free <= 0 || adverse <= 0 ||
      !OrderCalcProfit(order, _Symbol, minimum, quote, adverse, loss) || loss >= 0 ||
      !OrderCalcMargin(order, _Symbol, minimum, quote, margin) || margin <= 0)
      return 0;
   double unit_limit = MathMin(maximum, target * minimum / -loss);
   double broker_limit = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_LIMIT);
   if(broker_limit > 0)
   {
      double already = 0;
      for(int i = PositionsTotal()-1; i >= 0; --i)
         if(PositionGetTicket(i) != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol &&
            (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1) == side)
            already += PositionGetDouble(POSITION_VOLUME);
      unit_limit = MathMin(unit_limit, broker_limit-already);
   }
   if(unit_limit < minimum)
      return 0;
   double lots = NormalizeDouble(minimum + MathFloor((unit_limit-minimum)/step+1e-9) * step, 8);
   if(!OrderCalcProfit(order, _Symbol, lots, quote, adverse, loss) || -loss > target+1e-8 ||
      !OrderCalcMargin(order, _Symbol, lots, quote, margin) || margin > free+1e-8)
      return 0;
   return lots;
}

void StoreCampaign()
{
   if(g_tester)
      return;
   GlobalVariableSet(g_key+".side", g_campaign_side);
   GlobalVariableSet(g_key+".last", g_last_fill);
   GlobalVariableSet(g_key+".n", g_campaign_n);
   GlobalVariableSet(g_key+".units", g_used_units);
   GlobalVariablesFlush();
}

void RestoreCampaign(const int side, const int active)
{
   if(g_restored)
      return;
   g_restored = true;
   if(g_tester || active == 0)
      return;
   double saved_side=0, n=0, last=0, units=0;
   if(GlobalVariableGet(g_key+".side", saved_side) && GlobalVariableGet(g_key+".n", n) &&
      GlobalVariableGet(g_key+".last", last) && GlobalVariableGet(g_key+".units", units) &&
      (int)saved_side == side && n > 0 && last > 0 && units >= active && units <= InpMaxUnits)
   {
      g_campaign_side = side;
      g_campaign_n = n;
      g_last_fill = last;
      g_used_units = (int)units;
   }
   else
      Print("Original Turtles: campaign add state unavailable. Existing stops and channel exits remain active.");
}

bool TradeDone(const bool sent)
{
   uint code = g_trade.ResultRetcode();
   return sent && (code == TRADE_RETCODE_DONE || code == TRADE_RETCODE_DONE_PARTIAL || code == TRADE_RETCODE_NO_CHANGES);
}

void CloseUnits(const ulong &tickets[])
{
   for(int i = 0; i < ArraySize(tickets); ++i)
      if(PositionSelectByTicket(tickets[i]) && !TradeDone(g_trade.PositionClose(tickets[i], InpDeviationPoints)))
         PrintFormat("Original Turtles close ticket %I64u: %u", tickets[i], g_trade.ResultRetcode());
}

bool AllowedOrder(const int side)
{
   long mode = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE);
   long flags = SymbolInfoInteger(_Symbol, SYMBOL_ORDER_MODE);
   return (mode == SYMBOL_TRADE_MODE_FULL || (side == 1 && mode == SYMBOL_TRADE_MODE_LONGONLY) ||
          (side == -1 && mode == SYMBOL_TRADE_MODE_SHORTONLY)) &&
          (flags & SYMBOL_ORDER_MARKET) != 0 && (flags & SYMBOL_ORDER_SL) != 0;
}

ulong FindNewTicket(const ulong &older[])
{
   for(int i = PositionsTotal()-1; i >= 0; --i)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0 || PositionGetString(POSITION_SYMBOL) != _Symbol ||
         (ulong)PositionGetInteger(POSITION_MAGIC) != InpMagic)
         continue;
      bool seen = false;
      for(int j = 0; j < ArraySize(older) && !seen; ++j)
         seen = older[j] == ticket;
      if(!seen)
         return ticket;
   }
   return 0;
}

void AddUnit(const int side, const MqlTick &tick, const ulong &old_tickets[])
{
   int active = ArraySize(old_tickets);
   if(!AllowedOrder(side) || !CheckCaps(side, active))
      return;
   double n = active == 0 ? g_sizing_n : g_campaign_n;
   double price = side == 1 ? tick.ask : tick.bid;
   if(n <= 0 || (InpMaxSpreadN > 0 && tick.ask-tick.bid > InpMaxSpreadN*n))
      return;
   double stop = RoundStop(price-side*2*n, side);
   double lots = ValidStop(stop, side, tick, false) ? UnitLots(side, n, price) : 0;
   if(lots <= 0)
      return;
   string comment = StringFormat("OT-S%d-U%d", (int)InpSystem, active == 0 ? 1 : g_used_units+1);
   bool sent = side == 1 ? g_trade.Buy(lots, _Symbol, price, stop, 0, comment) :
                          g_trade.Sell(lots, _Symbol, price, stop, 0, comment);
   if(!TradeDone(sent))
   {
      PrintFormat("Original Turtles unit: %u %s", g_trade.ResultRetcode(), g_trade.ResultRetcodeDescription());
      // Some exchange venues acknowledge the order before filling. Disable adds until flat.
      if(g_trade.ResultRetcode() == TRADE_RETCODE_PLACED)
         g_campaign_n = 0;
      return;
   }
   if(active == 0)
   {
      g_campaign_n = n;
      g_campaign_side = side;
      g_used_units = 0;
   }
   g_used_units++;
   g_last_fill = g_trade.ResultPrice();
   ulong new_ticket = FindNewTicket(old_tickets);
   MqlTick latest = {};
   if(!SymbolInfoTick(_Symbol, latest))
      latest = tick;
   if(PositionSelectByTicket(new_ticket))
   {
      g_last_fill = PositionGetDouble(POSITION_PRICE_OPEN);
      double actual_stop = RoundStop(g_last_fill-side*2*n, side);
      if(MathAbs(actual_stop-PositionGetDouble(POSITION_SL)) >= g_tick_size*.5 &&
         (!ValidStop(actual_stop, side, latest, true) || !TradeDone(g_trade.PositionModify(new_ticket, actual_stop, 0))))
         g_exit_all = true;
   }
   if(g_last_fill <= 0 || new_ticket == 0)
      g_campaign_n = 0;
   for(int i=0; i<active; ++i)
   {
      if(!PositionSelectByTicket(old_tickets[i]))
         continue;
      double prior = PositionGetDouble(POSITION_SL);
      string prefix = StringFormat("OT-S%d-U", (int)InpSystem);
      string label = PositionGetString(POSITION_COMMENT);
      int sequence = StringFind(label, prefix) == 0 ? (int)StringToInteger(StringSubstr(label, StringLen(prefix))) : 0;
      double unrounded = sequence > 0 && sequence < g_used_units ?
                         PositionGetDouble(POSITION_PRICE_OPEN) + side*(-2.0+.5*(g_used_units-sequence))*n :
                         prior+side*.5*n;
      double raised = RoundStop(unrounded, side);
      raised = side == 1 ? MathMax(raised, prior) : MathMin(raised, prior);
      if(prior > 0 && MathAbs(raised-prior) < g_tick_size*.5)
         continue;
      // Move each earlier stop by half N, even if the newest fill gapped.
      if(prior <= 0 || !ValidStop(raised, side, latest, true) ||
         !TradeDone(g_trade.PositionModify(old_tickets[i], raised, 0)))
         g_exit_all = true;
   }
   StoreCampaign();
   if(g_exit_all)
   {
      ulong current[];
      int direction = 0;
      if(SelectUnits(current, direction) > 0)
         CloseUnits(current);
   }
}

void PlaceWithCaps(const int side, const MqlTick &tick, const ulong &tickets[])
{
   if(!g_tester && !GlobalVariableSetOnCondition(g_lock, 1, 0))
      return;
   AddUnit(side, tick, tickets);
   if(!g_tester)
      GlobalVariableSet(g_lock, 0);
}

void OnTick()
{
   MqlTick tick = {};
   if(!SymbolInfoTick(_Symbol, tick) || tick.bid <= 0 || tick.ask < tick.bid || !RefreshLevels())
      return;
   double quote = g_chart_last ? tick.last : tick.bid;
   if(quote <= 0)
      return;
   double previous = g_previous;
   g_previous = quote;
   int s1 = InpSystem == System1 ? UpdateShadow(quote, previous) : 0;
   if(!TradingEnabled())
      return;
   UpdateYearlyLoss(tick.time);
   ulong tickets[];
   int side = 0;
   int active = SelectUnits(tickets, side);
   if(active < 0)
      return;
   RestoreCampaign(side, active);
   if(active > 0)
   {
      double exit_low = InpSystem == System1 ? g_bands.lo10 : g_bands.lo20;
      double exit_high = InpSystem == System1 ? g_bands.hi10 : g_bands.hi20;
      if(g_exit_all || (side == 1 && AtOrBelow(quote, ShortTrigger(exit_low))) ||
         (side == -1 && AtOrAbove(quote, LongTrigger(exit_high))))
      {
         g_exit_all = true;
         CloseUnits(tickets);
         return;
      }
      double add_trigger = g_last_fill + side*.5*g_campaign_n;
      // Compare on the traded side of the quote, and space all units from actual fills.
      bool add = side == 1 ? AtOrAbove(tick.ask, add_trigger) : AtOrBelow(tick.bid, add_trigger);
      if(g_campaign_side == side && g_campaign_n > 0 && g_used_units < InpMaxUnits && add)
         PlaceWithCaps(side, tick, tickets);
      return;
   }
   g_exit_all = false;
   g_campaign_side = 0;
   g_campaign_n = g_last_fill = 0;
   g_used_units = 0;
   if(previous <= 0)
      return;
   int signal = InpSystem == System2 || g_previous_winner ? Breakout(quote, previous, g_bands.hi55, g_bands.lo55) : s1;
   if(signal != 0)
      PlaceWithCaps(signal, tick, tickets);
}