Page cover

Example: Creating and Running a Swarm Optimization

Example: Creating and Running a Swarm Optimization

# 1. Start the Julia server in one terminal
cd julia
julia --project=. julia_server.jl

# 2. Run the interactive CLI in another terminal
node packages/cli/interactive.cjs

# 3. From the interactive menu:
# - Select "🧬 Swarm Intelligence"
# - Select "Create Swarm"
# - Enter a name for your swarm (e.g., "OptimizationSwarm")
# - Select an algorithm (e.g., "DE" for Differential Evolution)
# - Enter swarm configuration as JSON (can use {} for defaults)
# - Select "Run Optimization"
# - Define your objective function (e.g., "function(x) return x[1]^2 + x[2]^2 end")
# - Enter optimization parameters (bounds, population size, etc.)
# - View the results when optimization completes

Alternatively, you can use the Python wrapper:

import asyncio
from juliaos import JuliaOS

async def run_optimization():
    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create a swarm
    swarm = await juliaos_client.swarms.create_swarm(
        name="OptimizationSwarm",
        algorithm="DE",
        config={
            "population_size": 50,
            "crossover_rate": 0.8,
            "mutation_factor": 0.5
        }
    )

    # Run optimization
    result = await juliaos_client.swarms.run_optimization(
        swarm_id=swarm["id"],
        objective_function="function(x) return sum(x.^2) end",
        parameters={
            "bounds": [(-10, 10), (-10, 10), (-10, 10)],
            "max_iterations": 100
        }
    )

    print(f"Best position: {result['best_position']}")
    print(f"Best fitness: {result['best_fitness']}")

    await juliaos_client.disconnect()

asyncio.run(run_optimization())

#### Complete Trading Workflow

Here's a concrete example of the complete trading flow:

1. **Create a Trading Agent**:
   - From the main menu, select "👤 Agent Management"
   - Choose "Create Agent"
   - Enter a name (e.g., "ETH-USDT Trader")
   - Select "Trading" as the agent type
   - Configure the agent with a strategy (e.g., momentum, mean reversion)

2. **Set Up a Wallet**:
   - From the main menu, select "💼 Wallet Management"
   - Choose "Create Wallet" or "Connect Wallet"
   - Enter wallet details (name, blockchain network)

3. **Execute a Trade**:
   - From Agent Management, use the "Trade Now" quick action
   - OR from the main menu, select "💱 Trading" then "⚡ Quick Trade"
   - Select your trading agent and wallet
   - Choose the trading pair (e.g., ETH/USDT)
   - Specify buy/sell and quantity
   - Review and confirm the trade

4. **Monitor Results**:
   - From the Trading menu, select "📜 View Trade History"
   - Check the status and details of your executed trades

The trading functionality provides:
- Agent-based trading execution
- Support for multiple blockchain networks (Ethereum, Polygon, Solana, Arbitrum, Optimism, Avalanche, BSC, Base)
- Integration with various DEXes (Uniswap V2/V3, SushiSwap, PancakeSwap, QuickSwap, TraderJoe, Raydium)
- Market and limit order types with advanced order features
- Trade history tracking and visualization with performance analytics
- Real-time market data with multiple price sources
- Seamless workflow between agent creation and trading
- Risk management with position sizing and stop-loss mechanisms

You can also use the Python wrapper to access the trading functionality:

```python
import asyncio
from juliaos import JuliaOS

async def execute_trade():
    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create a trading agent
    agent = await juliaos_client.agents.create_agent(
        name="ETH-USDT Trader",
        agent_type="trading",
        config={
            "strategy": "momentum",
            "risk_level": "medium",
            "max_position_size": 1000
        }
    )

    # Create or connect a wallet
    wallet = await juliaos_client.wallets.create_wallet(
        name="Trading Wallet",
        wallet_type="local",
        network="ethereum"
    )

    # Execute a trade
    result = await juliaos_client.trading.execute_trade(
        agent_id=agent["id"],
        wallet_id=wallet["id"],
        network="ethereum",
        pair="ETH/USDT",
        order_type="market",
        side="buy",
        quantity=0.1,
        dex="uniswap_v3",
        slippage=1.0,
        gas_multiplier=1.0
    )

    print(f"Trade executed: {result['transaction_id']}")
    print(f"Status: {result['status']}")
    print(f"Executed price: {result['executed_price']}")

    # Get trade history
    history = await juliaos_client.trading.get_trade_history(
        agent_id=agent["id"],
        limit=10
    )
    print(f"Trade history: {len(history['trades'])} trades found")

    await juliaos_client.disconnect()

# Execute the trade
asyncio.run(execute_trade())

Last updated