OS Trading Engine
Getting Started
Core Concepts
Positions

Positions

A position represents an active token holding that is being monitored for price changes, stop loss, DCA opportunities, and take-profit levels.


What is a Position?

When an agent executes a buy trade, a position is created. The position tracks:

  • What you bought: Token address and symbol
  • Purchase details: Price, amount, and total invested
  • Current state: Value, P&L, stop loss level
  • DCA history: Additional buys on dips (if DCA enabled)
  • Take-profit progress: Levels hit, realized profit, moon bag status (if take-profit enabled)

Position Properties

PropertyDescription
tokenAddressSolana token mint address
tokenSymbolToken ticker (e.g., BONK)
purchasePriceAverage price per token (weighted after DCAs)
purchaseAmountOriginal tokens purchased
remainingAmountTokens remaining after take-profit sales
totalInvestedSolTotal SOL invested (original + DCAs)
peakPriceHighest price seen (for trailing stop)
currentStopLossPercentageActive stop loss level
dcaCountNumber of DCA buys executed
takeProfitLevelsHitNumber of take-profit levels triggered
realizedProfitSolSOL profit locked in from take-profit sales
moonBagActivatedWhether moon bag has been set aside
moonBagAmountTokens reserved as moon bag

Position Lifecycle

┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   OPENED    │────▶│  MONITORED  │────▶│   CLOSED    │
│             │     │             │     │             │
│ Buy trade   │     │ Price track │     │ Sell trade  │
│ executed    │     │ Stop loss   │     │ executed    │
│             │     │ Take profit │     │             │
│             │     │ DCA eval    │     │             │
└─────────────┘     └─────────────┘     └─────────────┘

Stage 1: Opened

A position is created when:

  1. Signal passes agent eligibility checks
  2. Position size is calculated
  3. Buy trade executes successfully

Stage 2: Monitored

While open, the position is continuously:

  1. Price tracked - Current price fetched from feeds
  2. P&L calculated - Profit/loss computed (realized + unrealized)
  3. Stop loss evaluated - Checked for trigger
  4. Take-profit evaluated - Checked for gain levels (if enabled)
  5. DCA evaluated - Checked for buy opportunity (if enabled; can run alongside take-profit)

Take-profit may trigger partial sales while the position remains open. The position only fully closes when all tokens are sold (or moon bag is the only remainder and stop loss triggers).

Stage 3: Closed

A position closes when:

  1. Stop loss triggers - Price below threshold (sells everything, including moon bag)
  2. Take-profit completes - All levels hit and no moon bag (or moon bag + stop loss)
  3. Manual close - User closes via dashboard/API
  4. Stale trade - Auto-close after idle period (if configured)

Real-Time Monitoring

Positions are monitored with sub-second latency:

Price Updates

Price Feed (Pyth/DexScreener)


  ┌──────────────┐
  │ Price Update │
  │   Manager    │
  └──────┬───────┘


  ┌──────────────┐     ┌──────────────┐
  │ Stop Loss    │     │  WebSocket   │
  │  Evaluator   │     │  Broadcast   │
  └──────────────┘     └──────────────┘

Stop Loss Evaluation

Every price update triggers stop loss evaluation:

  1. Calculate price change from peak
  2. Determine current stop loss threshold
  3. If price ≤ threshold → trigger sell
  4. Update position state

WebSocket Updates

The dashboard receives real-time updates:

{
  "type": "position_update",
  "data": {
    "id": "position-123",
    "current": {
      "priceNative": 0.00000123,
      "priceUsd": 0.00025,
      "valueUsd": 125.50
    },
    "profitLoss": {
      "percent": 15.5,
      "usd": 16.82
    },
    "stopLoss": {
      "percentage": 85
    }
  }
}

Profit & Loss Calculation

Basic P&L

P&L % = ((Current Price - Purchase Price) / Purchase Price) × 100

With DCA

When DCA buys occur, the average purchase price is recalculated:

New Average Price = Total Invested SOL / Total Tokens Held

Example:

EventSOL SpentTokens ReceivedAvg Price
Initial buy0.5 SOL1,000,0000.0000005
DCA buy0.25 SOL625,0000.0000004
Total0.75 SOL1,625,0000.0000004615

