Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Bitfinex Php Sdk Laravel Package

ewertondaniel/bitfinex-php-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ewertondaniel/bitfinex-php-sdk
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        EwertonDaniel\Bitfinex\BitfinexServiceProvider::class,
    ],
    
  2. Publish Config (if needed):

    php artisan vendor:publish --provider="EwertonDaniel\Bitfinex\BitfinexServiceProvider"
    

    Configure API keys in .env:

    BITFINEX_API_KEY=your_api_key
    BITFINEX_API_SECRET=your_api_secret
    
  3. First Use Case: Fetch platform status (public endpoint):

    use EwertonDaniel\Bitfinex\Facades\Bitfinex;
    
    $status = Bitfinex::public()->platformStatus();
    dd($status->content->status); // "operative" or "maintenance"
    

Where to Look First

  • Public API: Bitfinex::public() for read-only operations (e.g., market data).
  • Authenticated API: Bitfinex::authenticated() for trading/private operations (requires config).
  • Docs: USAGE.md for endpoint-specific examples.

Implementation Patterns

Core Workflows

  1. Public Data Fetching:

    // Get ticker for BTC/USD
    $ticker = Bitfinex::public()->ticker('BTC/USD');
    $lastPrice = $ticker->content->last_price;
    
    // Fetch historical candles (OHLCV)
    $candles = Bitfinex::public()->candles('BTC/USD', '1m', 100);
    
  2. Authenticated Operations:

    // Generate a token (for session management)
    $token = Bitfinex::authenticated()->generateToken();
    
    // Place a new order
    $order = Bitfinex::authenticated()->orders()->newOrder([
        'symbol' => 'BTC/USD',
        'amount' => 0.1,
        'price' => 50000,
        'type' => 'exchange limit',
    ]);
    
  3. Webhook Integration: Use Laravel's queue:work to process Bitfinex webhook payloads:

    // In a controller/middleware
    $payload = json_decode(request()->getContent(), true);
    Bitfinex::authenticated()->webhooks()->validate($payload);
    

Integration Tips

  • Rate Limiting: Bitfinex enforces rate limits. Cache responses aggressively (e.g., Cache::remember).
  • Error Handling:
    try {
        $data = Bitfinex::public()->ticker('INVALID');
    } catch (\EwertonDaniel\Bitfinex\Exceptions\BitfinexException $e) {
        Log::error('Bitfinex API error: ' . $e->getMessage());
        // Fallback logic
    }
    
  • Laravel Queues: Offload long-running tasks (e.g., fetching 1000+ candles) to queues:
    dispatch(new FetchCandlesJob('BTC/USD', '1h', 1000));
    

Common Patterns

Use Case Pattern
Market Data Bitfinex::public()->ticker('symbol') or candles('symbol', 'timeframe', count)
Order Management Bitfinex::authenticated()->orders()->newOrder() + cancelOrder()
Wallet Balances Bitfinex::authenticated()->wallets()->get()
Webhooks Validate payloads via validate() and dispatch events

Gotchas and Tips

Pitfalls

  1. API Key Leaks:

    • Never hardcode keys. Use Laravel's .env and validate with:
      if (!config('bitfinex.api_key')) {
          throw new \RuntimeException('Bitfinex API key not configured.');
      }
      
    • Restrict keys to specific IPs in Bitfinex’s API settings.
  2. Time Synchronization:

    • Bitfinex requires precise timestamps for signed requests. Use:
      use Carbon\Carbon;
      $timestamp = Carbon::now()->timestamp;
      
    • Avoid server clock drift; sync with NTP.
  3. Webhook Validation:

    • Always validate payloads before processing:
      $isValid = Bitfinex::authenticated()->webhooks()->validate($payload);
      if (!$isValid) abort(403, 'Invalid webhook signature');
      
  4. Rate Limit Headers:

    • Check X-RateLimit-Remaining in responses. Implement exponential backoff:
      $remaining = $response->header('X-RateLimit-Remaining');
      if ($remaining <= 10) sleep(1); // Throttle
      

Debugging

  • Enable Debug Mode:
    Bitfinex::setDebug(true); // Logs raw requests/responses
    
  • Common Issues:
    • 403 Forbidden: Invalid API key/secret or incorrect nonce.
    • 429 Too Many Requests: Hit rate limits. Check headers and retry later.
    • 500 Errors: Bitfinex API issues. Monitor status page.

Extension Points

  1. Custom Endpoints: Extend the SDK by creating a new facade method:

    // app/Providers/BitfinexServiceProvider.php
    public function boot()
    {
        Bitfinex::extend('custom', function () {
            return new CustomBitfinexClient();
        });
    }
    

    Then use:

    Bitfinex::custom()->yourMethod();
    
  2. Middleware: Add request/response filters:

    Bitfinex::authenticated()->getClient()->getMiddleware()->push(
        function ($request) {
            $request->withHeader('X-Custom-Header', 'value');
        }
    );
    
  3. Testing: Use the BitfinexMock class for unit tests:

    $mock = new BitfinexMock();
    $mock->shouldReceive('platformStatus')->andReturn(['status' => 'operative']);
    Bitfinex::swap($mock);
    

Configuration Quirks

  • Environment Variables: Prefix keys with BITFINEX_ (e.g., BITFINEX_API_KEY). Example .env:
    BITFINEX_API_KEY=your_key
    BITFINEX_API_SECRET=your_secret
    BITFINEX_TESTNET=false
    
  • Testnet Support: Enable with:
    Bitfinex::setTestnet(true);
    
    Or in .env:
    BITFINEX_TESTNET=true
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle