PHPackages                             mahdimsr/laravel-bitunix-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. mahdimsr/laravel-bitunix-api

ActiveLibrary[API Development](/categories/api)

mahdimsr/laravel-bitunix-api
============================

composer package for using bitunix api trading

1.1.0(5mo ago)011[3 PRs](https://github.com/mahdimsr/laravel-bitunix-api/pulls)MITPHPPHP ^8.4CI passing

Since Sep 29Pushed 1mo agoCompare

[ Source](https://github.com/mahdimsr/laravel-bitunix-api)[ Packagist](https://packagist.org/packages/mahdimsr/laravel-bitunix-api)[ Docs](https://github.com/mahdimsr/laravel-bitunix-api)[ GitHub Sponsors](https://github.com/msr)[ RSS](/packages/mahdimsr-laravel-bitunix-api/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (12)Versions (7)Used By (0)

Laravel Bitunix API Package
===========================

[](#laravel-bitunix-api-package)

A Laravel package for interacting with the Bitunix cryptocurrency exchange API.

---

[![Latest Stable Version](https://camo.githubusercontent.com/ece9124c1eb4afd34df9e5bd8ffb06d4a7d315a1f2ec893544e9097e8fbdd3db/68747470733a2f2f706f7365722e707567782e6f72672f6d616864696d73722f6c61726176656c2d626974756e69782d6170692f762f737461626c65)](https://packagist.org/packages/msr/laravel-bitunix-api)[![Fix PHP code style issues](https://github.com/mahdimsr/laravel-bitunix-api/actions/workflows/fix-php-code-style-issues.yml/badge.svg)](https://github.com/mahdimsr/laravel-bitunix-api/actions/workflows/fix-php-code-style-issues.yml)[![PHPStan](https://github.com/mahdimsr/laravel-bitunix-api/actions/workflows/phpstan.yml/badge.svg)](https://github.com/mahdimsr/laravel-bitunix-api/actions/workflows/phpstan.yml)[![run-tests](https://github.com/mahdimsr/laravel-bitunix-api/actions/workflows/run-tests.yml/badge.svg)](https://github.com/mahdimsr/laravel-bitunix-api/actions/workflows/run-tests.yml)[![License](https://camo.githubusercontent.com/92d886cdb90df1c6273044db8cec8dd8adadd06e66dd832d3e3b257f19cc82f2/68747470733a2f2f706f7365722e707567782e6f72672f6d616864696d73722f6c61726176656c2d626974756e69782d6170692f6c6963656e7365)](https://packagist.org/packages/msr/laravel-bitunix-api)

Installation
------------

[](#installation)

```
composer require mahdimsr/laravel-bitunix-api
```

Configuration
-------------

[](#configuration)

### 1. Environment Variables

[](#1-environment-variables)

Add the following variables to your `.env` file:

```
BITUNIX_API_KEY=your-api-key-here
BITUNIX_API_SECRET=your-api-secret-here
BITUNIX_LANGUAGE=en-US
```

### 2. Publish Configuration (Optional)

[](#2-publish-configuration-optional)

```
php artisan vendor:publish --tag=bitunix-api-config
```

### 3. Verify Configuration

[](#3-verify-configuration)

Run the configuration check script:

```
php scripts/check-config.php
```

Usage
=====

[](#usage)

Using Facade Class
------------------

[](#using-facade-class)

```
$response = \Msr\LaravelBitunixApi\Facades\LaravelBitunixApi::changeLeverage('BTCUSDT', 'USDT', 12);
```

Using implemented contracts class
---------------------------------

[](#using-implemented-contracts-class)

```
$api = new \Msr\LaravelBitunixApi\LaravelBitunixApi();
$response = $api->changeLeverage('BTCUSDT', 'USDT', 12);
```

Using Contracts
---------------

[](#using-contracts)

which bind in package service provide (`LaravelBitunixApiServiceProvider`)

### Change Leverage

[](#change-leverage)

```
use Msr\LaravelBitunixApi\Requests\ChangeLeverageRequestContract;

$api = app(ChangeLeverageRequestContract::class);
$response = $api->changeLeverage('BTCUSDT', 'USDT', 12);

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    if ($data['code'] === 0) {
        echo "Leverage changed successfully!";
    }
}
```

### Change Margin Mode

[](#change-margin-mode)

```
use Msr\LaravelBitunixApi\Requests\ChangeMarginModeRequestContract;

$api = app(ChangeMarginModeRequestContract::class);
$response = $api->changeMarginMode('BTCUSDT', 'USDT', 'ISOLATION');

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    if ($data['code'] === 0) {
        echo "Margin mode changed successfully!";
    }
}
```

### Place Order

[](#place-order)

```
use Msr\LaravelBitunixApi\Requests\PlaceOrderRequestContract;

$api = app(PlaceOrderRequestContract::class);

// Basic market order
$response = $api->placeOrder('BTCUSDT', '0.1', 'BUY', 'OPEN', 'MARKET');

// Limit order with take profit and stop loss
$response = $api->placeOrder(
    'BTCUSDT',
    '0.1',
    'BUY',
    'OPEN',
    'LIMIT',
    '50000',        // price
    null,           // positionId
    'GTC',          // effect
    'order-123',   // clientId
    false,          // reduceOnly
    '51000',        // tpPrice
    'MARK_PRICE',   // tpStopType
    'LIMIT',        // tpOrderType
    '51000.1',      // tpOrderPrice
    '49000',        // slPrice
    'MARK_PRICE',   // slStopType
    'LIMIT',        // slOrderType
    '49000.1'       // slOrderPrice
);

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    if ($data['code'] === 0) {
        echo "Order placed successfully!";
        echo "Order ID: " . $data['data']['orderId'];
    }
}
```

### Flash Close Position

[](#flash-close-position)

```
use Msr\LaravelBitunixApi\Requests\FlashClosePositionRequestContract;

$api = app(FlashClosePositionRequestContract::class);
$response = $api->flashClosePosition('19848247723672');

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    if ($data['code'] === 0) {
        echo "Position flash closed successfully!";
        echo "Position ID: " . $data['data']['positionId'];
    }
}
```

### Get Pending Positions

[](#get-pending-positions)

```
use Msr\LaravelBitunixApi\Requests\GetPendingPositionsRequestContract;

$api = app(GetPendingPositionsRequestContract::class);

// Get all pending positions
$response = $api->getPendingPositions();

// Get positions by symbol
$response = $api->getPendingPositions('BTCUSDT');

// Get specific position by ID
$response = $api->getPendingPositions(null, '19848247723672');

// Get positions with both symbol and position ID
$response = $api->getPendingPositions('BTCUSDT', '19848247723672');

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    if ($data['code'] === 0) {
        echo "Positions retrieved successfully!";
        foreach ($data['data'] as $position) {
            echo "Position ID: " . $position['positionId'];
            echo "Symbol: " . $position['symbol'];
            echo "Side: " . $position['side'];
            echo "Unrealized PnL: " . $position['unrealizedPNL'];
        }
    }
}
```

### Get Single Account

[](#get-single-account)

```
use Msr\LaravelBitunixApi\Requests\GetSingleAccountRequestContract;

$api = app(GetSingleAccountRequestContract::class);
$response = $api->getSingleAccount('USDT');

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    if ($data['code'] === 0) {
        $account = $data['data'][0];
        echo "Account retrieved successfully!";
        echo "Margin Coin: " . $account['marginCoin'];
        echo "Available: " . $account['available'];
        echo "Frozen: " . $account['frozen'];
        echo "Margin: " . $account['margin'];
        echo "Transfer: " . $account['transfer'];
        echo "Position Mode: " . $account['positionMode'];
        echo "Cross Unrealized PnL: " . $account['crossUnrealizedPNL'];
        echo "Isolation Unrealized PnL: " . $account['isolationUnrealizedPNL'];
        echo "Bonus: " . $account['bonus'];
    }
}
```

### Place TP/SL Order

[](#place-tpsl-order)

```
use Msr\LaravelBitunixApi\Requests\PlaceTpSlOrderRequestContract;

$api = app(PlaceTpSlOrderRequestContract::class);

// Place TP/SL order with both take profit and stop loss
$response = $api->placeTpSlOrder(
    'BTCUSDT',          // symbol
    '111',              // positionId
    '50000',            // tpPrice
    'LAST_PRICE',       // tpStopType
    '45000',            // slPrice
    'LAST_PRICE',       // slStopType
    'LIMIT',            // tpOrderType
    '50000.1',          // tpOrderPrice
    'LIMIT',            // slOrderType
    '45000.1',          // slOrderPrice
    '1',                // tpQty
    '1'                 // slQty
);

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    if ($data['code'] === 0) {
        echo "TP/SL order placed successfully!";
        echo "Order ID: " . $data['data']['orderId'];
    }
}
```

### Place Position TP/SL Order

[](#place-position-tpsl-order)

```
use Msr\LaravelBitunixApi\Requests\PlacePositionTpSlOrderRequestContract;

$api = app(PlacePositionTpSlOrderRequestContract::class);

// Place position TP/SL order with both take profit and stop loss
$response = $api->placePositionTpSlOrder(
    'BTCUSDT',          // symbol
    '111',              // positionId
    '50000',            // tpPrice
    'LAST_PRICE',       // tpStopType
    '45000',            // slPrice
    'LAST_PRICE'        // slStopType
);

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    if ($data['code'] === 0) {
        echo "Position TP/SL order placed successfully!";
        echo "Order ID: " . $data['data']['orderId'];
    }
}
```

### Get Future Kline Data

[](#get-future-kline-data)

```
use Msr\LaravelBitunixApi\Requests\FutureKLineRequestContract;

$api = app(FutureKLineRequestContract::class);
$response = $api->getFutureKline('BTCUSDT', '1h', 100);

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);
    // Process kline data
}
```

API Methods
-----------

[](#api-methods)

### Account Management

[](#account-management)

- `changeLeverage(string $symbol, string $marginCoin, int $leverage)` - Change leverage
- `changeMarginMode(string $symbol, string $marginCoin, string $marginMode)` - Change margin mode
- `getSingleAccount(string $marginCoin)` - Get account details for specific margin coin

### Trading

[](#trading)

- `placeOrder(...)` - Place a new order with full support for all order types, take profit, stop loss, and position management
- `placeTpSlOrder(...)` - Place TP/SL order for existing positions
- `placePositionTpSlOrder(...)` - Place position TP/SL order (closes position at market price when triggered)
- `flashClosePosition(string $positionId)` - Flash close position by position ID

### Position Management

[](#position-management)

- `getPendingPositions(?string $symbol, ?string $positionId)` - Get pending positions with optional filtering

### Market Data

[](#market-data)

- `getFutureKline(string $symbol, string $interval, int $limit, ?int $startTime, ?int $endTime, string $type)` - Get kline data

Configuration Options
---------------------

[](#configuration-options)

OptionDescriptionDefault`future_base_uri`Bitunix API base URI`https://fapi.bitunix.com/``api_key`Your API keyFrom `BITUNIX_API_KEY` env var`api_secret`Your API secretFrom `BITUNIX_API_SECRET` env var`language`API languageFrom `BITUNIX_LANGUAGE` env var or `en-US`Rate Limits
-----------

[](#rate-limits)

- **Change Leverage**: 10 req/sec/uid
- **Change Margin Mode**: 10 req/sec/uid
- **Get Single Account**: 10 req/sec/uid
- **Place Order**: 10 req/sec/uid
- **Place TP/SL Order**: 10 req/sec/uid
- **Place Position TP/SL Order**: 10 req/sec/uid
- **Flash Close Position**: 5 req/sec/uid
- **Get Pending Positions**: 10 req/sec/uid

Error Handling
--------------

[](#error-handling)

All methods return a `ResponseInterface` object. Check the response status and parse the JSON response:

```
$response = $api->changeLeverage('BTCUSDT', 'USDT', 12);

if ($response->getStatusCode() === 200) {
    $data = json_decode($response->getBody()->getContents(), true);

    if ($data['code'] === 0) {
        // Success
        echo "Operation successful: " . $data['msg'];
    } else {
        // API Error
        echo "API Error: " . $data['msg'];
    }
} else {
    // HTTP Error
    echo "HTTP Error: " . $response->getStatusCode();
}
```

Testing
-------

[](#testing)

Run the test suite:

```
vendor/bin/pest
```

Run specific tests:

```
vendor/bin/pest tests/ChangeLeverageTest.php
vendor/bin/pest tests/ChangeMarginModeTest.php
vendor/bin/pest tests/GetSingleAccountTest.php
vendor/bin/pest tests/PlaceOrderTest.php
vendor/bin/pest tests/PlaceTpSlOrderTest.php
vendor/bin/pest tests/PlacePositionTpSlOrderTest.php
vendor/bin/pest tests/FlashClosePositionTest.php
vendor/bin/pest tests/GetPendingPositionsTest.php
vendor/bin/pest tests/HeaderTest.php
```

Examples
--------

[](#examples)

See the `examples/` directory for complete usage examples:

- `ChangeLeverageExample.php`
- `ChangeMarginModeExample.php`
- `GetSingleAccountExample.php`
- `PlaceOrderExample.php`
- `PlaceTpSlOrderExample.php`
- `PlacePositionTpSlOrderExample.php`
- `FlashClosePositionExample.php`
- `GetPendingPositionsExample.php`

Troubleshooting
---------------

[](#troubleshooting)

### API credentials not loading from .env

[](#api-credentials-not-loading-from-env)

1. Make sure your `.env` file is in the project root
2. Check that the variable names match exactly (case-sensitive)
3. Restart your application/server after changing .env
4. Clear config cache: `php artisan config:clear`

### Signature generation fails

[](#signature-generation-fails)

1. Verify API key and secret are correct
2. Check that the credentials have the necessary permissions
3. Ensure your system time is synchronized

Security
--------

[](#security)

- Never commit API credentials to version control
- Use environment variables for all sensitive data
- Restrict API key permissions to minimum required
- Regularly rotate API keys

License
-------

[](#license)

MIT License. See LICENSE file for details.

Support
-------

[](#support)

For issues and questions, please create an issue on the GitHub repository.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance82

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~55 days

Total

2

Last Release

171d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/716cd921611db607a27dc99662762d525ac140f8cc9ea230ec4af166b1353bd8?d=identicon)[mahdimsr](/maintainers/mahdimsr)

---

Top Contributors

[![mahdimsr](https://avatars.githubusercontent.com/u/32928013?v=4)](https://github.com/mahdimsr "mahdimsr (56 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laravelmsrlaravel-bitunix-api

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mahdimsr-laravel-bitunix-api/health.svg)

```
[![Health](https://phpackages.com/badges/mahdimsr-laravel-bitunix-api/health.svg)](https://phpackages.com/packages/mahdimsr-laravel-bitunix-api)
```

###  Alternatives

[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.0k7.8M57](/packages/dedoc-scramble)[scalar/laravel

Render your OpenAPI-based API reference

6183.9k2](/packages/scalar-laravel)[ryangjchandler/bearer

Minimalistic token-based authentication for Laravel API endpoints.

8129.8k](/packages/ryangjchandler-bearer)[combindma/laravel-facebook-pixel

Meta pixel integration for Laravel

4956.9k](/packages/combindma-laravel-facebook-pixel)[stechstudio/laravel-hubspot

A Laravel SDK for the HubSpot CRM Api

2971.0k](/packages/stechstudio-laravel-hubspot)[njoguamos/laravel-plausible

A laravel package for interacting with plausible analytics api.

208.8k](/packages/njoguamos-laravel-plausible)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