With Take-Profit

When take-profit sells occur, profit is tracked in two parts:

Total P&L = Realized Profit (from TP sales) + Unrealized Profit (on remaining tokens)

Example:

EventTokensSOL ReturnedRealized Profit
Initial buy1,000,000-0.5 SOL
TP Level 1 (50% gain)Sell 250,000+0.1875 SOL+0.0625 SOL
TP Level 2 (150% gain)Sell 250,000+0.3125 SOL+0.1875 SOL
Remaining500,000Total realized: 0.25 SOL

The dashboard shows combined P&L: realized profit from take-profit sales + unrealized profit on remaining tokens.


Position States

Healthy Position

  • Price above purchase price
  • Positive P&L
  • Stop loss trailing upward

At-Risk Position

  • Price below purchase price
  • Negative P&L
  • Stop loss may trigger soon

DCA Opportunity (DCA Mode)

  • Price dropped to DCA level
  • Additional buy may execute
  • Average cost will decrease

Take-Profit Opportunity (Take-Profit Mode)

  • Price above next take-profit level
  • Partial sale may execute
  • Realized profit will increase

Moon Bag Active

  • Take-profit has hit trigger level
  • Portion of position reserved permanently
  • Only sold if stop loss triggers or manual close

Viewing Positions

Dashboard

The Positions tab shows:

ColumnDescription
TokenSymbol and address
EntryPurchase price and time
CurrentCurrent price and value
P&LProfit/loss % and USD
Stop LossCurrent stop loss level
ActionsClose button

API

# Get all positions for an agent
curl http://localhost:4000/api/v1/agent-positions/{agentId} \
  -H "Authorization: Bearer <token>"

Response:

[
  {
    "id": "position-123",
    "tokenSymbol": "BONK",
    "purchase": {
      "priceNative": 0.0000005,
      "amount": 1000000
    },
    "current": {
      "priceNative": 0.00000058,
      "valueUsd": 125.50
    },
    "profitLoss": {
      "percent": 16.0,
      "usd": 17.30
    },
    "stopLoss": {
      "percentage": 85,
      "peakPrice": 0.0000006
    }
  }
]

Closing Positions

Manual Close

Via dashboard:

  1. Click on the position
  2. Click Close Position
  3. Select reason (Manual, Take Profit, Stop Loss)
  4. Confirm

Via API:

curl -X POST http://localhost:4000/api/v1/agent-positions/{agentId}/{positionId}/close \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"reason": "manual"}'

Automatic Close

Positions close automatically when:

  1. Stop loss triggers - Price drops below threshold
  2. Stale trade - Position idle for configured duration with small P&L

Historical Swaps

When a position closes, it becomes a Historical Swap record:

FieldDescription
Entry priceOriginal purchase price (weighted average after DCAs)
Exit priceEffective average sale price (across all take-profit + final sale)
AmountOriginal position size (total tokens)
P&L SOLTotal profit/loss in SOL (realized TP + final sale)
P&L USDTotal profit/loss in USD
Hold timeDuration held
Close reasonManual, stop_loss, stale_trade, take_profit

For positions with take-profit sales, the historical swap record reflects the full position: original amount, total P&L across all sales, and an effective average sale price.

Historical swaps are permanent records for performance tracking.


Best Practices

1. Monitor Active Positions

Check positions regularly, especially during volatile markets. Watch take-profit progress and remaining amounts.

2. Understand Stop Loss Behavior

Know at what price your position will sell. Stop loss sells everything, including moon bag.

3. Combine Exit Strategies as Needed

You can enable both DCA (average down on dips) and Take-Profit (lock gains on rises); the engine supports both simultaneously on the same position.

4. Consider Moon Bag Carefully

Moon bag is held indefinitely. Ensure you want that long-term exposure before enabling.

5. Consider DCA Carefully

DCA increases your exposure. Ensure you're comfortable with more capital at risk.

6. Review Historical Swaps

Learn from past trades to improve future performance. Compare DCA vs Take-Profit results.

7. Don't Over-Leverage

Limit the number of concurrent positions based on your total capital.