Skip to content

Latest commit

 

History

History
307 lines (217 loc) · 8.66 KB

information.md

File metadata and controls

307 lines (217 loc) · 8.66 KB

Trading Bot Foundational Concepts

What is Binance Futures

Binance Futures is a derivatives trading platform that allows traders to speculate on the future price of cryptocurrencies without owning the underlying asset. Unlike spot trading where assets are exchanged directly, futures contracts represent an agreement to buy or sell an asset at a predetermined price at a specified time in the future.

Key characteristics of futures trading include:

  • Leverage: Traders can control larger positions with smaller capital
  • Long and short positions: Profit potential in both rising and falling markets
  • Perpetual contracts: No expiration date, positions can be held indefinitely
  • Funding rates: Periodic payments between long and short traders to keep prices aligned with spot markets

USDT-M vs COIN-M Futures

Binance offers two types of futures contracts differentiated by their settlement currency.

USDT-Margined (USDT-M)

  • Collateral and settlement in USDT (Tether stablecoin)
  • Linear contracts where profit and loss are calculated in USDT
  • Easier to manage portfolio as all positions share the same quote currency
  • Preferred for traders who want stable collateral value
  • More intuitive profit/loss calculation

COIN-Margined (COIN-M)

  • Collateral and settlement in the underlying cryptocurrency (BTC, ETH, etc.)
  • Inverse contracts where profit and loss fluctuate with the coin value
  • Suitable for holders who want to earn more of the base cryptocurrency
  • More complex profit calculations due to collateral value changes
  • Useful for hedging existing cryptocurrency holdings

This project uses USDT-M contracts for straightforward position management and predictable settlement.

Order Types

Market Order

A market order executes immediately at the best available price in the order book. The trader specifies only the quantity, not the price.

Advantages:

  • Guaranteed execution
  • Immediate fill
  • Simple to use

Disadvantages:

  • No price control
  • Potential slippage in volatile markets
  • May receive worse prices for large orders

Use cases:

  • Urgent entries or exits
  • Highly liquid markets
  • When execution speed matters more than price

Limit Order

A limit order specifies both quantity and the exact price at which the trader is willing to buy or sell. The order only executes if the market reaches that price.

Advantages:

  • Price control
  • No slippage
  • Can place orders in advance

Disadvantages:

  • No execution guarantee
  • May miss opportunities if price never reaches limit
  • Requires price prediction

Use cases:

  • Non-urgent trades
  • Specific entry or exit points
  • Cost-sensitive strategies

Stop-Limit Order

A stop-limit order combines a trigger mechanism with a limit order. When the market reaches the stop price, a limit order is placed at the specified limit price.

Components:

  • Stop price: The trigger price that activates the order
  • Limit price: The price at which the order is placed after triggering

Advantages:

  • Combines trigger logic with price control
  • Useful for breakout strategies
  • Can protect profits or limit losses

Disadvantages:

  • May not execute if market moves too fast past the limit price
  • Requires setting two price parameters
  • More complex to configure

Use cases:

  • Breakout trading
  • Stop-loss with price protection
  • Automated entry at key levels

Testnet vs Mainnet

Testnet

A testnet is a simulated environment that mirrors the production system without using real funds.

Characteristics:

  • Uses simulated or test currency with no real value
  • Identical API endpoints and behavior to production
  • Separate account registration and API keys
  • Data may be reset periodically
  • Lower reliability and occasional downtime

Purpose:

  • Development and debugging
  • Strategy testing
  • API integration validation
  • Learning without financial risk

Mainnet

The mainnet is the live production environment where real transactions occur.

Characteristics:

  • Real funds at risk
  • Higher reliability and uptime guarantees
  • Stricter rate limits and security measures
  • Permanent transaction records
  • Actual market liquidity and participants

Transition considerations:

  • Thoroughly test on testnet before mainnet deployment
  • Verify all error handling works correctly
  • Confirm API key permissions are appropriately restricted
  • Start with small position sizes

API Authentication Basics

Binance API uses a key-based authentication system with two components.

API Key

  • A public identifier for your account
  • Sent with every request in the header
  • Used by Binance to identify the requester
  • Can be shared in logs without security risk

API Secret

  • A private key known only to the account holder
  • Used to sign requests cryptographically
  • Never transmitted directly to the server
  • Must be kept confidential at all times

Request Signing

For authenticated endpoints, requests are signed using HMAC SHA256:

  1. Construct the query string with all parameters
  2. Add a timestamp parameter
  3. Generate HMAC SHA256 hash using the secret key
  4. Append the signature to the request

Security Best Practices

  • Store credentials in environment variables, not source code
  • Use separate API keys for different applications
  • Enable IP restrictions when possible
  • Set appropriate permission levels (read-only vs trading)
  • Rotate keys periodically
  • Never commit credentials to version control

Risk Controls at API Level

Binance implements several mechanisms to prevent excessive losses and protect traders.

Position Limits

  • Maximum position size per symbol
  • Total account exposure limits
  • Leverage restrictions based on position size

Order Limits

  • Maximum order quantity per request
  • Minimum notional value requirements
  • Price deviation limits from mark price

Rate Limits

  • Request limits per minute
  • Order placement limits per second
  • Weight-based limits for different endpoint types

Margin and Liquidation

  • Initial margin requirements to open positions
  • Maintenance margin to keep positions open
  • Automatic liquidation when margin falls below threshold
  • Insurance fund to cover liquidation shortfalls

Account-Level Controls

  • Withdraw whitelist addresses
  • Two-factor authentication
  • API key permissions (enable/disable trading, withdrawals)
  • IP address restrictions

Why Logging is Critical in Trading Systems

Logging serves essential functions in automated trading systems beyond standard software debugging.

Audit Trail

  • Record of every order placed and response received
  • Evidence for dispute resolution
  • Compliance with regulatory requirements
  • Accountability for trading decisions

Debugging and Troubleshooting

  • Identify why orders failed
  • Track API response codes and messages
  • Diagnose connectivity issues
  • Understand system behavior during incidents

Performance Analysis

  • Measure execution latency
  • Track fill rates and slippage
  • Analyze order rejection reasons
  • Identify patterns in API behavior

Risk Management

  • Detect anomalous trading activity
  • Monitor position sizes and exposure
  • Track error rates and system health
  • Alert on critical failures

Recovery and Reconciliation

  • Reconstruct system state after failures
  • Verify orders against exchange records
  • Identify missing or duplicate orders
  • Support account reconciliation

Best Practices

  • Log timestamps with millisecond precision
  • Include unique identifiers for correlation
  • Separate log files by severity or function
  • Implement log rotation to manage disk space
  • Secure logs containing sensitive information
  • Retain logs according to compliance requirements

CLI-Based Trading Advantages

Command-line interfaces offer distinct benefits for trading applications.

Simplicity

  • No graphical dependencies
  • Minimal resource consumption
  • Fast startup time
  • Easy to understand and modify

Automation

  • Scriptable with shell commands
  • Integrates with cron jobs and schedulers
  • Pipeable output for further processing
  • Combinable with other command-line tools

Remote Access

  • Works over SSH connections
  • No graphical environment required
  • Suitable for server deployment
  • Low bandwidth requirements

Reproducibility

  • Commands can be saved and repeated
  • Exact parameters are visible and documented
  • Easy to share configurations
  • Version controllable

Development Efficiency

  • Rapid iteration without UI changes
  • Direct parameter manipulation
  • Immediate feedback loop
  • Focus on core logic

Reliability

  • Fewer failure points than graphical interfaces
  • No dependency on display servers
  • Consistent behavior across environments
  • Easier to test programmatically

Use Cases

  • Automated trading scripts
  • Server-side deployment
  • Quick manual interventions
  • Testing and development
  • Integration with larger systems